From 36ca7a3d34d9f8a7f91ff65ab05765027aacb425 Mon Sep 17 00:00:00 2001 From: BELLIER Sacha Date: Sun, 24 Nov 2024 14:33:34 +0100 Subject: [PATCH 01/42] wip: move to C++23 --- BUILD.bazel | 8 +++---- MODULE.bazel | 1 + README.md | 6 +----- premake5.lua | 61 ---------------------------------------------------- 4 files changed, 6 insertions(+), 70 deletions(-) delete mode 100644 premake5.lua diff --git a/BUILD.bazel b/BUILD.bazel index 2d3733d6..4ac952a0 100644 --- a/BUILD.bazel +++ b/BUILD.bazel @@ -8,8 +8,8 @@ cc_library( hdrs = glob([ "src/**/*.h" ]), includes = [ "src/" ], copts = select({ - "@rules_cc//cc/compiler:msvc-cl": ["/std:c++20"], - "//conditions:default": ["-std=c++20"], + "@rules_cc//cc/compiler:msvc-cl": ["/std:c++23"], + "//conditions:default": ["-std=c++23"], }), strip_include_prefix = "src", include_prefix = "StreamFormat", @@ -21,8 +21,8 @@ cc_test( name = "StreamFormatTests", srcs = glob([ "Tests/**/*.h", "Tests/**/*.cpp" ]), copts = select({ - "@rules_cc//cc/compiler:msvc-cl": ["/std:c++20"], - "//conditions:default": ["-std=c++20"], + "@rules_cc//cc/compiler:msvc-cl": ["/std:c++23"], + "//conditions:default": ["-std=c++23"], }), deps = [ ":StreamFormat" ], visibility = ["//visibility:public"], diff --git a/MODULE.bazel b/MODULE.bazel index 25f5dbb0..be47f62a 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -29,6 +29,7 @@ winlibs_toolchain_extension.winlibs_toolchain(name = "winlibs") winlibs_toolchain_extension.winlibs_toolchain(name = "pthread-winlibs", linklibs = [ "pthread" ]) use_repo(winlibs_toolchain_extension, "winlibs") use_repo(winlibs_toolchain_extension, "pthread-winlibs") +# register_toolchains("@winlibs//:gcc-toolchain") # register_toolchains("@winlibs//:clang-toolchain") buildbuddy_toolchain_extension = use_extension("@bazel_buildbuddy//:rules.bzl", "buildbuddy_toolchain_extension") diff --git a/README.md b/README.md index 93925ca3..a7ee7133 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ # StreamFormat -StreamFormat is a C++20 String Formatter, like [<fmt>](https://github.com/fmtlib/fmt) +StreamFormat is a C++23 String Formatter, like [<fmt>](https://github.com/fmtlib/fmt) Using this formatter, it define others functionalities: - Logger like [spdlog](https://github.com/gabime/spdlog) - Json Serializer @@ -29,9 +29,5 @@ It can be used using [Bazel](https://bazel.build/). A `cc_library` rule has been created: `@StreamFormat//:StreamFormat`. You need to add the module `streamformat` to your dependencies. -You will need at least to give an c++ standard to use (at least c++20) since no one have been forced. You can check the [bazelrc](.bazelrc) to see how you can add one. - -Not Recommended: There is also a [Premake](https://premake.github.io/docs/using-premake) configuration, thought it is deprecated (and run on a wrapper of mine: [PremakeUtilities](https://github.com/0-Sacha/PremakeUtilities)). I keep it for my Game Engine [Blackbird](https://github.com/0-Sacha/Blackbird) which is using `Premake` as Build system. - ## Examples You can check the [Examples](Examples/README.md) to see what you can do with this. diff --git a/premake5.lua b/premake5.lua deleted file mode 100644 index b8b071ae..00000000 --- a/premake5.lua +++ /dev/null @@ -1,61 +0,0 @@ - --- TODO:bazel remove Solution.Projects Infos: -Solution.Projects["StreamFormat"].PlatformDefineName = "STREAMFORMAT" -Solution.Projects["StreamFormat"].Type = "StaticLib" -Solution.Projects["StreamFormat"].IncludeDirs = { - "%{Solution.Projects.StreamFormat.Path}/src/" -} - -project "StreamFormat" - kind (Solution.Projects["StreamFormat"].Type) - language "C++" - cppdialect "C++20" - - Solution.HighWarnings() - - targetdir (Solution.Path.ProjectTargetDirectory) - objdir (Solution.Path.ProjectObjectDirectory) - - files { - "src/**.h", - "src/**.inl", - "src/**.cpp", - } - - Solution.Project("StreamFormat") - - defines { - "STREAMFORMAT_BASE_LOGGER_NAME=\"%{Solution.Name}\"" - } - -if (StreamFormatTestsEnable) -then - -Solution.AddProject("StreamFormatTests", Solution.Projects["StreamFormat"].Path) -Solution.Projects["StreamFormatTests"].ProjectDependencies = { - "StreamFormat" -} - -StreamFormatTestsLaunch = {} -StreamFormatTestsLaunch.Project = "StreamFormatTests" -Solution.Launch["StreamFormatTests"] = StreamFormatTestsLaunch - -project "StreamFormatTests" - kind (Solution.Projects["StreamFormatTests"].Type) - language "C++" - cppdialect "C++20" - - Solution.HighWarnings() - - targetdir (Solution.Path.ProjectTargetDirectory) - objdir (Solution.Path.ProjectObjectDirectory) - - files { - "Tests/**.h", - "Tests/**.hpp", - "Tests/**.inl", - "Tests/**.cpp", - } - - Solution.Project("StreamFormatTests") -end From e990ac15b05d8533debfbd0bb756a863f07c195c Mon Sep 17 00:00:00 2001 From: BELLIER Sacha Date: Sun, 24 Nov 2024 19:55:36 +0100 Subject: [PATCH 02/42] wip: use std::expected for error handling --- src/StreamFormat/Core/CompilerInfo.h | 23 ---- src/StreamFormat/Core/{Core.h => Prelude.h} | 24 ++-- src/StreamFormat/FMT/Buffer/BufferInfo.h | 2 +- src/StreamFormat/FMT/Buffer/BufferManip.h | 92 +++------------- .../BufferOutManager/BasicBufferOutManager.h | 12 +- .../DynamicBufferOutManager.h | 18 +-- .../BufferOutManager/GivenBufferOutManager.h | 8 +- .../BufferOutManager/StaticBufferOutManager.h | 7 +- src/StreamFormat/FMT/Buffer/BufferOutManip.h | 92 +++++++--------- src/StreamFormat/FMT/Buffer/BufferReadManip.h | 70 ++++++------ src/StreamFormat/FMT/Buffer/BufferTestManip.h | 66 +++++------ .../FMT/Buffer/BufferWriteManip.h | 46 ++++---- .../FMT/Buffer/FMTBufferOutManip.h | 34 +++--- .../FMT/Buffer/FMTBufferReadManip.h | 34 +++--- .../FMT/Buffer/FMTBufferWriteManip.h | 40 ++++--- .../FMT/Buffer/Utils/BufferGlobberManip.h | 6 +- .../FMT/Buffer/Utils/BufferShiftManip.h | 16 +-- .../FMT/Buffer/Utils/BufferUtils.h | 60 +++++----- .../Context/BasicContext/BasicArgsInterface.h | 43 ++++---- .../FMT/Context/BasicContext/BasicContext.h | 50 ++++----- .../BasicContext/BasicContextParse-impl.h | 79 +++++++------ .../BasicContext/ITextPropertiesExecutor.h | 50 ++++----- .../BasicContext/TextPropertiesManager-impl.h | 86 +++++++-------- .../BasicContext/TextPropertiesManager.cpp | 75 +++++++------ .../BasicContext/TextPropertiesManager.h | 104 +++++++++--------- .../BasicFormatterExecutor.h | 23 ++-- .../FormatterExecutor/FormatBasics-impl.h | 39 ++++--- .../FormatTextProperties-impl.h | 28 ++--- .../Context/FormatterExecutor/FormatterArgs.h | 94 ++++++++-------- .../FormatterANSITextPropertiesExecutor.h | 96 ++++++++-------- .../FormatterTextPropertiesExecutor.h | 48 ++++---- .../Context/FormatterExecutor/FormatterType.h | 34 +++--- .../FMT/Context/FormatterExecutor/IndexArgs.h | 4 +- .../FMT/Context/FormatterExecutor/NamedArgs.h | 10 +- .../Context/FormatterExecutor/STDEnumerable.h | 6 +- .../FormatterExecutor/UtilityFunctions.h | 36 +++--- .../ParserExecutor/BasicParserExecutor.h | 21 ++-- .../Context/ParserExecutor/ParseBasics-impl.h | 16 +-- .../ParserExecutor/ParseTextProperties-impl.h | 28 ++--- .../FMT/Context/ParserExecutor/ParserArgs.h | 89 ++++++++------- .../ParserANSITextPropertiesExecutor.h | 72 ++++++++---- .../ParserTextPropertiesExecutor.h | 50 ++++----- .../FMT/Context/ParserExecutor/ParserType.h | 11 +- .../Context/ParserExecutor/UtilityFunctions.h | 2 +- src/StreamFormat/FMT/Detail/ConvertTraits.h | 2 +- src/StreamFormat/FMT/Detail/Exception.h | 50 --------- src/StreamFormat/FMT/Detail/FMTResult.h | 26 +++++ src/StreamFormat/FMT/Detail/IndentHandlers.h | 2 +- .../FMT/Detail/{Detail.h => Prelude.h} | 10 +- src/StreamFormat/FMT/Detail/Specifiers.h | 21 ++-- src/StreamFormat/FMT/Detail/TypesTraits.h | 10 +- .../FMT/Serializers/CompilationData.h | 6 +- .../FMT/Serializers/FormatChrono.h | 22 ++-- .../FMT/Serializers/FormatSTDLib.h | 12 +- .../FMT/Serializers/STDContainer/FMT_array.h | 2 +- .../FMT/Serializers/STDContainer/FMT_deque.h | 2 +- .../STDContainer/FMT_forward_list.h | 2 +- .../FMT/Serializers/STDContainer/FMT_list.h | 2 +- .../FMT/Serializers/STDContainer/FMT_map.h | 4 +- .../FMT/Serializers/STDContainer/FMT_queue.h | 2 +- .../FMT/Serializers/STDContainer/FMT_set.h | 4 +- .../FMT/Serializers/STDContainer/FMT_stack.h | 2 +- .../FMT/Serializers/STDContainer/FMT_tuple.h | 10 +- .../STDContainer/FMT_unordered_map.h | 4 +- .../STDContainer/FMT_unordered_set.h | 4 +- .../FMT/Serializers/STDContainer/FMT_vector.h | 2 +- .../FMT/TextProperties/BaseTextProperties.h | 2 +- src/StreamFormat/Json/JsonParser.cpp | 4 +- src/StreamFormat/Json/JsonParser.h | 12 +- src/StreamFormat/Json/JsonSerializer.h | 14 +-- src/StreamFormat/ProfilerManager/Event.h | 2 +- src/StreamFormat/ProfilerManager/Profiler.h | 2 +- 72 files changed, 1017 insertions(+), 1064 deletions(-) delete mode 100644 src/StreamFormat/Core/CompilerInfo.h rename src/StreamFormat/Core/{Core.h => Prelude.h} (59%) delete mode 100644 src/StreamFormat/FMT/Detail/Exception.h create mode 100644 src/StreamFormat/FMT/Detail/FMTResult.h rename src/StreamFormat/FMT/Detail/{Detail.h => Prelude.h} (81%) diff --git a/src/StreamFormat/Core/CompilerInfo.h b/src/StreamFormat/Core/CompilerInfo.h deleted file mode 100644 index 7babe3f2..00000000 --- a/src/StreamFormat/Core/CompilerInfo.h +++ /dev/null @@ -1,23 +0,0 @@ -#pragma once - -#ifndef STREAMFORMAT_DO_NOT_USE_DEFAULT_MACRO -#if defined(__clang__) -#define STREAMFORMAT_COMPILER_CLANG -#elif defined(__GNUC__) || defined(__GNUG__) -#define STREAMFORMAT_COMPILER_GCC -#elif defined(_MSC_VER) -#define STREAMFORMAT_COMPILER_MSVC -#endif - -#ifdef STREAMFORMAT_COMPILER_MSVC -#ifdef _DEBUG -#define STREAMFORMAT_DEBUG -#endif -#endif - -#if defined(STREAMFORMAT_COMPILER_CLANG) || defined(STREAMFORMAT_COMPILER_GCC) -#if !defined(NDEBUG) -#define STREAMFORMAT_DEBUG -#endif -#endif -#endif diff --git a/src/StreamFormat/Core/Core.h b/src/StreamFormat/Core/Prelude.h similarity index 59% rename from src/StreamFormat/Core/Core.h rename to src/StreamFormat/Core/Prelude.h index 3aa614c2..f722589b 100644 --- a/src/StreamFormat/Core/Core.h +++ b/src/StreamFormat/Core/Prelude.h @@ -1,7 +1,5 @@ #pragma once -#include "CompilerInfo.h" - #include #define STREAMFORMAT_DEBUG @@ -32,9 +30,21 @@ #define STREAMFORMAT_DEBUGBREAK() #endif -// NOT USED YET -#define STREAMFORMAT_NODISCARD [[nodiscard]] -#define STREAMFORMAT_INLINE inline +#include +#include +// https://github.com/SerenityOS/serenity/blob/50642f85ac547a3caee353affcb08872cac49456/AK/Try.h +#define SF_TRY(exp) ({ \ + auto __expected = exp; \ + if (not __expected) [[unlikely]] \ + return __expected; \ + __expected.value(); \ + }); + +#define SF_TRY_TERR(exp, transform_error) ({ \ + auto __expected = exp; \ + if (not __expected) [[unlikely]] \ + return __expected.transform_error(transform_error); \ + __expected.value(); \ + }); -#define UNKOWN_TYPE_MESSAGE -#define UNKOWN_TYPE_DEBUG +#define SF_TRY_OR(exp, new_error) SF_TRY_TERR(exp, [](auto){return new_error;}) \ No newline at end of file diff --git a/src/StreamFormat/FMT/Buffer/BufferInfo.h b/src/StreamFormat/FMT/Buffer/BufferInfo.h index 9d535a1a..0e596a78 100644 --- a/src/StreamFormat/FMT/Buffer/BufferInfo.h +++ b/src/StreamFormat/FMT/Buffer/BufferInfo.h @@ -1,6 +1,6 @@ #pragma once -#include "StreamFormat/FMT/Detail/Detail.h" +#include "StreamFormat/FMT/Detail/Prelude.h" namespace StreamFormat::FMT::Detail { diff --git a/src/StreamFormat/FMT/Buffer/BufferManip.h b/src/StreamFormat/FMT/Buffer/BufferManip.h index 65e3cef0..222c9078 100644 --- a/src/StreamFormat/FMT/Buffer/BufferManip.h +++ b/src/StreamFormat/FMT/Buffer/BufferManip.h @@ -1,34 +1,9 @@ #pragma once #include "BufferInfo.h" -#include "StreamFormat/FMT/Detail/Exception.h" namespace StreamFormat::FMT::Detail { - class FMTBufferManipError : public FMTError - { - public: - const char* what() const noexcept override { return "FMTBufferManipError"; } - }; - - struct BufferManipResult - { - bool Result = false; - constexpr inline BufferManipResult(bool result) noexcept : Result(result) {} - constexpr inline operator bool() const noexcept { return Result; } - - bool HasFailed() const noexcept { return !Result; } - - void ThrowIfFailed() const - { - if (Result == false) - throw FMTBufferManipError{}; - } - }; - - template - class BufferManipException; - template class BufferAccess { @@ -43,12 +18,12 @@ namespace StreamFormat::FMT::Detail constexpr inline std::size_t GetBufferRemainingSize() const noexcept { return static_cast(Buffer.BufferEnd - Buffer.CurrentPos); } public: - constexpr inline BufferManipResult CanMoveForward(const std::size_t count = 1) const noexcept { return Buffer.CurrentPos + count <= Buffer.BufferEnd; } - constexpr inline BufferManipResult CanMoveBackward(const std::size_t count = 1) const noexcept { return Buffer.CurrentPos - count >= Buffer.Buffer; } + constexpr inline bool CanMoveForward(const std::size_t count = 1) const noexcept { return Buffer.CurrentPos + count <= Buffer.BufferEnd; } + constexpr inline bool CanMoveBackward(const std::size_t count = 1) const noexcept { return Buffer.CurrentPos - count >= Buffer.Buffer; } - constexpr inline BufferManipResult IsOutOfBound() const noexcept { return Buffer.CurrentPos < Buffer.Buffer || Buffer.CurrentPos >= Buffer.BufferEnd; } - constexpr inline BufferManipResult IsEmpty() const noexcept { return Buffer.CurrentPos >= Buffer.BufferEnd; } - constexpr inline BufferManipResult IsEndOfString() const noexcept { return IsEmpty() || Buffer.Get() == 0; } + constexpr inline bool IsOutOfBound() const noexcept { return Buffer.CurrentPos < Buffer.Buffer || Buffer.CurrentPos >= Buffer.BufferEnd; } + constexpr inline bool IsEmpty() const noexcept { return Buffer.CurrentPos >= Buffer.BufferEnd; } + constexpr inline bool IsEndOfString() const noexcept { return IsEmpty() || Buffer.Get() == 0; } constexpr inline TChar GetNextForce(const std::size_t count = 1) const noexcept { return *(Buffer.CurrentPos + count); } constexpr inline TChar GetPrevForce(const std::size_t count = 1) const noexcept { return *(Buffer.CurrentPos - count); } @@ -62,9 +37,6 @@ namespace StreamFormat::FMT::Detail public: BufferInfo& Buffer; - public: - BufferManipException ThrowIfFailed() { return BufferManipException(Buffer); } - public: constexpr inline void Set(TChar* const buffer, const std::size_t size) noexcept { @@ -84,62 +56,24 @@ namespace StreamFormat::FMT::Detail public: constexpr inline void ForceForward(const std::size_t count = 1) noexcept { Buffer.CurrentPos += count; } - constexpr inline BufferManipResult Forward(const std::size_t count = 1) noexcept + [[nodiscard]] constexpr inline std::expected Forward(const std::size_t count = 1) noexcept { - if (!Access().CanMoveForward(count)) return false; + if (!Access().CanMoveForward(count)) + return std::unexpected(FMTResult::Buffer_OutOfBoundAccess); Buffer.CurrentPos += count; - return true; + return {}; } constexpr inline void ForceBackward(const std::size_t count = 1) noexcept { Buffer.CurrentPos -= count; } - constexpr inline BufferManipResult Backward(const std::size_t count = 1) noexcept + [[nodiscard]] constexpr inline std::expected Backward(const std::size_t count = 1) noexcept { - if (!Access().CanMoveBackward(count)) return false; + if (!Access().CanMoveBackward(count)) + return std::unexpected(FMTResult::Buffer_OutOfBoundAccess); Buffer.CurrentPos -= count; - return true; + return {}; } constexpr inline TChar GetAndForceForward() noexcept { return *Buffer.CurrentPos++; } constexpr inline TChar GetAndForceBackward() noexcept { return *Buffer.CurrentPos--; } }; - - template - class BufferManipException - { - public: - BufferManipException(BufferInfo& buffer) : Buffer(buffer) {} - public: - BufferInfo& Buffer; - - public: - inline void Forward(const std::size_t count = 1) - { - BufferAccess(Buffer).Forward(count).ThrowIfFailed(); - } - inline void Backward(const std::size_t count = 1) - { - BufferAccess(Buffer).Backward(count).ThrowIfFailed(); - } - - inline TChar GetAndForward() - { - BufferAccess(Buffer).CanMoveForward(1).ThrowIfFailed(); - return *Buffer.CurrentPos++; - } - inline TChar GetAndBackward() - { - BufferAccess(Buffer).CanMoveBackward(1).ThrowIfFailed(); - return *Buffer.CurrentPos--; - } - inline TChar GetNext(const std::size_t count = 1) const - { - BufferAccess(Buffer).CanMoveForward(count).ThrowIfFailed(); - return BufferManip(Buffer).GetNextForce(count); - } - inline TChar GetPrev(const std::size_t count = 1) const - { - BufferAccess(Buffer).CanMoveBackward(count).ThrowIfFailed(); - return BufferManip(Buffer).GetPrevForce(count); - } - }; } diff --git a/src/StreamFormat/FMT/Buffer/BufferOutManager/BasicBufferOutManager.h b/src/StreamFormat/FMT/Buffer/BufferOutManager/BasicBufferOutManager.h index d1e78892..03721d90 100644 --- a/src/StreamFormat/FMT/Buffer/BufferOutManager/BasicBufferOutManager.h +++ b/src/StreamFormat/FMT/Buffer/BufferOutManager/BasicBufferOutManager.h @@ -1,15 +1,23 @@ #pragma once -#include "StreamFormat/FMT/Detail/Detail.h" +#include "StreamFormat/FMT/Detail/Prelude.h" #include "StreamFormat/FMT/Buffer/BufferInfo.h" namespace StreamFormat::FMT::Detail { + enum class BufferManagerError + { + StaticMemoryManager, + AllocationFailed, + }; + template class BasicBufferOutManager { public: virtual ~BasicBufferOutManager() = default; + BasicBufferOutManager(BasicBufferOutManager&) = delete; + BasicBufferOutManager& operator=(BasicBufferOutManager&) = delete; protected: virtual void BeginContextImpl() {} @@ -29,7 +37,7 @@ namespace StreamFormat::FMT::Detail virtual std::size_t GetBufferSize() const = 0; public: - virtual bool AddSize(const std::size_t count) = 0; + [[nodiscard]] virtual std::expected AddSize(const std::size_t count) = 0; public: BufferInfoView GetLastGeneratedBufferInfoView() const { return BufferInfoView(GetBuffer(), m_LastGeneratedDataSize); } diff --git a/src/StreamFormat/FMT/Buffer/BufferOutManager/DynamicBufferOutManager.h b/src/StreamFormat/FMT/Buffer/BufferOutManager/DynamicBufferOutManager.h index 3949af13..7a2f2051 100644 --- a/src/StreamFormat/FMT/Buffer/BufferOutManager/DynamicBufferOutManager.h +++ b/src/StreamFormat/FMT/Buffer/BufferOutManager/DynamicBufferOutManager.h @@ -18,7 +18,9 @@ namespace StreamFormat::FMT::Detail m_BufferSize = beginSize; } ~DynamicBufferOutManager() override = default; - + DynamicBufferOutManager(DynamicBufferOutManager&) = delete; + DynamicBufferOutManager& operator=(DynamicBufferOutManager&) = delete; + public: static constexpr std::size_t DEFAULT_BEGIN_SIZE = 128; static constexpr std::size_t GROW_UP_BUFFER_SIZE = 2; @@ -30,8 +32,8 @@ namespace StreamFormat::FMT::Detail std::size_t GetBufferSize() const override { return m_BufferSize; } public: - bool AddSize(const std::size_t count) override { return Resize(count + m_BufferSize); } - bool Resize(const std::size_t targetBufferSize); + [[nodiscard]] std::expected AddSize(const std::size_t count) override { return Resize(count + m_BufferSize); } + [[nodiscard]] std::expected Resize(const std::size_t targetBufferSize); protected: std::unique_ptr m_Buffer; @@ -64,8 +66,9 @@ namespace StreamFormat::FMT::Detail : Base(beginSize) , m_MeanGeneratedSize(beginSize) {} - ~ShrinkDynamicBufferOutManager() override = default; + ShrinkDynamicBufferOutManager(ShrinkDynamicBufferOutManager&) = delete; + ShrinkDynamicBufferOutManager& operator=(ShrinkDynamicBufferOutManager&) = delete; protected: void BeginContextImpl() override { ShrinkIfNeeded(); } @@ -85,7 +88,7 @@ namespace StreamFormat::FMT::Detail }; template - bool DynamicBufferOutManager::Resize(const std::size_t targetBufferSize) + [[nodiscard]] std::expected DynamicBufferOutManager::Resize(const std::size_t targetBufferSize) { std::size_t newBufferSize = targetBufferSize; @@ -97,7 +100,8 @@ namespace StreamFormat::FMT::Detail } CharType* newBuffer = new CharType[newBufferSize]; - if (newBuffer == nullptr) return false; + if (newBuffer == nullptr) + return std::unexpected(BufferManagerError::AllocationFailed); std::memcpy(newBuffer, m_Buffer.get(), std::min(newBufferSize, m_BufferSize)); @@ -106,6 +110,6 @@ namespace StreamFormat::FMT::Detail m_Buffer.reset(newBuffer); m_BufferSize = newBufferSize; - return true; + return {}; } } diff --git a/src/StreamFormat/FMT/Buffer/BufferOutManager/GivenBufferOutManager.h b/src/StreamFormat/FMT/Buffer/BufferOutManager/GivenBufferOutManager.h index 20a366e4..a264da80 100644 --- a/src/StreamFormat/FMT/Buffer/BufferOutManager/GivenBufferOutManager.h +++ b/src/StreamFormat/FMT/Buffer/BufferOutManager/GivenBufferOutManager.h @@ -21,13 +21,19 @@ namespace StreamFormat::FMT::Detail ~GivenBufferOutManager() override = default; + GivenBufferOutManager(GivenBufferOutManager&) = delete; + GivenBufferOutManager& operator=(GivenBufferOutManager&) = delete; + public: CharType* GetBuffer() override { return m_Buffer; } const CharType* GetBuffer() const override { return m_Buffer; } std::size_t GetBufferSize() const override { return m_BufferSize; } public: - bool AddSize(const std::size_t /* count */) override { return false; } + [[nodiscard]] std::expected AddSize(const std::size_t /* count */) override + { + return std::unexpected(BufferManagerError::StaticMemoryManager); + } private: CharType* m_Buffer; diff --git a/src/StreamFormat/FMT/Buffer/BufferOutManager/StaticBufferOutManager.h b/src/StreamFormat/FMT/Buffer/BufferOutManager/StaticBufferOutManager.h index 8631710e..b9372a43 100644 --- a/src/StreamFormat/FMT/Buffer/BufferOutManager/StaticBufferOutManager.h +++ b/src/StreamFormat/FMT/Buffer/BufferOutManager/StaticBufferOutManager.h @@ -9,6 +9,8 @@ namespace StreamFormat::FMT::Detail { public: ~StaticBufferOutManager() override = default; + StaticBufferOutManager(StaticBufferOutManager&) = delete; + StaticBufferOutManager& operator=(StaticBufferOutManager&) = delete; public: CharType* GetBuffer() override { return m_Buffer; } @@ -16,7 +18,10 @@ namespace StreamFormat::FMT::Detail std::size_t GetBufferSize() const override { return Count; } public: - bool AddSize(const std::size_t) override { return false; } + [[nodiscard]] std::expected AddSize(const std::size_t) override + { + return std::unexpected(BufferManagerError::StaticMemoryManager); + } private: CharType m_Buffer[Count]; diff --git a/src/StreamFormat/FMT/Buffer/BufferOutManip.h b/src/StreamFormat/FMT/Buffer/BufferOutManip.h index 49b0ac90..a5f9b461 100644 --- a/src/StreamFormat/FMT/Buffer/BufferOutManip.h +++ b/src/StreamFormat/FMT/Buffer/BufferOutManip.h @@ -31,7 +31,7 @@ namespace StreamFormat::FMT::Detail BasicBufferOutManager* Manager; public: - void SetManager(BasicBufferOutManager& bufferOutManager) + [[nodiscard]] std::expected SetManager(BasicBufferOutManager& bufferOutManager) { Manager = &bufferOutManager; Manager->BeginContext(); @@ -54,83 +54,72 @@ namespace StreamFormat::FMT::Detail BufferOutInfo& Buffer; public: - void SetManager(BasicBufferOutManager& bufferOutManager) + [[nodiscard]] void SetManager(BasicBufferOutManager& bufferOutManager) noexcept { - Buffer.SetManager(bufferOutManager); + return Buffer.SetManager(bufferOutManager); } - void ComputeGeneratedSize() { Buffer.Manager->ComputeGeneratedSize(BufferAccess(Buffer).GetBufferCurrentSize()); } + void ComputeGeneratedSize() noexcept { Buffer.Manager->ComputeGeneratedSize(BufferAccess(Buffer).GetBufferCurrentSize()); } public: - bool AddSize(const std::size_t count) + [[nodiscard]] std::expected AddSize(const std::size_t count) noexcept { - if (Buffer.Manager == nullptr) throw Detail::FMTShouldNotEndHere{}; - if (Buffer.CurrentPos > Buffer.BufferEnd) throw Detail::FMTParseError{}; + if (Buffer.Manager == nullptr) + return std::unexpected(FMTResult::NonValidBuffer); std::size_t currentSize = BufferAccess(Buffer).GetBufferCurrentSize(); - if (Buffer.Manager->AddSize(count) == false) return false; + if (not Buffer.Manager->AddSize(count)) + return std::unexpected(FMTResult::Buffer_UnableToReserveMemory); BufferManip(Buffer).Set(Buffer.Manager->GetBuffer(), Buffer.Manager->GetBufferSize()); Buffer.CurrentPos = Buffer.Manager->GetBuffer() + currentSize; - return true; + return {}; } - inline BufferManipResult Reserve(const std::size_t count = 1) + [[nodiscard]] inline std::expected Reserve(const std::size_t count = 1) noexcept { if (Buffer.CurrentPos + count <= Buffer.BufferEnd) - return true; + return {}; return AddSize(static_cast(count)); } - inline BufferManipResult Forward(const std::size_t count = 1) + [[nodiscard]] inline std::expected Forward(const std::size_t count = 1) noexcept { - if (Reserve(count)) - { - Buffer.CurrentPos += count; - return true; - } - return false; + SF_TRY(Reserve(count)); + Buffer.CurrentPos += count; + return {}; } public: - inline void SetChar(const TChar c) { *Buffer.CurrentPos = c; } - inline BufferManipResult Pushback(const TChar c) + inline void SetChar(const TChar c) noexcept { *Buffer.CurrentPos = c; } + [[nodiscard]] inline std::expected Pushback(const TChar c) noexcept { - if (Reserve(1)) - { - *Buffer.CurrentPos++ = c; - return true; - } - return false; + SF_TRY(Reserve(1)); + *Buffer.CurrentPos++ = c; + return {}; } - inline BufferManipResult SetInverse(const TChar c) + [[nodiscard]] inline std::expected SetInverse(const TChar c) noexcept { - if (BufferAccess(Buffer).CanMoveBackward(1)) - { - *--Buffer.CurrentPos = c; - return true; - } - return false; + SF_TRY(BufferAccess(Buffer).CanMoveBackward(1)); + *--Buffer.CurrentPos = c; + return {}; } - inline void ForcePushback(const TChar c) { *Buffer.CurrentPos++ = c; } - inline void ForceSetInverse(const TChar c) { *--Buffer.CurrentPos = c; } + inline void ForcePushback(const TChar c) noexcept { *Buffer.CurrentPos++ = c; } + inline void ForceSetInverse(const TChar c) noexcept { *--Buffer.CurrentPos = c; } public: - inline BufferManipResult Pushback(const TChar c, auto count) + [[nodiscard]] inline std::expected Pushback(const TChar c, auto count) noexcept { - if (Reserve(count)) - { - while (count-- > 0) - ForcePushback(c); - return true; - } - return false; + SF_TRY(Reserve(count)) + while (count-- > 0) + ForcePushback(c); + return {}; } public: - inline void AddSpaces(const auto count) { Pushback(' ', count); } + [[nodiscard]] inline std::expected AddSpaces(const auto count) noexcept { return Pushback(' ', count); } - protected: + private: template - inline void PushbackSeqImpl(const TChar c, const Rest... rest) + inline void PushbackSeqImpl(const TChar c, const Rest... rest) noexcept { ForcePushback(c); if constexpr (sizeof...(rest) > 0) PushbackSeqImpl(rest...); @@ -138,14 +127,11 @@ namespace StreamFormat::FMT::Detail public: template - inline BufferManipResult PushbackSeq(const CharToPush... ele) + [[nodiscard]] inline std::expected PushbackSeq(const CharToPush... ele) noexcept { - if (Reserve(sizeof...(ele))) - { - PushbackSeqImpl(ele...); - return true; - } - return false; + SF_TRY(Reserve(sizeof...(ele))) + PushbackSeqImpl(ele...); + return {}; } }; } diff --git a/src/StreamFormat/FMT/Buffer/BufferReadManip.h b/src/StreamFormat/FMT/Buffer/BufferReadManip.h index 90f49bd1..545a7450 100644 --- a/src/StreamFormat/FMT/Buffer/BufferReadManip.h +++ b/src/StreamFormat/FMT/Buffer/BufferReadManip.h @@ -15,49 +15,52 @@ namespace StreamFormat::FMT::Detail public: template - constexpr BufferManipResult FastReadInteger(T& i) noexcept + [[nodiscard]] constexpr std::expected FastReadInteger(T& t) noexcept { - T res = 0; - bool sign = false; if constexpr (std::is_signed_v) - { - sign = BufferTestManip(Buffer).IsEqualToForward('-'); - if (!BufferTestAccess(Buffer).IsADigit()) return false; - } + { sign = BufferTestManip(Buffer).IsEqualToForward('-'); } + if (!BufferTestAccess(Buffer).IsADigit()) + { return std::unexpected(FMTResult::Parse_NonValidDigit); } + + T value = static_cast(0); while (BufferTestAccess(Buffer).IsADigit()) - res = res * static_cast(10) + static_cast(BufferManip(Buffer).ThrowIfFailed().GetAndForward() - static_cast('0')); + { + char c = SF_TRY(BufferManip(Buffer).GetAndForward()); + value = value * static_cast(10) + static_cast(c - static_cast('0')); + } - i = sign ? -res : res; - return true; + t = sign ? -value : value; + return {}; } public: template - constexpr inline BufferManipResult FastReadFloat(T& i, std::int32_t floatPrecision = -1) noexcept + [[nodiscard]] constexpr inline std::expected FastReadFloat(T& t, std::int32_t floatPrecision = -1) noexcept { + T intpart = static_cast(0); + BufferTestAccess access(Buffer); BufferTestManip manip(Buffer); - bool sign = manip.IsEqualToForward('-'); + bool sign = SF_TRY(manip.IsEqualToForward('-')); - bool hasIntPart = false; - if (access.IsNotEqualTo('.')) + if (access.IsADigit()) { - hasIntPart = access.IsADigit(); - if (hasIntPart == false) return false; - T res = 0; - while (access.IsADigit()) - res = res * static_cast(10) + static_cast(BufferManipException(Buffer).GetAndForward() - static_cast('0')); - i = sign ? -res : res; + SF_TRY(FastReadInteger(intpart)); + } + else if (access.IsEqualTo('.') == false) + { + SF_TRY(manip.Forward()); + return std::unexpected(FMTResult::Parse_NonValidDigit); } - - if (manip.IsEqualToForward('.') == false) return hasIntPart; if (floatPrecision < 0) + { while (access.IsADigit() && BufferAccess(Buffer).IsEndOfString() == false) - BufferManip(Buffer).ForceForward(); + { BufferManip(Buffer).ForceForward(); } + } else { while (access.IsADigit() && floatPrecision > 0 && BufferAccess(Buffer).IsEndOfString() == false) @@ -68,37 +71,40 @@ namespace StreamFormat::FMT::Detail } BufferManip(Buffer).ForceBackward(); - T dec = (T)0; + T dec = static_cast(0); while (access.IsADigit()) { dec += static_cast(BufferManip(Buffer).GetAndForceBackward() - '0'); dec /= 10; } - i += dec; - return true; + + t = sign ? - intpart - dec : intpart + dec; + return {}; } public: template - BufferManipResult FastReadCharPtr(const CharPtr* str, std::size_t sizeToCopy, bool isZeroEnded = true) + [[nodiscard]] std::expected FastReadCharPtr(const CharPtr* str, std::size_t sizeToCopy, bool isZeroEnded = true) { if (BufferAccess(Buffer).CanMoveForward(sizeToCopy) == false) + { return BufferReadManip(Buffer).FastReadCharPtr(str, BufferAccess(Buffer).GetBufferRemainingSize(), isZeroEnded); + } // TODO : Opti with bigger types while (sizeToCopy-- != 0) - *str++ = BufferManip(Buffer).GetAndForward(); - if (isZeroEnded) *str = 0; + { *str++ = BufferManip(Buffer).GetAndForward(); } + if (isZeroEnded) { *str = 0; } - return true; + return {}; } template - inline BufferManipResult FastReadCharArray(const CharStr (&str)[SIZE], bool isZeroEnded = true) + [[nodiscard]] inline std::expected FastReadCharArray(const CharStr (&str)[SIZE], bool isZeroEnded = true) { return FastReadCharPtr(str, SIZE); } template - inline BufferManipResult FastReadCharBound(const CharStr* begin, const CharStr* end, bool isZeroEnded = true) + [[nodiscard]] inline std::expected FastReadCharBound(const CharStr* begin, const CharStr* end, bool isZeroEnded = true) { return FastReadCharPtr(begin, end - begin - (isZeroEnded ? 1 : 0), isZeroEnded); } diff --git a/src/StreamFormat/FMT/Buffer/BufferTestManip.h b/src/StreamFormat/FMT/Buffer/BufferTestManip.h index 33b6a502..e5569eef 100644 --- a/src/StreamFormat/FMT/Buffer/BufferTestManip.h +++ b/src/StreamFormat/FMT/Buffer/BufferTestManip.h @@ -14,34 +14,35 @@ namespace StreamFormat::FMT::Detail const BufferInfo& Buffer; public: - constexpr inline BufferManipResult IsEqualTo(const TChar c) const noexcept { return Buffer.Get() == c; } - constexpr inline BufferManipResult IsNotEqualTo(const TChar c) const noexcept { return Buffer.Get() != c; } + constexpr inline bool IsEqualTo(const TChar c) const noexcept { return Buffer.Get() == c; } + constexpr inline bool IsNotEqualTo(const TChar c) const noexcept { return Buffer.Get() != c; } template - constexpr inline BufferManipResult IsEqualTo(const TChar c, const CharToTest... ele) const noexcept + constexpr inline bool IsEqualTo(const TChar c, const CharToTest... ele) const noexcept { return IsEqualTo(c) || IsEqualTo(ele...); } template - constexpr inline BufferManipResult IsNotEqualTo(const TChar c, const CharToTest... ele) const noexcept + constexpr inline bool IsNotEqualTo(const TChar c, const CharToTest... ele) const noexcept { return IsNotEqualTo(c) && IsNotEqualTo(ele...); } - constexpr inline BufferManipResult NextIsEqualTo(const TChar c) const noexcept { return BufferAccess(Buffer).GetNextForce() + 1 == c; } - constexpr inline BufferManipResult NextIsNotEqualTo(const TChar c) const noexcept { return BufferAccess(Buffer).GetNextForce() + 1 != c; } - constexpr inline BufferManipResult PrevIsEqualTo(const TChar c) const noexcept { return BufferAccess(Buffer).GetPrevForce() - 1 == c; } - constexpr inline BufferManipResult PrevIsNotEqualTo(const TChar c) const noexcept { return BufferAccess(Buffer).GetPrevForce() - 1 != c; } + constexpr inline bool NextIsEqualTo(const TChar c) const noexcept { return BufferAccess(Buffer).GetNextForce() + 1 == c; } + constexpr inline bool NextIsNotEqualTo(const TChar c) const noexcept { return BufferAccess(Buffer).GetNextForce() + 1 != c; } + constexpr inline bool PrevIsEqualTo(const TChar c) const noexcept { return BufferAccess(Buffer).GetPrevForce() - 1 == c; } + constexpr inline bool PrevIsNotEqualTo(const TChar c) const noexcept { return BufferAccess(Buffer).GetPrevForce() - 1 != c; } public: - constexpr inline BufferManipResult IsLowerCase() const noexcept { return Buffer.Get() >= 'a' && Buffer.Get() <= 'z'; } - constexpr inline BufferManipResult IsUpperCase() const noexcept { return Buffer.Get() >= 'A' && Buffer.Get() <= 'Z'; } - constexpr inline BufferManipResult IsADigit() const noexcept { return Buffer.Get() >= '0' && Buffer.Get() <= '9'; } + constexpr inline bool IsLowerCase() const noexcept { return Buffer.Get() >= 'a' && Buffer.Get() <= 'z'; } + constexpr inline bool IsUpperCase() const noexcept { return Buffer.Get() >= 'A' && Buffer.Get() <= 'Z'; } + constexpr inline bool IsADigit() const noexcept { return Buffer.Get() >= '0' && Buffer.Get() <= '9'; } public: template - constexpr BufferManipResult IsSame(const CharToTest* str, std::size_t size) const noexcept + constexpr bool IsSame(const CharToTest* str, std::size_t size) const noexcept { - if (size > BufferAccess(Buffer).GetBufferRemainingSize()) return false; + if (size > BufferAccess(Buffer).GetBufferRemainingSize()) + { return false; } const TChar* bufferStr = Buffer.CurrentPos; bool isSame = true; @@ -50,11 +51,12 @@ namespace StreamFormat::FMT::Detail isSame = *bufferStr++ == *str++; --size; } - if (size != 0 && *str != 0) isSame = false; + if (size != 0 && *str != 0) + { return false; } return isSame; } template - constexpr inline BufferManipResult IsSame(std::basic_string_view sv) const noexcept + constexpr inline bool IsSame(std::basic_string_view sv) const noexcept { return IsSame(sv.data(), sv.size()); } @@ -75,52 +77,52 @@ namespace StreamFormat::FMT::Detail public: template - constexpr inline BufferManipResult IsEqualToForward(const CharToTest... ele) noexcept + [[nodiscard]] constexpr inline std::expected IsEqualToForward(const CharToTest... ele) noexcept { if (Access().IsEqualTo(ele...)) - return BufferManip(Buffer).Forward(); + { return BufferManip(Buffer).Forward().transform([]{return true;}); } return false; } template - constexpr inline BufferManipResult IsNotEqualForward(const CharToTest... ele) noexcept + [[nodiscard]] constexpr inline std::expected IsNotEqualForward(const CharToTest... ele) noexcept { if (Access().IsNotEqualTo(ele...)) - return BufferManip(Buffer).Forward(); + { return BufferManip(Buffer).Forward().transform([]{return true;}); } return false; } public: template - constexpr BufferManipResult IsSameForward(const CharToTest* str, std::size_t size) noexcept + [[nodiscard]] constexpr std::expected IsSameForward(const CharToTest* str, std::size_t size) noexcept { if (Access().IsSame(str, size)) - return BufferManip(Buffer).Forward(size); + { return BufferManip(Buffer).Forward().transform([]{return true;}); } return false; } template - constexpr inline BufferManipResult IsSameForward(std::basic_string_view sv) noexcept + [[nodiscard]] constexpr inline std::expected IsSameForward(std::basic_string_view sv) noexcept { if (Access().IsSame(sv)) - return BufferManip(Buffer).Forward(sv.size()); + { return BufferManip(Buffer).Forward().transform([]{return true;}); } return false; } public: template - inline void Skip(const CharToTest... ele) noexcept { IsEqualToForward(ele...); } + [[nodiscard]] inline std::expected SkipOneOf(const CharToTest... ele) noexcept { return IsEqualToForward(ele...).transform([]{}); } template - inline void SkipAll(const CharToTest... ele) noexcept + inline void SkipEvery(const CharToTest... ele) noexcept { while (Access().IsEqualTo(ele...) && BufferAccess(Buffer).CanMoveForward()) - BufferManip(Buffer).ForceForward(); + { BufferManip(Buffer).ForceForward(); } } public: - inline void SkipSpace() noexcept { Skip(' ', '\t'); } - inline void SkipBlank() noexcept { Skip(' ', '\t', '\n', '\r', '\v'); } + [[nodiscard]] inline std::expected SkipSpace() noexcept { return SkipOneOf(' ', '\t'); } + [[nodiscard]] inline std::expected SkipBlank() noexcept { return SkipOneOf(' ', '\t', '\n', '\r', '\v'); } - inline void SkipAllSpaces() noexcept { SkipAll(' ', '\t'); } - inline void SkipAllBlanks() noexcept { SkipAll(' ', '\t', '\n', '\r', '\v'); } + inline void SkipAllSpaces() noexcept { SkipEvery(' ', '\t'); } + inline void SkipAllBlanks() noexcept { SkipEvery(' ', '\t', '\n', '\r', '\v'); } public: template @@ -130,10 +132,10 @@ namespace StreamFormat::FMT::Detail BufferManip(Buffer).ForceForward(); } template - inline void GoToForward(const CharToTest... ele) noexcept + [[nodiscard]] inline std::expected GoToForward(const CharToTest... ele) noexcept { GoTo(ele...); - BufferManip(Buffer).Forward(); + return BufferManip(Buffer).Forward(); } public: diff --git a/src/StreamFormat/FMT/Buffer/BufferWriteManip.h b/src/StreamFormat/FMT/Buffer/BufferWriteManip.h index ed7a28eb..2bcea37e 100644 --- a/src/StreamFormat/FMT/Buffer/BufferWriteManip.h +++ b/src/StreamFormat/FMT/Buffer/BufferWriteManip.h @@ -57,11 +57,11 @@ namespace StreamFormat::FMT::Detail public: template requires std::is_integral_v - constexpr void FastWriteInteger(T i) + [[nodiscard]] constexpr std::expected FastWriteInteger(T i) { BufferOutManip manip(Buffer); - if (i == 0) { manip.Pushback('0'); return; } + if (i == 0) { manip.Pushback('0'); return {}; } if constexpr (std::is_signed_v) { @@ -69,28 +69,28 @@ namespace StreamFormat::FMT::Detail } std::int32_t nbDigit = BufferWriteUtils::GetNumberOfDigitDec(i); - manip.Forward(nbDigit).ThrowIfFailed(); + SF_TRY(manip.Forward(nbDigit)); while (i > 0) { - if (BufferAccess(Buffer).IsOutOfBound()) - BufferAccess(Buffer).IsOutOfBound(); manip.ForceSetInverse(i % 10 + '0'); i /= 10; } - manip.Forward(nbDigit).ThrowIfFailed(); + SF_TRY(manip.Forward(nbDigit)); + + return {}; } public: template requires std::is_floating_point_v - void FastWriteFloat(T i, std::int32_t floatPrecision = 2) + [[nodiscard]] constexpr std::expected FastWriteFloat(T i, std::int32_t floatPrecision = 2) { BufferOutManip manip(Buffer); if (i == 0) - { manip.Pushback('0'); return; } + { SF_TRY(manip.Pushback('0')); return {}; } if (i < 0) - { manip.Pushback('-'); i = -i; } + { SF_TRY(manip.Pushback('-')); i = -i; } T k = std::trunc(i); i = i - k; @@ -116,7 +116,7 @@ namespace StreamFormat::FMT::Detail public: template - void FastWriteCharArray(const CharInput* str, std::size_t size) + [[nodiscard]] constexpr std::expected FastWriteCharArray(const CharInput* str, std::size_t size) { if (BufferOutManip(Buffer).Reserve(size) == false) return FastWriteCharArray(str, BufferAccess(Buffer).GetBufferRemainingSize()); @@ -126,30 +126,34 @@ namespace StreamFormat::FMT::Detail BufferOutManip(Buffer).ForcePushback(*str++); } template - inline void FastWriteString(std::basic_string_view sv) + [[nodiscard]] inline constexpr std::expected FastWriteString(std::basic_string_view sv) { - FastWriteCharArray(sv.data(), sv.size()); + return FastWriteCharArray(sv.data(), sv.size()); } - inline void FastWriteString(std::basic_string_view sv) + [[nodiscard]] inline std::expected FastWriteString(std::basic_string_view sv) { - FastWriteCharArray(sv.data(), sv.size()); + return FastWriteCharArray(sv.data(), sv.size()); } template - inline void FastWriteStringLitteral(CharInput (&str)[SIZE]) + [[nodiscard]] inline std::expected FastWriteStringLitteral(CharInput (&str)[SIZE]) { std::size_t size = SIZE; while (str[size - 1] == 0) --size; - FastWriteCharArray(str, size); + return FastWriteCharArray(str, size); } public: - template inline void BasicWriteType(std::basic_string_view str) { FastWriteString(str); } - template inline void BasicWriteType(CharInput (&str)[SIZE]) { FastWriteStringLitteral(str); } - template requires std::is_integral_v void BasicWriteType(T t) { FastWriteInteger(t); } - template requires std::is_floating_point_v void BasicWriteType(T t) { FastWriteFloat(t); } + template + [[nodiscard]] inline std::expected BasicWriteType(std::basic_string_view str) { return FastWriteString(str); } + template + [[nodiscard]] inline std::expected BasicWriteType(CharInput (&str)[SIZE]) { return FastWriteStringLitteral(str); } + template requires std::is_integral_v + [[nodiscard]] inline std::expected BasicWriteType(T t) { return FastWriteInteger(t); } + template requires std::is_floating_point_v + [[nodiscard]] inline std::expected BasicWriteType(T t) { return FastWriteFloat(t); } template - inline void BasicWriteType(Type&& type, Rest&&... rest) + [[nodiscard]] inline std::expected BasicWriteType(Type&& type, Rest&&... rest) { BasicWriteType(type); if constexpr (sizeof...(rest) > 0) diff --git a/src/StreamFormat/FMT/Buffer/FMTBufferOutManip.h b/src/StreamFormat/FMT/Buffer/FMTBufferOutManip.h index 49857bcf..d4a2bb9b 100644 --- a/src/StreamFormat/FMT/Buffer/FMTBufferOutManip.h +++ b/src/StreamFormat/FMT/Buffer/FMTBufferOutManip.h @@ -40,23 +40,23 @@ namespace StreamFormat::FMT::Detail FMTBufferOutInfo& Buffer; public: - constexpr inline void AddNoStride(const std::size_t noStride) noexcept { Buffer.NoStride += noStride; } + constexpr inline void AddNoStride(const std::size_t noStride) noexcept { Buffer.NoStride += noStride; } - constexpr inline void AddIndent(const std::size_t indent) noexcept { Buffer.Indent += indent; } - constexpr inline void RemoveIndent(const std::size_t indent) noexcept { Buffer.Indent -= indent; } - constexpr inline void SetIndent() noexcept { Buffer.Indent = BufferManip(Buffer).GetBufferCurrentSize() - Buffer.NoStride; } + constexpr inline void AddIndent(const std::size_t indent) noexcept { Buffer.Indent += indent; } + constexpr inline void RemoveIndent(const std::size_t indent) noexcept { Buffer.Indent -= indent; } + constexpr inline void SetIndent() noexcept { Buffer.Indent = BufferManip(Buffer).GetBufferCurrentSize() - Buffer.NoStride; } public: - constexpr inline void NewLineIndent() + [[nodiscard]] constexpr inline std::expected NewLineIndent() { - BufferOutManip(Buffer).Pushback('\n'); - BufferOutManip(Buffer).Pushback(' ', Buffer.Indent); + SF_TRY(BufferOutManip(Buffer).Pushback('\n')); + return BufferOutManip(Buffer).Pushback(' ', Buffer.Indent); } - constexpr inline void PushbackCheckIndent(const TChar c) + [[nodiscard]] constexpr inline std::expected PushbackCheckIndent(const TChar c) { - BufferOutManip(Buffer).Pushback(c); - if (c == '\n') BufferOutManip(Buffer).Pushback(' ', Buffer.Indent); + SF_TRY(BufferOutManip(Buffer).Pushback(c)); + return if (c == '\n') BufferOutManip(Buffer).Pushback(' ', Buffer.Indent); } }; @@ -75,29 +75,31 @@ namespace StreamFormat::FMT::Detail BufferTestManip(Buffer).GoTo(ele..., '}'); } template - inline void ParamGoToForward(const CharToTest... ele) + [[nodiscard]] inline std::expected ParamGoToForward(const CharToTest... ele) { - BufferTestManip(Buffer).GoToForward(ele..., '}'); + return BufferTestManip(Buffer).GoToForward(ele..., '}'); } - inline BufferManipResult IsBeginOfParameter() + inline bool IsBeginOfParameter() { return BufferTestAccess(Buffer).IsEqualTo('{'); } - inline BufferManipResult IsEndOfParameter() + inline bool IsEndOfParameter() { return BufferTestAccess(Buffer).IsEqualTo('}'); } public: template - bool NextIsNamedArgs(const std::basic_string_view& sv) + [[nodiscard]] std::expected NextIsNamedArgs(const std::basic_string_view& sv) { BufferTestAccess access(Buffer); BufferTestManip manip(Buffer); TChar* const oldpos = Buffer.CurrentPos; - if (manip.IsSameForward(sv) && (access.IsEqualTo(':') || access.IsEqualTo('}'))) return true; + auto isSame = SF_TRY(manip.IsSameForward(sv)); + if (isSame && (access.IsEqualTo(':') || access.IsEqualTo('}'))) + { return true; } Buffer.CurrentPos = oldpos; return false; } diff --git a/src/StreamFormat/FMT/Buffer/FMTBufferReadManip.h b/src/StreamFormat/FMT/Buffer/FMTBufferReadManip.h index 29eb3a6e..ebe77f24 100644 --- a/src/StreamFormat/FMT/Buffer/FMTBufferReadManip.h +++ b/src/StreamFormat/FMT/Buffer/FMTBufferReadManip.h @@ -18,7 +18,7 @@ namespace StreamFormat::FMT::Detail public: template - void ReadInteger(T& i, ShiftInfo shift = ShiftInfo{}) + [[nodiscard]] std::expected ReadInteger(T& i, ShiftInfo shift = ShiftInfo{}) { BufferShiftReadManip shiftManip(Buffer); Detail::BufferTestAccess access(Buffer); @@ -44,13 +44,11 @@ namespace StreamFormat::FMT::Detail shiftManip.SkipShiftEnd(shift); - if (shift.Size > 0) throw FMTParseError(); - i = sign ? -res : res; } public: template - void ReadFloat(T& i, std::int32_t floatPrecision = -1, ShiftInfo shift = ShiftInfo{}) + [[nodiscard]] std::expected ReadFloat(T& i, std::int32_t floatPrecision = -1, ShiftInfo shift = ShiftInfo{}) { BufferShiftReadManip shiftManip(Buffer); Detail::BufferTestAccess access(Buffer); @@ -104,14 +102,12 @@ namespace StreamFormat::FMT::Detail shiftManip.SkipShiftEnd(shift); - if (shift.Size > 0) throw FMTParseError(); - sign ? i = -res - dec : i = res + dec; } public: template - void ReadIntegerH(T& i, std::uint8_t digitSize, std::uint8_t (&digitLUT)(TChar), TChar base_prefix = '\0', ShiftInfo shift = ShiftInfo{}) + [[nodiscard]] std::expected ReadIntegerH(T& i, std::uint8_t digitSize, std::uint8_t (&digitLUT)(TChar), TChar base_prefix = '\0', ShiftInfo shift = ShiftInfo{}) { BufferShiftReadManip shiftManip(Buffer); Detail::BufferTestAccess access(Buffer); @@ -123,7 +119,7 @@ namespace StreamFormat::FMT::Detail shiftManip.SkipShiftBeginSpace(shift); if (base_prefix != '\0') - { manip.Skip('0'); manip.Skip(base_prefix); } + { manip.SkipOneOf('0'); manip.SkipOneOf(base_prefix); } T res = 0; @@ -136,8 +132,6 @@ namespace StreamFormat::FMT::Detail shiftManip.SkipShiftEnd(shift); - if (shift.Size > 0) throw FMTParseError(); - i = res; } @@ -179,7 +173,7 @@ namespace StreamFormat::FMT::Detail public: template - void ReadIntegerFormatData(T& i, const FormatData& formatData) + [[nodiscard]] std::expected ReadIntegerFormatData(T& i, const FormatData& formatData) { if (formatData.HasSpec) { @@ -187,7 +181,7 @@ namespace StreamFormat::FMT::Detail { case IntegerPrintBase::Dec: if (formatData.Shift.Type == ShiftInfo::ShiftType::Nothing) - return BufferReadManip(Buffer).FastReadInteger(i).ThrowIfFailed(); + return BufferReadManip(Buffer).FastReadInteger(i); else return ReadInteger(i, formatData.Shift); case IntegerPrintBase::Bin: @@ -202,37 +196,37 @@ namespace StreamFormat::FMT::Detail return ReadIntegerH(i, 4, DigitLUT_HEXUPPER, formatData.PrefixSuffix ? (char)formatData.IntegerPrint : '\0', formatData.Shift); } } - return BufferReadManip(Buffer).FastReadInteger(i).ThrowIfFailed(); + return BufferReadManip(Buffer).FastReadInteger(i); } template - void ReadFloatFormatData(T& i, const FormatData& formatData) + [[nodiscard]] std::expected ReadFloatFormatData(T& i, const FormatData& formatData) { if (formatData.HasSpec) { if (formatData.ShiftType == ShiftInfo::ShiftType::Nothing) - return BufferReadManip(Buffer).FastReadFloat(i, formatData.FloatPrecision).ThrowIfFailed(); + return BufferReadManip(Buffer).FastReadFloat(i, formatData.FloatPrecision); else return ReadFloat(i, formatData.FloatPrecision, formatData.Shift); } - return BufferReadManip(Buffer).FastReadFloat(i, formatData.FloatPrecision).ThrowIfFailed(); + return BufferReadManip(Buffer).FastReadFloat(i, formatData.FloatPrecision); } public: template - void ReadCharPtr(const CharStr* str, std::size_t sizeContainer, std::size_t sizeToWrite, ShiftInfo shift = ShiftInfo{}) + [[nodiscard]] std::expected ReadCharPtr(const CharStr* str, std::size_t sizeContainer, std::size_t sizeToWrite, ShiftInfo shift = ShiftInfo{}) { // FIXME // TODO - throw FMTImplError{}; + return std::unexpected(FMTResult::FunctionNotImpl); } template - inline void ReadCharArray(const CharStr (&str)[SIZE], ShiftInfo shift = ShiftInfo{}) + [[nodiscard]] inline std::expected ReadCharArray(const CharStr (&str)[SIZE], ShiftInfo shift = ShiftInfo{}) { ReadCharPtr(str, SIZE, 0, shift); } template - inline void ReadCharBound(const CharStr* begin, const CharStr* end, ShiftInfo shift = ShiftInfo{}) + [[nodiscard]] inline std::expected ReadCharBound(const CharStr* begin, const CharStr* end, ShiftInfo shift = ShiftInfo{}) { ReadCharPtr(begin, end - begin, 0, shift); } diff --git a/src/StreamFormat/FMT/Buffer/FMTBufferWriteManip.h b/src/StreamFormat/FMT/Buffer/FMTBufferWriteManip.h index ca354506..a91f53b7 100644 --- a/src/StreamFormat/FMT/Buffer/FMTBufferWriteManip.h +++ b/src/StreamFormat/FMT/Buffer/FMTBufferWriteManip.h @@ -20,9 +20,11 @@ namespace StreamFormat::FMT::Detail public: template - void WriteInteger(T i, Detail::ShiftInfo shift = Detail::ShiftInfo{}) + [[nodiscard]] std::expected WriteInteger(T i, Detail::ShiftInfo shift = Detail::ShiftInfo{}) { - shift.Print.ValidateForNumber(); + char oldBefore = shift.Print.Before; + if (shift.Print.Before >= '0' && shift.Print.Before <= '9') + shift.Print.Before = ' '; std::int32_t nbDigit = BufferWriteUtils::GetNumberOfDigitDec(i); @@ -55,13 +57,17 @@ namespace StreamFormat::FMT::Detail } BufferShiftWriteManip(Buffer).WriteShiftEnd(shift); + + shift.Print.Before = oldBefore; } public: template - void WriteFloat(T i, std::int32_t floatPrecision = 2, Detail::ShiftInfo shift = Detail::ShiftInfo{}) + [[nodiscard]] std::expected WriteFloat(T i, std::int32_t floatPrecision = 2, Detail::ShiftInfo shift = Detail::ShiftInfo{}) { - shift.Print.ValidateForNumber(); + char oldBefore = shift.Print.Before; + if (shift.Print.Before >= '0' && shift.Print.Before <= '9') + shift.Print.Before = ' '; std::int32_t nbDigit = BufferWriteUtils::GetNumberOfDigitDec(std::trunc(i)); @@ -104,11 +110,13 @@ namespace StreamFormat::FMT::Detail } BufferShiftWriteManip(Buffer).WriteShiftEnd(shift); + + shift.Print.Before = oldBefore; } public: template - void WriteIntegerH(T i, std::uint8_t digitSize, const TChar* const lut, TChar base_prefix = '\0', ShiftInfo shift = ShiftInfo{}) + [[nodiscard]] std::expected WriteIntegerH(T i, std::uint8_t digitSize, const TChar* const lut, TChar base_prefix = '\0', ShiftInfo shift = ShiftInfo{}) { BufferOutManip manip(Buffer); @@ -144,7 +152,7 @@ namespace StreamFormat::FMT::Detail public: template - void WriteIntegerFormatData(T i, const FormatData& formatData) + [[nodiscard]] std::expected WriteIntegerFormatData(T i, const FormatData& formatData) { if (formatData.HasSpec) { @@ -171,7 +179,7 @@ namespace StreamFormat::FMT::Detail return BufferWriteManip(Buffer).FastWriteInteger(i); } template - void WriteFloatFormatData(T i, const FormatData& formatData) + [[nodiscard]] std::expected WriteFloatFormatData(T i, const FormatData& formatData) { if (formatData.HasSpec) { @@ -184,7 +192,7 @@ namespace StreamFormat::FMT::Detail public: template - inline void WriteIndentCharPtr(const CharStr* str, std::size_t size) + [[nodiscard]] inline std::expected WriteIndentCharPtr(const CharStr* str, std::size_t size) { while (size > 0) { @@ -206,23 +214,23 @@ namespace StreamFormat::FMT::Detail } } template - inline void WriteIndentCharBound(const CharStr* begin, const CharStr* end) + [[nodiscard]] inline std::expected WriteIndentCharBound(const CharStr* begin, const CharStr* end) { WriteIndentCharPtr(begin, end - begin); } template - inline void WriteIndentString(std::basic_string_view str) + [[nodiscard]] inline std::expected WriteIndentString(std::basic_string_view str) { WriteIndentCharPtr(str.data(), str.size()); } template - inline void WriteCharPtr(const CharStr* str, std::size_t size, ShiftInfo& shift) + [[nodiscard]] inline std::expected WriteCharPtr(const CharStr* str, std::size_t size, ShiftInfo& shift) { if (shift.Size <= 0) return BufferWriteManip(Buffer).FastWriteCharArray(str, size); - BufferOutManip(Buffer).Reserve(std::max(static_cast(shift.Size), size)).ThrowIfFailed(); + BufferOutManip(Buffer).Reserve(std::max(static_cast(shift.Size), size)); if (static_cast(shift.Size) > size) { @@ -240,14 +248,14 @@ namespace StreamFormat::FMT::Detail } } template - inline void WriteCharBound(const CharStr* begin, const CharStr* end, ShiftInfo& shift) + [[nodiscard]] inline std::expected WriteCharBound(const CharStr* begin, const CharStr* end, ShiftInfo& shift) { - WriteCharPtr(begin, end - begin, shift); + return WriteCharPtr(begin, end - begin, shift); } template - inline void WriteString(std::basic_string_view str, ShiftInfo& shift) + [[nodiscard]] inline std::expected WriteString(std::basic_string_view str, ShiftInfo& shift) { - WriteCharPtr(str.data(), str.size(), shift); + return WriteCharPtr(str.data(), str.size(), shift); } }; } diff --git a/src/StreamFormat/FMT/Buffer/Utils/BufferGlobberManip.h b/src/StreamFormat/FMT/Buffer/Utils/BufferGlobberManip.h index e55549e4..f5ff4859 100644 --- a/src/StreamFormat/FMT/Buffer/Utils/BufferGlobberManip.h +++ b/src/StreamFormat/FMT/Buffer/Utils/BufferGlobberManip.h @@ -109,7 +109,7 @@ namespace StreamFormat::FMT::Detail BufferInfo& Buffer; public: - BufferManipResult FastReadCharPtrGlobber(std::basic_string_view globPattern, TChar* str, std::size_t sizeToCopy) + [[nodiscard]] std::expected FastReadCharPtrGlobber(std::basic_string_view globPattern, TChar* str, std::size_t sizeToCopy) { BufferInfo globber(globPattern); const TChar* begin = Buffer.CurrentPos; @@ -120,9 +120,9 @@ namespace StreamFormat::FMT::Detail return BufferReadManip(subContext).FastReadCharPtr(str, sizeToCopy); } - BufferManipResult FastReadCharPtrRegex(std::basic_string_view regexPattern, TChar* str, std::size_t sizeToCopy) + [[nodiscard]] std::expected FastReadCharPtrRegex(std::basic_string_view regexPattern, TChar* str, std::size_t sizeToCopy) { - throw FMTImplError{}; + return std::unexpected(FMTResult::FunctionNotImpl); } }; } diff --git a/src/StreamFormat/FMT/Buffer/Utils/BufferShiftManip.h b/src/StreamFormat/FMT/Buffer/Utils/BufferShiftManip.h index 31f15fe1..dfe258b1 100644 --- a/src/StreamFormat/FMT/Buffer/Utils/BufferShiftManip.h +++ b/src/StreamFormat/FMT/Buffer/Utils/BufferShiftManip.h @@ -14,7 +14,7 @@ namespace StreamFormat::FMT::Detail BufferOutInfo& Buffer; public: - inline void WriteShiftCenterBegin(Detail::ShiftInfo& shift) + [[nodiscard]] inline std::expected WriteShiftCenterBegin(Detail::ShiftInfo& shift) { if (shift.Type == Detail::ShiftInfo::ShiftType::CenterRight || shift.Type == Detail::ShiftInfo::ShiftType::CenterLeft) { @@ -25,31 +25,31 @@ namespace StreamFormat::FMT::Detail } } - inline void WriteShiftCenterEnd(Detail::ShiftInfo& shift) + [[nodiscard]] inline std::expected WriteShiftCenterEnd(Detail::ShiftInfo& shift) { if (shift.Type == Detail::ShiftInfo::ShiftType::CenterRight || shift.Type == Detail::ShiftInfo::ShiftType::CenterLeft) BufferOutManip(Buffer).Pushback(shift.Print.After, shift.Size); } - inline void WriteShiftRightAll(Detail::ShiftInfo& shift) + [[nodiscard]] inline std::expected WriteShiftRightAll(Detail::ShiftInfo& shift) { if (shift.Type == Detail::ShiftInfo::ShiftType::Right) BufferOutManip(Buffer).Pushback(shift.Print.Before, shift.Size); } - inline void WriteShiftLeftAll(Detail::ShiftInfo& shift) + [[nodiscard]] inline std::expected WriteShiftLeftAll(Detail::ShiftInfo& shift) { if (shift.Type == Detail::ShiftInfo::ShiftType::Left) BufferOutManip(Buffer).Pushback(shift.Print.After, shift.Size); } - inline void WriteShiftBegin(Detail::ShiftInfo& shift) + [[nodiscard]] inline std::expected WriteShiftBegin(Detail::ShiftInfo& shift) { WriteShiftCenterBegin(shift); WriteShiftRightAll(shift); } - inline void WriteShiftEnd(Detail::ShiftInfo& shift) + [[nodiscard]] inline std::expected WriteShiftEnd(Detail::ShiftInfo& shift) { WriteShiftLeftAll(shift); WriteShiftCenterEnd(shift); @@ -65,7 +65,7 @@ namespace StreamFormat::FMT::Detail BufferInfo& Buffer; public: - void SkipShiftBeginSpace(Detail::ShiftInfo& shift) + [[nodiscard]] std::expected SkipShiftBeginSpace(Detail::ShiftInfo& shift) { if (shift.Print.BeforeIsADigit() == false) return; if (shift.Type == Detail::ShiftInfo::ShiftType::Right || shift.Type == Detail::ShiftInfo::ShiftType::CenterLeft || shift.Type == Detail::ShiftInfo::ShiftType::CenterRight) @@ -76,7 +76,7 @@ namespace StreamFormat::FMT::Detail } } - void SkipShiftEnd(Detail::ShiftInfo& shift) + [[nodiscard]] std::expected SkipShiftEnd(Detail::ShiftInfo& shift) { if (shift.Type == Detail::ShiftInfo::ShiftType::Left || shift.Type == Detail::ShiftInfo::ShiftType::CenterLeft || shift.Type == Detail::ShiftInfo::ShiftType::CenterRight) while (Buffer.Get() == ' ' && shift.Size > 0) diff --git a/src/StreamFormat/FMT/Buffer/Utils/BufferUtils.h b/src/StreamFormat/FMT/Buffer/Utils/BufferUtils.h index 84bc313e..627fd036 100644 --- a/src/StreamFormat/FMT/Buffer/Utils/BufferUtils.h +++ b/src/StreamFormat/FMT/Buffer/Utils/BufferUtils.h @@ -23,14 +23,15 @@ namespace StreamFormat::FMT::Detail using TConstChar = std::remove_const_t; public: - static constexpr std::size_t GET_WORD_FROM_LIST_NOT_FOUND = (std::numeric_limits::max)(); - template - std::size_t GetWordFromList(const std::basic_string_view (&data)[SIZE], const std::size_t defaultValue = GET_WORD_FROM_LIST_NOT_FOUND) + [[nodiscard]] std::expected GetWordFromList(const std::basic_string_view (&data)[SIZE]) { for (std::size_t idx = 0; idx < SIZE; ++idx) - if (BufferTestManip(Buffer).IsSameForward(data[idx])) return idx; - return defaultValue; + { + bool found = SF_TRY(BufferTestManip(Buffer).IsSameForward(data[idx])); + if (found) return idx; + } + return std::unexpected(FMTResult::Specifers_Invalid); } // TODO: use static map ? @@ -38,11 +39,14 @@ namespace StreamFormat::FMT::Detail using DictPairs = std::pair, T>; template - T GetWordFromDictPairs(const DictPairs (&data)[SIZE], std::convertible_to auto defaultValue = T{}) + [[nodiscard]] std::expected GetWordFromDictPairs(const DictPairs (&data)[SIZE]) { for (std::size_t idx = 0; idx < SIZE; ++idx) - if (BufferTestManip(Buffer).IsSameForward(data[idx].first)) return data[idx].second; - return defaultValue; + { + bool found = SF_TRY(BufferTestManip(Buffer).IsSameForward(data[idx].first)); + if (found) return data[idx].second; + } + return std::unexpected(FMTResult::Specifers_Invalid); } }; @@ -50,73 +54,73 @@ namespace StreamFormat::FMT::Detail { public: template - static void ParseEscapedQuotedString(Detail::BufferInfo& buffer, Detail::BufferOutInfo& stringOut) + [[nodiscard]] static std::expected ParseEscapedQuotedString(Detail::BufferInfo& buffer, Detail::BufferOutInfo& stringOut) { - Detail::BufferTestManip(buffer).Skip('"'); + SF_TRY(Detail::BufferTestManip(buffer).SkipOneOf('"')); while (Detail::BufferAccess(buffer).IsEndOfString() == false) { - Detail::BufferWriteManip(stringOut).FastWriteString( + SF_TRY(Detail::BufferWriteManip(stringOut).FastWriteString( Detail::BufferTestManip(buffer).ViewUntil('"', '\\') - ); + )); if (Detail::BufferTestAccess(buffer).IsEqualTo('"')) break; - Detail::BufferTestManip(buffer).Skip('\\'); + Detail::BufferTestManip(buffer).SkipOneOf('\\'); switch (buffer.Get()) { // TODO : Do all others escape char case '"': - Detail::BufferOutManip(stringOut).Pushback('"'); + SF_TRY(Detail::BufferOutManip(stringOut).Pushback('"')); break; case 't': - Detail::BufferOutManip(stringOut).Pushback('\t'); + SF_TRY(Detail::BufferOutManip(stringOut).Pushback('\t')); break; case 'r': - Detail::BufferOutManip(stringOut).Pushback('\r'); + SF_TRY(Detail::BufferOutManip(stringOut).Pushback('\r')); break; case 'n': - Detail::BufferOutManip(stringOut).Pushback('\n'); + SF_TRY(Detail::BufferOutManip(stringOut).Pushback('\n')); break; default: break; } } - Detail::BufferTestManip(buffer).Skip('"'); + SF_TRY(Detail::BufferTestManip(buffer).SkipOneOf('"')); } template - static void FormatEscapedQuotedString(Detail::BufferOutInfo& buffer, Detail::BufferInfo& stringIn) + [[nodiscard]] static std::expected FormatEscapedQuotedString(Detail::BufferOutInfo& buffer, Detail::BufferInfo& stringIn) { - Detail::BufferOutManip(buffer).Pushback('"'); + SF_TRY(Detail::BufferOutManip(buffer).Pushback('"')); while (Detail::BufferAccess(stringIn).IsEndOfString() == false) { - Detail::BufferWriteManip(buffer).FastWriteString( + SF_TRY(Detail::BufferWriteManip(buffer).FastWriteString( Detail::BufferTestManip(stringIn).ViewUntil('\\') - ); + )); if (Detail::BufferAccess(stringIn).IsEndOfString()) break; - Detail::BufferTestManip(stringIn).Skip('\\'); + SF_TRY(Detail::BufferTestManip(stringIn).SkipOneOf('\\')); switch (stringIn.Get()) { // TODO : Do all others escape char case '"': - Detail::BufferOutManip(buffer).Pushback('"'); + SF_TRY(Detail::BufferOutManip(buffer).Pushback('"')); break; case 't': - Detail::BufferOutManip(buffer).Pushback('\t'); + SF_TRY(Detail::BufferOutManip(buffer).Pushback('\t')); break; case 'r': - Detail::BufferOutManip(buffer).Pushback('\r'); + SF_TRY(Detail::BufferOutManip(buffer).Pushback('\r')); break; case 'n': - Detail::BufferOutManip(buffer).Pushback('\n'); + SF_TRY(Detail::BufferOutManip(buffer).Pushback('\n')); break; default: break; } } - Detail::BufferOutManip(buffer).Pushback('"'); + SF_TRY(Detail::BufferOutManip(buffer).Pushback('"')); } }; } diff --git a/src/StreamFormat/FMT/Context/BasicContext/BasicArgsInterface.h b/src/StreamFormat/FMT/Context/BasicContext/BasicArgsInterface.h index 30cc38d8..01b0cf74 100644 --- a/src/StreamFormat/FMT/Context/BasicContext/BasicArgsInterface.h +++ b/src/StreamFormat/FMT/Context/BasicContext/BasicArgsInterface.h @@ -1,7 +1,8 @@ #pragma once #include "StreamFormat/FMT/Detail/ConvertTraits.h" -#include "StreamFormat/FMT/Detail/Detail.h" +#include "StreamFormat/FMT/Detail/Prelude.h" +#include "StreamFormat/FMT/Buffer/BufferInfo.h" #include #include @@ -35,30 +36,27 @@ namespace StreamFormat::FMT::Detail virtual size_t Size() = 0; public: - virtual void RunTypeAtIndex(std::int32_t idx) = 0; - - virtual std::int32_t GetIndexOfCurrentNamedArg(BufferInfoView& format) = 0; - virtual std::int32_t GetFormatIndexAt(std::int32_t idx) = 0; - - virtual PointerID GetTypeAt(std::int32_t idx) = 0; - virtual typename std::basic_string_view GetStringAt(std::int32_t idx) = 0; - virtual int64_t GetIntAt(std::int32_t idx) = 0; + [[nodiscard]] virtual std::expected GetPointerIDAt(std::int32_t idx) = 0; + [[nodiscard]] virtual std::expected RunTypeAtIndex(std::int32_t idx) = 0; + [[nodiscard]] virtual std::expected GetIndexOfCurrentNamedArg(BufferInfoView& format) = 0; + [[nodiscard]] virtual std::expected, FMTResult> GetStringAt(std::int32_t idx) = 0; + [[nodiscard]] virtual std::expected GetIntAt(std::int32_t idx) = 0; public: template - const T* GetTypeAtIndex(std::int32_t idx) + [[nodiscard]] std::expected GetTypeAt(std::int32_t idx) { - PointerID ptr = GetTypeAt(idx); + PointerID ptr = SF_TRY(GetPointerIDAt(idx)); if (ptr.TypeInfo != typeid(T)) - return nullptr; - return static_cast(ptr.Ptr); + { return std::unexpected(FMTResult::ArgsInterface_InvalidTypeID); } + return reinterpret_cast(ptr.Ptr); } template - void RunFuncFromTypeAtIndex(std::int32_t idx, std::function func) + [[nodiscard]] std::expected RunFuncFromTypeAtIndex(std::int32_t idx, std::function func) { - const T* value = GetTypeAtIndex(idx); - if (value != nullptr) func(*value); + const T* value = SF_TRY(GetTypeAt(idx)); + func(*value); } }; @@ -73,13 +71,10 @@ namespace StreamFormat::FMT::Detail size_t Size() override { return 0; } public: - void RunTypeAtIndex(std::int32_t) override {} - - std::int32_t GetIndexOfCurrentNamedArg(BufferInfoView& format) override { return std::int32_t{-1}; } - std::int32_t GetFormatIndexAt(std::int32_t) override { return std::int32_t{-1}; } - - PointerID GetTypeAt(std::int32_t) override { return PointerID{.TypeInfo = typeid(void), .Ptr = nullptr}; } - std::basic_string_view GetStringAt(std::int32_t) override { return ""; } - std::int64_t GetIntAt(std::int32_t) override { return 0; } + [[nodiscard]] std::expected GetPointerIDAt(std::int32_t) override { return std::unexpected(FMTResult::ArgsInterface_Unavaible); } + [[nodiscard]] std::expected RunTypeAtIndex(std::int32_t) override { return std::unexpected(FMTResult::ArgsInterface_Unavaible); } + [[nodiscard]] std::expected GetIndexOfCurrentNamedArg(BufferInfoView& format) override { return std::unexpected(FMTResult::ArgsInterface_Unavaible); } + [[nodiscard]] std::expected, FMTResult> GetStringAt(std::int32_t) override { return std::unexpected(FMTResult::ArgsInterface_Unavaible); } + [[nodiscard]] std::expected GetIntAt(std::int32_t) override { return std::unexpected(FMTResult::ArgsInterface_Unavaible); } }; } diff --git a/src/StreamFormat/FMT/Context/BasicContext/BasicContext.h b/src/StreamFormat/FMT/Context/BasicContext/BasicContext.h index 59d1754a..9e0dc3e7 100644 --- a/src/StreamFormat/FMT/Context/BasicContext/BasicContext.h +++ b/src/StreamFormat/FMT/Context/BasicContext/BasicContext.h @@ -1,7 +1,7 @@ #pragma once #include "StreamFormat/FMT/Detail/ConvertTraits.h" -#include "StreamFormat/FMT/Detail/Detail.h" +#include "StreamFormat/FMT/Detail/Prelude.h" #include "StreamFormat/FMT/Buffer/BufferInfo.h" #include "StreamFormat/FMT/Buffer/BufferManip.h" @@ -29,8 +29,8 @@ namespace StreamFormat::FMT::Context virtual ~ContextExecutor() = default; public: - virtual void ExecSettings() = 0; - virtual Detail::BufferManipResult ExecRawString(std::basic_string_view) = 0; + [[nodiscard]] virtual std::expected ExecSettings() = 0; + [[nodiscard]] virtual std::expected ExecRawString(std::basic_string_view) = 0; public: Detail::FormatData Data; @@ -59,28 +59,27 @@ namespace StreamFormat::FMT::Context std::int32_t ValuesIndex; public: - void Run(); + [[nodiscard]] std::expected Run(); public: - Detail::BufferManipResult GetFormatIndex(std::int32_t& idx); - + [[nodiscard]] std::expected GetFormatIndex(); template - Detail::BufferManipResult FormatReadParameter(T& i, const T& defaultValue); + [[nodiscard]] std::expected FormatReadParameter(const T& defaultValue); - public: - void FormatDataApplyNextOverride(); + protected: + std::expected FormatDataApplyNextOverride(); protected: std::basic_string_view ParseNextOverrideFormatData(); - void ParseFormatDataBase(); - void ParseFormatDataSpecial(); - void ParseFormatDataSpecial_ShiftType(const Detail::ShiftInfo::ShiftType type); - void ParseFormatDataCustom(); - void ParseFormatData(); + [[nodiscard]] std::expected ParseFormatDataBase(); + [[nodiscard]] std::expected ParseFormatDataSpecial(); + [[nodiscard]] std::expected ParseFormatDataSpecial_ShiftType(const Detail::ShiftInfo::ShiftType type); + [[nodiscard]] std::expected ParseFormatDataCustom(); + [[nodiscard]] std::expected ParseFormatData(); - void ParseVariable(std::int32_t formatIdx); - bool Parse(); + [[nodiscard]] std::expected ParseVariable(std::int32_t formatIdx); + [[nodiscard]] std::expected Parse(); public: template @@ -111,7 +110,7 @@ namespace StreamFormat::FMT::Context {} template - void BasicContext::Run() + std::expected BasicContext::Run() { while (!Detail::BufferAccess(Format).IsEndOfString()) { @@ -122,13 +121,13 @@ namespace StreamFormat::FMT::Context ++sizeContinousString; Detail::BufferManip(Format).Forward(); } - Executor.ExecRawString(std::basic_string_view(beginContinousString, sizeContinousString)); + SF_TRY(Executor.ExecRawString(std::basic_string_view(beginContinousString, sizeContinousString))); if (Detail::BufferAccess(Format).IsEndOfString() == false && Detail::BufferTestAccess(Format).IsEqualTo('{')) { bool parseArg = Parse(); if (parseArg == false) - Executor.ExecRawString("{").ThrowIfFailed(); + SF_TRY(Executor.ExecRawString("{")); } } } @@ -147,19 +146,18 @@ namespace StreamFormat::FMT::Context template template - Detail::BufferManipResult BasicContext::FormatReadParameter(T& i, const T& defaultValue) + [[nodiscard]] std::expected BasicContext::FormatReadParameter(const T& defaultValue) { if (!Detail::BufferTestAccess(Format).IsEqualTo('{')) { - if (Detail::BufferReadManip(Format).FastReadInteger(i) == false) - i = defaultValue; - return true; + T t; + SF_TRY(Detail::BufferReadManip(Format).FastReadInteger(t)); + return t; } // SubIndex - std::int32_t formatIdx = 0; - if (GetFormatIndex(formatIdx) == false) return false; - Detail::BufferTestManip(Format).IsEqualToForward('}'); + std::int32_t formatIdx = SF_TRY(GetFormatIndex(formatIdx)); + SF_TRY(Detail::BufferTestManip(Format).SkipOneOf('}')); if constexpr (std::is_convertible_v) i = static_cast(ArgsInterface.GetIntAt(formatIdx)); else if constexpr (std::is_convertible_v>) diff --git a/src/StreamFormat/FMT/Context/BasicContext/BasicContextParse-impl.h b/src/StreamFormat/FMT/Context/BasicContext/BasicContextParse-impl.h index 836f0352..0327f784 100644 --- a/src/StreamFormat/FMT/Context/BasicContext/BasicContextParse-impl.h +++ b/src/StreamFormat/FMT/Context/BasicContext/BasicContextParse-impl.h @@ -25,7 +25,7 @@ namespace StreamFormat::FMT::Context Detail::FMTBufferParamsManip(Format).ParamGoTo('{'); const TChar* begin = Format.CurrentPos; - manip.IsEqualToForward('{').ThrowIfFailed(); + SF_TRY(manip.IsEqualToForward('{')); int scopes = 0; while (Detail::FMTBufferParamsManip(Format).IsEndOfParameter() == false || scopes > 0) { @@ -37,13 +37,13 @@ namespace StreamFormat::FMT::Context else if (scopes > 0 && manip.IsEqualToForward('}')) scopes--; } - manip.IsEqualToForward('}').ThrowIfFailed(); + SF_TRY(manip.IsEqualToForward('}')); const TChar* end = Format.CurrentPos; return std::basic_string_view(begin, end - begin); } template - void BasicContext::ParseFormatDataBase() + std::expected BasicContext::ParseFormatDataBase() { Detail::BufferTestManip manip(Format); @@ -62,21 +62,21 @@ namespace StreamFormat::FMT::Context } template - void BasicContext::ParseFormatDataSpecial_ShiftType(const Detail::ShiftInfo::ShiftType type) + std::expected BasicContext::ParseFormatDataSpecial_ShiftType(const Detail::ShiftInfo::ShiftType type) { Executor.Data.Shift.Type = type; - FormatReadParameter(Executor.Data.Shift.Size, -1); + Executor.Data.Shift.Size = SF_TRY(FormatReadParameter(-1)); if (Detail::BufferTestManip(Format).IsEqualToForward(':')) { - Executor.Data.Shift.Print.Before = Detail::BufferManip(Format).ThrowIfFailed().GetAndForward(); + Executor.Data.Shift.Print.Before = SF_TRY(Detail::BufferManip(Format).GetAndForward()); Executor.Data.Shift.Print.After = Executor.Data.Shift.Print.Before; - if (Detail::BufferTestManip(Format).IsEqualToForward('|')) - Executor.Data.Shift.Print.After = Detail::BufferManip(Format).ThrowIfFailed().GetAndForward(); + if (SF_TRY(Detail::BufferTestManip(Format).IsEqualToForward('|'))) + Executor.Data.Shift.Print.After = SF_TRY(Detail::BufferManip(Format).GetAndForward()); } } template - void BasicContext::ParseFormatDataSpecial() + std::expected BasicContext::ParseFormatDataSpecial() { Detail::BufferTestAccess access(Format); Detail::BufferTestManip manip(Format); @@ -86,19 +86,22 @@ namespace StreamFormat::FMT::Context std::int32_t formatIndex = 0; if (GetFormatIndex(formatIndex) == false) return; - if ((Executor.Data.TestApply(ArgsInterface.template GetTypeAtIndex>(formatIndex)) || - Executor.Data.TestApply(ArgsInterface.template GetTypeAtIndex>(formatIndex)) || - Executor.Data.TestApply(ArgsInterface.template GetTypeAtIndex(formatIndex)) || - Executor.Data.TestApply(ArgsInterface.template GetTypeAtIndex(formatIndex))) == false) - throw Detail::FMTGivenTypeError{}; - manip.IsEqualToForward('}'); + if ((Executor.Data.TestApply(ArgsInterface.template GetTypeAt>(formatIndex)) || + Executor.Data.TestApply(ArgsInterface.template GetTypeAt>(formatIndex)) || + Executor.Data.TestApply(ArgsInterface.template GetTypeAt(formatIndex)) || + Executor.Data.TestApply(ArgsInterface.template GetTypeAt(formatIndex))) == false) + return std::unexpected(FMTResult::CannotApplyType); + SF_TRY(manip.IsEqualToForward('}')); } else if (manip.IsEqualToForward('.')) - FormatReadParameter(Executor.Data.FloatPrecision, -1); + Executor.Data.FloatPrecision = SF_TRY(FormatReadParameter(-1)); else if (access.IsEqualTo('d', 'b', 'B', 'o', 'O', 'x', 'X')) - Executor.Data.IntegerPrint = static_cast(Detail::BufferManip(Format).ThrowIfFailed().GetAndForward()); + { + auto get = SF_TRY(Detail::BufferManip(Format).GetAndForward()); + Executor.Data.IntegerPrint = static_cast(get); + } else if (manip.IsEqualToForward('#')) Executor.Data.PrefixSuffix = true; @@ -123,7 +126,7 @@ namespace StreamFormat::FMT::Context } template - void BasicContext::ParseFormatDataCustom() + [[nodiscard]] std::expected BasicContext::ParseFormatDataCustom() { Detail::BufferTestAccess access(Format); Detail::BufferTestManip manip(Format); @@ -162,7 +165,7 @@ namespace StreamFormat::FMT::Context /////---------- Impl ----------///// template - void BasicContext::ParseFormatData() + [[nodiscard]] std::expected BasicContext::ParseFormatData() { Detail::BufferTestAccess access(Format); Detail::BufferTestManip manip(Format); @@ -185,7 +188,7 @@ namespace StreamFormat::FMT::Context } template - Detail::BufferManipResult BasicContext::GetFormatIndex(std::int32_t& idx) + std::expected BasicContext::GetFormatIndex() { const TChar* mainSubFormat = Format.CurrentPos; @@ -202,7 +205,7 @@ namespace StreamFormat::FMT::Context // II: A number(idx) std::int32_t subIndex = -1; - if (Detail::BufferReadManip(Format).FastReadInteger(subIndex)) + if (Detail::BufferReadManip(Format).FastReadInteger(subIndex).has_value()) if (access.IsEqualTo(':') || access.IsEqualTo('}')) if (subIndex >= 0 && subIndex < ArgsInterface.Size()) { @@ -212,27 +215,30 @@ namespace StreamFormat::FMT::Context Format.CurrentPos = mainSubFormat; // III : A name - std::int32_t indexOfNamedArg = ArgsInterface.GetIndexOfCurrentNamedArg(Format); - if (indexOfNamedArg >= 0 && indexOfNamedArg < ArgsInterface.Size()) + auto currentNamedArg = ArgsInterface.GetIndexOfCurrentNamedArg(Format); + if (currentNamedArg.has_value()) { - idx = indexOfNamedArg; - return true; + std::int32_t indexOfNamedArg = currentNamedArg.value(); + if (indexOfNamedArg >= 0 && indexOfNamedArg < ArgsInterface.Size()) + { + idx = indexOfNamedArg; + return true; + } + Format.CurrentPos = mainSubFormat; } - Format.CurrentPos = mainSubFormat; // VI : { which is a idx to an argument - if (manip.IsEqualToForward('{')) + if (access.IsEqualTo('{')) { - std::int32_t recIndex = -1; - if (GetFormatIndex(recIndex) == false) - return false; - - if (manip.IsEqualToForward('}') && recIndex >= 0 && recIndex < ArgsInterface.Size()) + SF_TRY(Detail::BufferManip(Format).Forward()); + std::int32_t recIndex = SF_TRY(GetFormatIndex()); + if (manip.IsEqualTo('}') && recIndex >= 0 && recIndex < ArgsInterface.Size()) { + SF_TRY(Detail::BufferManip(Format).Forward()); manip.SkipAllSpaces(); if (access.IsEqualTo(':', '}')) { - std::int32_t finalRecIndex = ArgsInterface.GetFormatIndexAt(recIndex); + std::int32_t finalRecIndex = SF_TRY(ArgsInterface.GetFormatIndexAt(recIndex)); if (finalRecIndex >= 0 && finalRecIndex < ArgsInterface.Size()) return finalRecIndex; return false; @@ -240,11 +246,12 @@ namespace StreamFormat::FMT::Context } } Format.CurrentPos = mainSubFormat; - return false; + + return std::unexpected(FMTResult::ArgumentIndexResolution); } template - void BasicContext::ParseVariable(std::int32_t formatIdx) + [[nodiscard]] std::expected BasicContext::ParseVariable(std::int32_t formatIdx) { Detail::FormatData saveFormatData = Executor.Data; Executor.Data = Detail::FormatData{}; @@ -265,7 +272,7 @@ namespace StreamFormat::FMT::Context } template - bool BasicContext::Parse() + [[nodiscard]] std::expected BasicContext::Parse() { Detail::BufferManip(Format).Forward(); // Skip { diff --git a/src/StreamFormat/FMT/Context/BasicContext/ITextPropertiesExecutor.h b/src/StreamFormat/FMT/Context/BasicContext/ITextPropertiesExecutor.h index e010ee11..cdf0151e 100644 --- a/src/StreamFormat/FMT/Context/BasicContext/ITextPropertiesExecutor.h +++ b/src/StreamFormat/FMT/Context/BasicContext/ITextPropertiesExecutor.h @@ -1,6 +1,6 @@ #pragma once -#include "StreamFormat/FMT/Detail/Detail.h" +#include "StreamFormat/FMT/Detail/Prelude.h" #include "StreamFormat/FMT/TextProperties/TextProperties.h" namespace StreamFormat::FMT::Detail @@ -14,35 +14,35 @@ namespace StreamFormat::FMT::Detail virtual void LinkToExecutor(void* executor) = 0; public: - virtual void AllPropertiesReset() = 0; + [[nodiscard]] virtual std::expected AllPropertiesReset() = 0; public: - virtual void ResetColor() = 0; - virtual void ExecuteColor(const TextProperties::TextColor::BasicColorFG& t) = 0; - virtual void ExecuteColor(const TextProperties::TextColor::BasicColorBG& t) = 0; - virtual void ExecuteColor(const TextProperties::TextColor::BasicColor& t) = 0; - virtual void ExecuteColor(const TextProperties::TextColor::Color24bFG& t) = 0; - virtual void ExecuteColor(const TextProperties::TextColor::Color24bBG& t) = 0; - virtual void ExecuteColor(const TextProperties::TextColor::Color24b& t) = 0; - virtual void ExecuteColor(const TextProperties::TextColor::ColorCubeFG& t) = 0; - virtual void ExecuteColor(const TextProperties::TextColor::ColorCubeBG& t) = 0; - virtual void ExecuteColor(const TextProperties::TextColor::ColorCube& t) = 0; + [[nodiscard]] virtual std::expected ResetColor() = 0; + [[nodiscard]] virtual std::expected ExecuteColor(const TextProperties::TextColor::BasicColorFG& t) = 0; + [[nodiscard]] virtual std::expected ExecuteColor(const TextProperties::TextColor::BasicColorBG& t) = 0; + [[nodiscard]] virtual std::expected ExecuteColor(const TextProperties::TextColor::BasicColor& t) = 0; + [[nodiscard]] virtual std::expected ExecuteColor(const TextProperties::TextColor::Color24bFG& t) = 0; + [[nodiscard]] virtual std::expected ExecuteColor(const TextProperties::TextColor::Color24bBG& t) = 0; + [[nodiscard]] virtual std::expected ExecuteColor(const TextProperties::TextColor::Color24b& t) = 0; + [[nodiscard]] virtual std::expected ExecuteColor(const TextProperties::TextColor::ColorCubeFG& t) = 0; + [[nodiscard]] virtual std::expected ExecuteColor(const TextProperties::TextColor::ColorCubeBG& t) = 0; + [[nodiscard]] virtual std::expected ExecuteColor(const TextProperties::TextColor::ColorCube& t) = 0; public: - virtual void ResetFront() = 0; - virtual void ExecuteFront(const TextProperties::TextFront::FrontID& t) = 0; + [[nodiscard]] virtual std::expected ResetFront() = 0; + [[nodiscard]] virtual std::expected ExecuteFront(const TextProperties::TextFront::FrontID& t) = 0; public: - virtual void ResetStyle() = 0; - virtual void ExecuteStyle(const TextProperties::TextStyle::Intensity& t) = 0; - virtual void ExecuteStyle(const TextProperties::TextStyle::Italic& t) = 0; - virtual void ExecuteStyle(const TextProperties::TextStyle::Underline& t) = 0; - virtual void ExecuteStyle(const TextProperties::TextStyle::UnderlineColor::Color& t) = 0; - virtual void ExecuteStyle(const TextProperties::TextStyle::UnderlineColor::ColorCube& t) = 0; - virtual void ExecuteStyle(const TextProperties::TextStyle::UnderlineColor::Color24b& t) = 0; - virtual void ExecuteStyle(const TextProperties::TextStyle::Blink& t) = 0; - virtual void ExecuteStyle(const TextProperties::TextStyle::Inverted& t) = 0; - virtual void ExecuteStyle(const TextProperties::TextStyle::Ideogram& t) = 0; - virtual void ExecuteStyle(const TextProperties::TextStyle::Script& t) = 0; + [[nodiscard]] virtual std::expected ResetStyle() = 0; + [[nodiscard]] virtual std::expected ExecuteStyle(const TextProperties::TextStyle::Intensity& t) = 0; + [[nodiscard]] virtual std::expected ExecuteStyle(const TextProperties::TextStyle::Italic& t) = 0; + [[nodiscard]] virtual std::expected ExecuteStyle(const TextProperties::TextStyle::Underline& t) = 0; + [[nodiscard]] virtual std::expected ExecuteStyle(const TextProperties::TextStyle::UnderlineColor::Color& t) = 0; + [[nodiscard]] virtual std::expected ExecuteStyle(const TextProperties::TextStyle::UnderlineColor::ColorCube& t) = 0; + [[nodiscard]] virtual std::expected ExecuteStyle(const TextProperties::TextStyle::UnderlineColor::Color24b& t) = 0; + [[nodiscard]] virtual std::expected ExecuteStyle(const TextProperties::TextStyle::Blink& t) = 0; + [[nodiscard]] virtual std::expected ExecuteStyle(const TextProperties::TextStyle::Inverted& t) = 0; + [[nodiscard]] virtual std::expected ExecuteStyle(const TextProperties::TextStyle::Ideogram& t) = 0; + [[nodiscard]] virtual std::expected ExecuteStyle(const TextProperties::TextStyle::Script& t) = 0; }; } diff --git a/src/StreamFormat/FMT/Context/BasicContext/TextPropertiesManager-impl.h b/src/StreamFormat/FMT/Context/BasicContext/TextPropertiesManager-impl.h index d483925c..d4c9f4b6 100644 --- a/src/StreamFormat/FMT/Context/BasicContext/TextPropertiesManager-impl.h +++ b/src/StreamFormat/FMT/Context/BasicContext/TextPropertiesManager-impl.h @@ -11,7 +11,7 @@ namespace StreamFormat::FMT::Detail { template - void Detail::TextPropertiesManager::ApplyColorOnIndex(Context::BasicContext& context, std::int32_t index) + std::expected Detail::TextPropertiesManager::ApplyColorOnIndex(Context::BasicContext& context, std::int32_t index) { context.ArgsInterface.template RunFuncFromTypeAtIndex( index, [this](const Detail::TextProperties::TextColor::Color& data) { this->ReloadColor(data); }); @@ -30,7 +30,7 @@ namespace StreamFormat::FMT::Detail } template - void Detail::TextPropertiesManager::ApplyFrontOnIndex(Context::BasicContext& context, std::int32_t index) + std::expected Detail::TextPropertiesManager::ApplyFrontOnIndex(Context::BasicContext& context, std::int32_t index) { context.ArgsInterface.template RunFuncFromTypeAtIndex( index, [this](const Detail::TextProperties::TextFront::Front& data) { this->ReloadFront(data); }); @@ -39,24 +39,24 @@ namespace StreamFormat::FMT::Detail } template - void Detail::TextPropertiesManager::ApplyStyleOnIndex(Context::BasicContext& context, std::int32_t index) + std::expected Detail::TextPropertiesManager::ApplyStyleOnIndex(Context::BasicContext& context, std::int32_t index) { context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextStyle::Style& data) { this->ReloadStyle(data); }); + index, [this](const Detail::TextProperties::TextStyle::Style& data) { return this->ReloadStyle(data); }); context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextStyle::Intensity& data) { this->AskApplyStyle(data); }); + index, [this](const Detail::TextProperties::TextStyle::Intensity& data) { return this->AskApplyStyle(data); }); context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextStyle::Italic& data) { this->AskApplyStyle(data); }); + index, [this](const Detail::TextProperties::TextStyle::Italic& data) { return this->AskApplyStyle(data); }); context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextStyle::Underline& data) { this->AskApplyStyle(data); }); + index, [this](const Detail::TextProperties::TextStyle::Underline& data) { return this->AskApplyStyle(data); }); context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextStyle::Blink& data) { this->AskApplyStyle(data); }); + index, [this](const Detail::TextProperties::TextStyle::Blink& data) { return this->AskApplyStyle(data); }); context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextStyle::Inverted& data) { this->AskApplyStyle(data); }); + index, [this](const Detail::TextProperties::TextStyle::Inverted& data) { return this->AskApplyStyle(data); }); context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextStyle::Ideogram& data) { this->AskApplyStyle(data); }); + index, [this](const Detail::TextProperties::TextStyle::Ideogram& data) { return this->AskApplyStyle(data); }); context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextStyle::Script& data) { this->AskApplyStyle(data); }); + index, [this](const Detail::TextProperties::TextStyle::Script& data) { return this->AskApplyStyle(data); }); context.ArgsInterface.template RunFuncFromTypeAtIndex( index, [this](const Detail::TextProperties::TextStyle::UnderlineColor::ColorCube& data) { this->AskApplyStyle(data); }); @@ -65,29 +65,28 @@ namespace StreamFormat::FMT::Detail } template - void Detail::TextPropertiesManager::ParseColor(Context::BasicContext& context) + std::expected Detail::TextPropertiesManager::ParseColor(Context::BasicContext& context) { if (BufferTestManip(context.Format).IsEqualToForward(':')) { BufferTestManip(context.Format).SkipAllSpaces(); if (BufferTestManip(context.Format).IsEqualToForward('{')) { - std::int32_t idx = 0; - context.GetFormatIndex(idx).ThrowIfFailed(); + std::int32_t idx = SF_TRY(context.GetFormatIndex()); ApplyColorOnIndex(context, idx); BufferTestManip(context.Format).IsEqualToForward('}'); } else { Detail::TextProperties::TextColor::BasicColorFG colorFg; - bool colorFgFound = GetColorCode(context.Format, colorFg); + bool colorFgFound = SF_TRY(GetColorCode(context.Format, colorFg)); FMTBufferParamsManip(context.Format).ParamGoTo('-', ','); if (BufferTestManip(context.Format).IsEqualToForward('-')) { BufferTestManip(context.Format).SkipAllSpaces(); Detail::TextProperties::TextColor::BasicColorBG colorBg; - bool colorBgFound = GetColorCode(context.Format, colorBg); + bool colorBgFound = SF_TRY(GetColorCode(context.Format, colorBg)); if (colorBgFound && colorFgFound) AskApplyColor(Detail::TextProperties::TextColor::BasicColor{colorFg, colorBg}); else @@ -107,10 +106,11 @@ namespace StreamFormat::FMT::Detail } template - void Detail::TextPropertiesManager::ParseStyle(Context::BasicContext& context) + std::expected Detail::TextPropertiesManager::ParseStyle(Context::BasicContext& context) { - if (BufferTestManip(context.Format).IsEqualToForward(':')) + if (BufferTestAccess(context.Format).IsEqualTo(':')) { + SF_TRY(BufferTestManip(context.Format).Forward()); if (!BufferTestAccess(context.Format).IsEqualTo('}', ',')) { bool l = true; @@ -119,8 +119,7 @@ namespace StreamFormat::FMT::Detail BufferTestManip(context.Format).SkipAllSpaces(); if (BufferTestManip(context.Format).IsEqualToForward('{')) { - std::int32_t idx = 0; - context.GetFormatIndex(idx).ThrowIfFailed(); + std::int32_t idx = SF_TRY(context.GetFormatIndex(idx)); ApplyStyleOnIndex(context, idx); BufferTestManip(context.Format).IsEqualToForward('}'); } @@ -129,19 +128,19 @@ namespace StreamFormat::FMT::Detail ParseStyleNamed(context.Format); } FMTBufferParamsManip(context.Format).ParamGoTo('|', ','); - l = BufferTestManip(context.Format).IsEqualToForward('|'); + l = SF_TRY(BufferTestManip(context.Format).IsEqualToForward('|')); BufferTestManip(context.Format).SkipAllSpaces(); } } else - ReloadDefaultStyle(); + return ReloadDefaultStyle(); } else - ReloadDefaultStyle(); + return ReloadDefaultStyle(); } template - void Detail::TextPropertiesManager::ParseStyleNamed(BufferInfoView& format) + std::expected Detail::TextPropertiesManager::ParseStyleNamed(BufferInfoView& format) { Detail::BufferUtilsManip utils(format); @@ -183,20 +182,20 @@ namespace StreamFormat::FMT::Detail {"subscript", Detail::TextProperties::TextStyle::Script::Subscript}, {"n-script", Detail::TextProperties::TextStyle::Script::AllDisable}}; - std::uint8_t code = (std::uint8_t)BufferUtilsManip(format).GetWordFromDictPairs(styleIntensity, (Detail::TextProperties::TextStyle::Intensity)255); + std::uint8_t code = (std::uint8_t)BufferUtilsManip(format).GetWordFromDictPairs(styleIntensity); if (code != 255) return ApplyStyle(Detail::TextProperties::TextStyle::Intensity{code}); - code = (std::uint8_t)BufferUtilsManip(format).GetWordFromDictPairs(styleItalic, (Detail::TextProperties::TextStyle::Italic)255); + code = (std::uint8_t)BufferUtilsManip(format).GetWordFromDictPairs(styleItalic); if (code != 255) return ApplyStyle(Detail::TextProperties::TextStyle::Italic{code}); - code = (std::uint8_t)BufferUtilsManip(format).GetWordFromDictPairs(styleBlink, (Detail::TextProperties::TextStyle::Blink)255); + code = (std::uint8_t)BufferUtilsManip(format).GetWordFromDictPairs(styleBlink); if (code != 255) return ApplyStyle(Detail::TextProperties::TextStyle::Blink{code}); - code = (std::uint8_t)BufferUtilsManip(format).GetWordFromDictPairs(styleInverted, (Detail::TextProperties::TextStyle::Inverted)255); + code = (std::uint8_t)BufferUtilsManip(format).GetWordFromDictPairs(styleInverted); if (code != 255) return ApplyStyle(Detail::TextProperties::TextStyle::Inverted{code}); - code = (std::uint8_t)BufferUtilsManip(format).GetWordFromDictPairs(styleIdeogram, (Detail::TextProperties::TextStyle::Ideogram)255); + code = (std::uint8_t)BufferUtilsManip(format).GetWordFromDictPairs(styleIdeogram); if (code != 255) return ApplyStyle(Detail::TextProperties::TextStyle::Ideogram{code}); - code = (std::uint8_t)BufferUtilsManip(format).GetWordFromDictPairs(styleScript, (Detail::TextProperties::TextStyle::Script)255); + code = (std::uint8_t)BufferUtilsManip(format).GetWordFromDictPairs(styleScript); if (code != 255) return ApplyStyle(Detail::TextProperties::TextStyle::Script{code}); - code = (std::uint8_t)BufferUtilsManip(format).GetWordFromDictPairs(styleUnderline, (Detail::TextProperties::TextStyle::Underline)255); + code = (std::uint8_t)BufferUtilsManip(format).GetWordFromDictPairs(styleUnderline); if (code != 255) { if (code == (std::uint8_t)Detail::TextProperties::TextStyle::Underline::SelectUnderlinedColor) @@ -209,29 +208,28 @@ namespace StreamFormat::FMT::Detail } template - TextProperties::TextStyle::UnderlineColor::ColorCube TextPropertiesManager::SelectUnderlinedColorStyle(BufferInfoView& format) + std::expected TextPropertiesManager::SelectUnderlinedColorStyle(BufferInfoView& format) { - FMTBufferParamsManip(format).ParamGoTo(':'); - BufferTestManip(format).IsEqualToForward(':'); - BufferTestManip(format).SkipAllSpaces(); - Detail::TextProperties::TextStyle::UnderlineColor::ColorCube color; - if (GetColorCode(format, color)) return color; - // TODO : handle Color24b - return Detail::TextProperties::TextStyle::UnderlineColor::ColorCube{}; + // TODO + // FIXME + return std::unexpected(FMTResult::FunctionNotImpl); } template - void Detail::TextPropertiesManager::ParseFront(Context::BasicContext& context) + std::expected Detail::TextPropertiesManager::ParseFront(Context::BasicContext& context) { static constexpr std::string_view frontCode[] = {"default", "front0", "front1", "front2", "front3", "front4", "front5", "front6", "front7", "front8", "front9"}; - if (BufferTestManip(context.Format).IsEqualToForward(':')) + if (BufferTestManip(context.Format).IsEqualTo(':')) { + SF_TRY(BufferManip(context.Format).Forward()); BufferTestManip(context.Format).SkipAllSpaces(); - Detail::TextProperties::TextFront::FrontID frontID = (static_cast(BufferUtilsManip(context.Format).GetWordFromList(frontCode))); - ApplyFront(frontID); + + Detail::TextProperties::TextFront::FrontID frontID = (std::uint8_t)SF_TRY(BufferUtilsManip(context.Format).GetWordFromList(frontCode)); + return ApplyFront(frontID); } else - ReloadDefaultFront(); + return ReloadDefaultFront(); + return {}; } } diff --git a/src/StreamFormat/FMT/Context/BasicContext/TextPropertiesManager.cpp b/src/StreamFormat/FMT/Context/BasicContext/TextPropertiesManager.cpp index bcef40f3..5e08461b 100644 --- a/src/StreamFormat/FMT/Context/BasicContext/TextPropertiesManager.cpp +++ b/src/StreamFormat/FMT/Context/BasicContext/TextPropertiesManager.cpp @@ -2,21 +2,18 @@ namespace StreamFormat::FMT::Detail { - void TextPropertiesApplyManager::ReloadColorFG(const TextProperties::TextColor::ColorFG& target) + std::expected TextPropertiesApplyManager::ReloadColorFG(const TextProperties::TextColor::ColorFG& target) { if (target.Type != m_CurrentContextProperties.Color.Fg.Type) { switch (target.Type) { case TextProperties::TextColor::ColorType::BasicColor: - ApplyColor(target.Data.BasicColor); - break; + return ApplyColor(target.Data.BasicColor); case TextProperties::TextColor::ColorType::ColorCube: - ApplyColor(target.Data.ColorCube); - break; + return ApplyColor(target.Data.ColorCube); case TextProperties::TextColor::ColorType::Color24b: - ApplyColor(target.Data.Color24b); - break; + return ApplyColor(target.Data.Color24b); } } else @@ -24,33 +21,34 @@ namespace StreamFormat::FMT::Detail switch (target.Type) { case TextProperties::TextColor::ColorType::BasicColor: - if (m_CurrentContextProperties.Color.Fg.Data.BasicColor != target.Data.BasicColor) ApplyColor(target.Data.BasicColor); + if (m_CurrentContextProperties.Color.Fg.Data.BasicColor != target.Data.BasicColor) + return ApplyColor(target.Data.BasicColor); break; case TextProperties::TextColor::ColorType::ColorCube: - if (m_CurrentContextProperties.Color.Fg.Data.ColorCube != target.Data.ColorCube) ApplyColor(target.Data.ColorCube); + if (m_CurrentContextProperties.Color.Fg.Data.ColorCube != target.Data.ColorCube) + return ApplyColor(target.Data.ColorCube); break; case TextProperties::TextColor::ColorType::Color24b: - if (m_CurrentContextProperties.Color.Fg.Data.Color24b != target.Data.Color24b) ApplyColor(target.Data.Color24b); + if (m_CurrentContextProperties.Color.Fg.Data.Color24b != target.Data.Color24b) + return ApplyColor(target.Data.Color24b); break; } } + return {}; } - void TextPropertiesApplyManager::ReloadColorBG(const TextProperties::TextColor::ColorBG& target) + std::expected TextPropertiesApplyManager::ReloadColorBG(const TextProperties::TextColor::ColorBG& target) { if (target.Type != m_CurrentContextProperties.Color.Bg.Type) { switch (target.Type) { case TextProperties::TextColor::ColorType::BasicColor: - ApplyColor(target.Data.BasicColor); - break; + return ApplyColor(target.Data.BasicColor); case TextProperties::TextColor::ColorType::ColorCube: - ApplyColor(target.Data.ColorCube); - break; + return ApplyColor(target.Data.ColorCube); case TextProperties::TextColor::ColorType::Color24b: - ApplyColor(target.Data.Color24b); - break; + return ApplyColor(target.Data.Color24b); } } else @@ -58,48 +56,52 @@ namespace StreamFormat::FMT::Detail switch (target.Type) { case TextProperties::TextColor::ColorType::BasicColor: - if (m_CurrentContextProperties.Color.Bg.Data.BasicColor != target.Data.BasicColor) ApplyColor(target.Data.BasicColor); + if (m_CurrentContextProperties.Color.Bg.Data.BasicColor != target.Data.BasicColor) + return ApplyColor(target.Data.BasicColor); break; case TextProperties::TextColor::ColorType::ColorCube: - if (m_CurrentContextProperties.Color.Bg.Data.ColorCube != target.Data.ColorCube) ApplyColor(target.Data.ColorCube); + if (m_CurrentContextProperties.Color.Bg.Data.ColorCube != target.Data.ColorCube) + return ApplyColor(target.Data.ColorCube); break; case TextProperties::TextColor::ColorType::Color24b: - if (m_CurrentContextProperties.Color.Bg.Data.Color24b != target.Data.Color24b) ApplyColor(target.Data.Color24b); + if (m_CurrentContextProperties.Color.Bg.Data.Color24b != target.Data.Color24b) + return ApplyColor(target.Data.Color24b); break; } } + return {}; } - void TextPropertiesApplyManager::ReloadStyle(const TextProperties::TextStyle::Style& target) + std::expected TextPropertiesApplyManager::ReloadStyle(const TextProperties::TextStyle::Style& target) { if (target.Intensity != m_CurrentContextProperties.Style.Intensity) { - ApplyStyle(target.Intensity); + SF_TRY(ApplyStyle(target.Intensity)); m_CurrentContextProperties.Style.Intensity = target.Intensity; } if (target.Italic != m_CurrentContextProperties.Style.Italic) { - ApplyStyle(target.Italic); + SF_TRY(ApplyStyle(target.Italic)); m_CurrentContextProperties.Style.Italic = target.Italic; } if (target.Blink != m_CurrentContextProperties.Style.Blink) { - ApplyStyle(target.Blink); + SF_TRY(ApplyStyle(target.Blink)); m_CurrentContextProperties.Style.Blink = target.Blink; } if (target.Inverted != m_CurrentContextProperties.Style.Inverted) { - ApplyStyle(target.Inverted); + SF_TRY(ApplyStyle(target.Inverted)); m_CurrentContextProperties.Style.Inverted = target.Inverted; } if (target.Ideogram != m_CurrentContextProperties.Style.Ideogram) { - ApplyStyle(target.Ideogram); + SF_TRY(ApplyStyle(target.Ideogram)); m_CurrentContextProperties.Style.Ideogram = target.Ideogram; } if (target.Script != m_CurrentContextProperties.Style.Script) { - ApplyStyle(target.Script); + SF_TRY(ApplyStyle(target.Script)); m_CurrentContextProperties.Style.Script = target.Script; } @@ -114,14 +116,14 @@ namespace StreamFormat::FMT::Detail switch (target.UnderlineColor.Type) { case TextProperties::TextStyle::UnderlineColor::ColorType::Default: - ApplyStyle(TextProperties::TextStyle::UnderlineColor::ColorCube{TextProperties::TextStyle::UnderlineColor::ColorCube::Default}); + SF_TRY(ApplyStyle(TextProperties::TextStyle::UnderlineColor::ColorCube{TextProperties::TextStyle::UnderlineColor::ColorCube::Default})); break; case TextProperties::TextStyle::UnderlineColor::ColorType::ColorCube: - ApplyStyle(target.UnderlineColor.Data.ColorCube); + SF_TRY(ApplyStyle(target.UnderlineColor.Data.ColorCube)); m_CurrentContextProperties.Style.UnderlineColor.Data.ColorCube = target.UnderlineColor.Data.ColorCube; break; case TextProperties::TextStyle::UnderlineColor::ColorType::Color24b: - ApplyStyle(target.UnderlineColor.Data.Color24b); + SF_TRY(ApplyStyle(target.UnderlineColor.Data.Color24b)); m_CurrentContextProperties.Style.UnderlineColor.Data.Color24b = target.UnderlineColor.Data.Color24b; break; } @@ -136,26 +138,29 @@ namespace StreamFormat::FMT::Detail case TextProperties::TextStyle::UnderlineColor::ColorType::ColorCube: if (m_CurrentContextProperties.Style.UnderlineColor.Data.ColorCube != target.UnderlineColor.Data.ColorCube) { - ApplyStyle(target.UnderlineColor.Data.ColorCube); + SF_TRY(ApplyStyle(target.UnderlineColor.Data.ColorCube)); m_CurrentContextProperties.Style.UnderlineColor.Data.ColorCube = target.UnderlineColor.Data.ColorCube; } break; case TextProperties::TextStyle::UnderlineColor::ColorType::Color24b: if (m_CurrentContextProperties.Style.UnderlineColor.Data.Color24b != target.UnderlineColor.Data.Color24b) { - ApplyStyle(target.UnderlineColor.Data.Color24b); + SF_TRY(ApplyStyle(target.UnderlineColor.Data.Color24b)); m_CurrentContextProperties.Style.UnderlineColor.Data.Color24b = target.UnderlineColor.Data.Color24b; } break; } } + return {}; } - void TextPropertiesApplyManager::ReloadFront(const TextProperties::TextFront::Front& target) + std::expected TextPropertiesApplyManager::ReloadFront(const TextProperties::TextFront::Front& target) { - if (m_CurrentContextProperties.Front == target) return; + if (m_CurrentContextProperties.Front == target) + return {}; - ApplyFront(target.CurrentID); + SF_TRY(ApplyFront(target.CurrentID)); m_CurrentContextProperties.Front = target; + return {}; } } diff --git a/src/StreamFormat/FMT/Context/BasicContext/TextPropertiesManager.h b/src/StreamFormat/FMT/Context/BasicContext/TextPropertiesManager.h index f7b9539e..437b87b8 100644 --- a/src/StreamFormat/FMT/Context/BasicContext/TextPropertiesManager.h +++ b/src/StreamFormat/FMT/Context/BasicContext/TextPropertiesManager.h @@ -1,6 +1,6 @@ #pragma once -#include "StreamFormat/FMT/Detail/Detail.h" +#include "StreamFormat/FMT/Detail/Prelude.h" #include "ITextPropertiesExecutor.h" #include "BasicArgsInterface.h" #include "StreamFormat/FMT/Buffer/BufferInfo.h" @@ -17,89 +17,89 @@ namespace StreamFormat::FMT::Detail , m_CurrentContextProperties{} {} - void Terminate() { ReloadDefault(); } + std::expected Terminate() { return ReloadDefault(); } public: template requires Detail::TextPropertiesColorCanApply - void ApplyColor(const T& modif) + std::expected ApplyColor(const T& modif) { m_CurrentContextProperties.Color.Apply(modif); - m_TextPropertiesExecutor.ExecuteColor(modif); + return m_TextPropertiesExecutor.ExecuteColor(modif); } template requires Detail::TextPropertiesStyleCanApply - void ApplyStyle(const T& modif) + std::expected ApplyStyle(const T& modif) { m_CurrentContextProperties.Style.Apply(modif); - m_TextPropertiesExecutor.ExecuteStyle(modif); + return m_TextPropertiesExecutor.ExecuteStyle(modif); } template requires Detail::TextPropertiesFrontCanApply - void ApplyFront(const T& modif) + std::expected ApplyFront(const T& modif) { m_CurrentContextProperties.Front.Apply(modif); - m_TextPropertiesExecutor.ExecuteFront(modif); + return m_TextPropertiesExecutor.ExecuteFront(modif); } - void AllPropertiesReset() + std::expected AllPropertiesReset() { - ApplyColorReset(); - ApplyStyleReset(); - ApplyFrontReset(); + SF_TRY(ApplyColorReset()); + SF_TRY(ApplyStyleReset()); + return ApplyFrontReset(); } - void ApplyColorReset() + std::expected ApplyColorReset() { m_CurrentContextProperties.Color.ModifyReset(); - m_TextPropertiesExecutor.ResetColor(); + return m_TextPropertiesExecutor.ResetColor(); } - void ApplyStyleReset() + std::expected ApplyStyleReset() { m_CurrentContextProperties.Style.ModifyReset(); - m_TextPropertiesExecutor.ResetStyle(); + return m_TextPropertiesExecutor.ResetStyle(); } - void ApplyFrontReset() + std::expected ApplyFrontReset() { m_CurrentContextProperties.Front.ModifyReset(); - m_TextPropertiesExecutor.ResetFront(); + return m_TextPropertiesExecutor.ResetFront(); } public: Detail::TextProperties::Properties Save() { return m_CurrentContextProperties; } public: - void ReloadDefault() + std::expected ReloadDefault() { ReloadDefaultColor(); ReloadDefaultStyle(); ReloadDefaultFront(); } - void ReloadDefaultColor() + std::expected ReloadDefaultColor() { ReloadDefaultColorFG(); ReloadDefaultColorBG(); } - void ReloadDefaultColorFG() { ReloadColorFG(Detail::TextProperties::TextColor::ColorFG{}); } - void ReloadDefaultColorBG() { ReloadColorBG(Detail::TextProperties::TextColor::ColorBG{}); } - void ReloadDefaultStyle() { ReloadStyle(Detail::TextProperties::TextStyle::Style{}); } - void ReloadDefaultFront() { ReloadFront(Detail::TextProperties::TextFront::Front{}); } + std::expected ReloadDefaultColorFG() { ReloadColorFG(Detail::TextProperties::TextColor::ColorFG{}); } + std::expected ReloadDefaultColorBG() { ReloadColorBG(Detail::TextProperties::TextColor::ColorBG{}); } + std::expected ReloadDefaultStyle() { ReloadStyle(Detail::TextProperties::TextStyle::Style{}); } + std::expected ReloadDefaultFront() { ReloadFront(Detail::TextProperties::TextFront::Front{}); } - void Reload(const Detail::TextProperties::Properties& target) + std::expected Reload(const Detail::TextProperties::Properties& target) { ReloadColor(target.Color); ReloadStyle(target.Style); ReloadFront(target.Front); } - void ReloadColor(const Detail::TextProperties::TextColor::Color& target) + std::expected ReloadColor(const Detail::TextProperties::TextColor::Color& target) { ReloadColorFG(target.Fg); ReloadColorBG(target.Bg); } - void ReloadColorFG(const Detail::TextProperties::TextColor::ColorFG& target); - void ReloadColorBG(const Detail::TextProperties::TextColor::ColorBG& target); - void ReloadStyle(const Detail::TextProperties::TextStyle::Style& target); - void ReloadFront(const Detail::TextProperties::TextFront::Front& target); + std::expected ReloadColorFG(const Detail::TextProperties::TextColor::ColorFG& target); + std::expected ReloadColorBG(const Detail::TextProperties::TextColor::ColorBG& target); + std::expected ReloadStyle(const Detail::TextProperties::TextStyle::Style& target); + std::expected ReloadFront(const Detail::TextProperties::TextFront::Front& target); public: ITextPropertiesExecutor& GetTextPropertiesExecutor() { return m_TextPropertiesExecutor; } @@ -112,24 +112,24 @@ namespace StreamFormat::FMT::Detail public: template requires Detail::TextPropertiesColorCanApply - inline void AskApplyColor(const T& modif) + inline std::expected AskApplyColor(const T& modif) { if (m_CurrentContextProperties.Color.NeedModif(modif)) ApplyColor(modif); } template requires Detail::TextPropertiesStyleCanApply - inline void AskApplyStyle(const T& modif) + inline std::expected AskApplyStyle(const T& modif) { if (m_CurrentContextProperties.Style.NeedModif(modif)) ApplyStyle(modif); } template requires Detail::TextPropertiesFrontCanApply - inline void AskApplyFront(const T& modif) + inline std::expected AskApplyFront(const T& modif) { if (m_CurrentContextProperties.Front.NeedModif(modif)) ApplyFront(modif); } - void AskApplyColor(const Detail::TextProperties::TextColor::BasicColor& modif) + std::expected AskApplyColor(const Detail::TextProperties::TextColor::BasicColor& modif) { if (m_CurrentContextProperties.Color.NeedModif(modif.Fg)) { @@ -139,7 +139,7 @@ namespace StreamFormat::FMT::Detail if (m_CurrentContextProperties.Color.NeedModif(modif.Fg)) return ApplyColor(modif.Bg); } - void AskApplyColor(const Detail::TextProperties::TextColor::ColorCube& modif) + std::expected AskApplyColor(const Detail::TextProperties::TextColor::ColorCube& modif) { if (m_CurrentContextProperties.Color.NeedModif(modif.Fg)) { @@ -149,7 +149,7 @@ namespace StreamFormat::FMT::Detail if (m_CurrentContextProperties.Color.NeedModif(modif.Fg)) return ApplyColor(modif.Bg); } - void AskApplyColor(const Detail::TextProperties::TextColor::Color24b& modif) + std::expected AskApplyColor(const Detail::TextProperties::TextColor::Color24b& modif) { if (m_CurrentContextProperties.Color.NeedModif(modif.Fg)) { @@ -159,9 +159,9 @@ namespace StreamFormat::FMT::Detail if (m_CurrentContextProperties.Color.NeedModif(modif.Fg)) return ApplyColor(modif.Bg); } - void AskApplyColor(const Detail::TextProperties::TextColor::ColorFG& modif) { ReloadColorFG(modif); } - void AskApplyColor(const Detail::TextProperties::TextColor::ColorBG& modif) { ReloadColorBG(modif); } - void AskApplyColor(const Detail::TextProperties::TextColor::Color& modif) { ReloadColor(modif); } + std::expected AskApplyColor(const Detail::TextProperties::TextColor::ColorFG& modif) { ReloadColorFG(modif); } + std::expected AskApplyColor(const Detail::TextProperties::TextColor::ColorBG& modif) { ReloadColorBG(modif); } + std::expected AskApplyColor(const Detail::TextProperties::TextColor::Color& modif) { ReloadColor(modif); } }; template @@ -173,20 +173,20 @@ namespace StreamFormat::FMT::Detail {} public: - void ApplyColorOnIndex(Context::BasicContext& context, std::int32_t index); - void ApplyStyleOnIndex(Context::BasicContext& context, std::int32_t index); - void ApplyFrontOnIndex(Context::BasicContext& context, std::int32_t index); + std::expected ApplyColorOnIndex(Context::BasicContext& context, std::int32_t index); + std::expected ApplyStyleOnIndex(Context::BasicContext& context, std::int32_t index); + std::expected ApplyFrontOnIndex(Context::BasicContext& context, std::int32_t index); public: - void ParseColor(Context::BasicContext& context); - void ParseStyle(Context::BasicContext& context); - void ParseFront(Context::BasicContext& context); + std::expected ParseColor(Context::BasicContext& context); + std::expected ParseStyle(Context::BasicContext& context); + std::expected ParseFront(Context::BasicContext& context); private: template - bool GetColorCode(BufferInfoView& format, T& t); - void ParseStyleNamed(BufferInfoView& format); - Detail::TextProperties::TextStyle::UnderlineColor::ColorCube SelectUnderlinedColorStyle(BufferInfoView& format); + std::expected GetColorCode(BufferInfoView& format, T& t); + std::expected ParseStyleNamed(BufferInfoView& format); + std::expected SelectUnderlinedColorStyle(BufferInfoView& format); }; } @@ -194,13 +194,13 @@ namespace StreamFormat::FMT::Detail { template template - bool Detail::TextPropertiesManager::GetColorCode(BufferInfoView& format, T& t) + std::expected Detail::TextPropertiesManager::GetColorCode(BufferInfoView& format) { static constexpr std::string_view colorCode[] = {"black", "red", "green", "yellow", "blue", "magenta", "cyan", "white", " ", "default"}; - std::uint8_t step = static_cast(BufferTestManip(format).IsEqualToForward('+') ? T::BaseBStep : T::BaseStep); - std::uint8_t code = static_cast(BufferUtilsManip(format).GetWordFromList(colorCode)); - if (code == BufferUtilsManip::GET_WORD_FROM_LIST_NOT_FOUND) return false; + bool bright = SF_TRY(BufferTestManip(format).IsEqualToForward('+')); + std::uint8_t step = static_cast(bright ? T::BaseBStep : T::BaseStep); + std::uint8_t code = (std::uint8_t)SF_TRY(BufferUtilsManip(format).GetWordFromList(colorCode));; t = static_cast(code + step); return true; } diff --git a/src/StreamFormat/FMT/Context/FormatterExecutor/BasicFormatterExecutor.h b/src/StreamFormat/FMT/Context/FormatterExecutor/BasicFormatterExecutor.h index f393eb3f..9ec10e73 100644 --- a/src/StreamFormat/FMT/Context/FormatterExecutor/BasicFormatterExecutor.h +++ b/src/StreamFormat/FMT/Context/FormatterExecutor/BasicFormatterExecutor.h @@ -26,7 +26,7 @@ namespace StreamFormat::FMT::Context BasicFormatterExecutor(Detail::FMTBufferOutInfo& bufferOut, Detail::ITextPropertiesExecutor& textPropertiesExecutor); ~BasicFormatterExecutor() override = default; - void Terminate(); + std::expected Terminate(); public: Detail::FMTBufferOutInfo& BufferOut; @@ -35,18 +35,21 @@ namespace StreamFormat::FMT::Context using ContextExecutor::TextManager; protected: - Detail::BufferManipResult ExecRawString(std::basic_string_view sv) override { Detail::BufferWriteManip(BufferOut).FastWriteString(sv); return true; } - void ExecSettings() override; + [[nodiscard]] std::expected ExecRawString(std::basic_string_view sv) override + { + return Detail::BufferWriteManip(BufferOut).FastWriteString(sv); + } + std::expected ExecSettings() override; public: template - void Run_(Detail::BufferInfoView format, Args&&... args); + std::expected Run_(Detail::BufferInfoView format, Args&&... args); template - void Run(Format&& format, Args&&... args); + std::expected Run(Format&& format, Args&&... args); public: template - inline void WriteType(Type&& type, Rest&&... rest) + inline std::expected WriteType(Type&& type, Rest&&... rest) { FormatterType>::Type, M_Type>::Format(std::forward(type), *this); if constexpr (sizeof...(rest) > 0) @@ -66,7 +69,7 @@ namespace StreamFormat::FMT::Context } template - void BasicFormatterExecutor::Terminate() + std::expected BasicFormatterExecutor::Terminate() { Detail::BufferOutManip(BufferOut).ComputeGeneratedSize(); @@ -76,7 +79,7 @@ namespace StreamFormat::FMT::Context } template - void BasicFormatterExecutor::ExecSettings() + std::expected BasicFormatterExecutor::ExecSettings() { // Indent auto indent = Data.Specifiers.Get("indent"); @@ -86,7 +89,7 @@ namespace StreamFormat::FMT::Context template template - void BasicFormatterExecutor::Run_(Detail::BufferInfoView format, Args&&... args) + std::expected BasicFormatterExecutor::Run_(Detail::BufferInfoView format, Args&&... args) { auto argsInterface = Detail::FormatterArgsInterface, Args...>(*this, std::forward(args)...); @@ -98,7 +101,7 @@ namespace StreamFormat::FMT::Context template template - void BasicFormatterExecutor::Run(Format&& formatInput, Args&&... args) + std::expected BasicFormatterExecutor::Run(Format&& formatInput, Args&&... args) { Run_(Detail::BufferInfoView{formatInput}, std::forward(args)...); } diff --git a/src/StreamFormat/FMT/Context/FormatterExecutor/FormatBasics-impl.h b/src/StreamFormat/FMT/Context/FormatterExecutor/FormatBasics-impl.h index 1ee9d417..2662a18c 100644 --- a/src/StreamFormat/FMT/Context/FormatterExecutor/FormatBasics-impl.h +++ b/src/StreamFormat/FMT/Context/FormatterExecutor/FormatBasics-impl.h @@ -13,7 +13,7 @@ namespace StreamFormat::FMT template struct FormatterType, FormatterExecutor> { - static void Format(const typename FormatterExecutor::Detail::template FormatSpecifier& specifier, FormatterExecutor& executor) + [[nodiscard]] static std::expected Format(const typename FormatterExecutor::Detail::template FormatSpecifier& specifier, FormatterExecutor& executor) { if (specifier.ValueIsText) executor.Run("{ '{}', '{}' }", specifier.Name, specifier.AsText); @@ -29,7 +29,7 @@ namespace StreamFormat::FMT namespace Detail::Forwarders { template - void FormatObjectArray(const T* const buffer, std::size_t totalsize, FormatterExecutor& executor) + [[nodiscard]] std::expected FormatObjectArray(const T* const buffer, std::size_t totalsize, FormatterExecutor& executor) { std::size_t beginIdx = (std::size_t)executor.Data.Specifiers.GetAsNumber("begin", 0); totalsize = executor.Data.Specifiers.GetAsNumber("totalsize", totalsize); @@ -64,7 +64,7 @@ namespace StreamFormat::FMT } template - void FormatString(const T* buffer, std::size_t size, FormatterExecutor& executor) + [[nodiscard]] std::expected FormatString(const T* buffer, std::size_t size, FormatterExecutor& executor) { std::size_t beginIdx = (std::size_t)executor.Data.Specifiers.GetAsNumber("begin", 0); size = executor.Data.Specifiers.GetAsNumber("size", size); @@ -98,7 +98,7 @@ namespace StreamFormat::FMT template struct FormatterType { - static void Format(const bool t, FormatterExecutor& executor) + [[nodiscard]] static std::expected Format(const bool t, FormatterExecutor& executor) { if (executor.Data.PrefixSuffix) { @@ -121,21 +121,24 @@ namespace StreamFormat::FMT requires (std::is_integral_v && !std::is_floating_point_v && !Detail::IsCharType::Value) struct FormatterType { - static inline void Format(const T t, FormatterExecutor& executor) { Detail::FMTBufferWriteManip(executor.BufferOut).WriteIntegerFormatData(t, executor.Data); } + [[nodiscard]] static inline std::expected Format(const T t, FormatterExecutor& executor) + { return Detail::FMTBufferWriteManip(executor.BufferOut).WriteIntegerFormatData(t, executor.Data); } }; template requires std::is_floating_point_v struct FormatterType { - static inline void Format(const T t, FormatterExecutor& executor) { Detail::FMTBufferWriteManip(executor.BufferOut).WriteFloatFormatData(t, executor.Data); } + [[nodiscard]] static inline std::expected Format(const T t, FormatterExecutor& executor) + { return Detail::FMTBufferWriteManip(executor.BufferOut).WriteFloatFormatData(t, executor.Data); } }; template requires Detail::IsCharType::Value struct FormatterType { - static inline void Format(const T t, FormatterExecutor& executor) { Detail::BufferOutManip(executor.BufferOut).Pushback(t); } + [[nodiscard]] static inline std::expected Format(const T t, FormatterExecutor& executor) + { return Detail::BufferOutManip(executor.BufferOut).Pushback(t); } }; //-------------------------------------------------------// @@ -145,47 +148,43 @@ namespace StreamFormat::FMT template struct FormatterType { - static void Format(const void* const t, FormatterExecutor& executor) + [[nodiscard]] static inline std::expected Format(const void* const t, FormatterExecutor& executor) { if (t == nullptr) return Detail::BufferOutManip(executor.BufferOut).FastWriteString(executor.Data.GetAsText("null", "nullptr")); - Detail::BufferWriteManip(executor.BufferOut).FastWriteInteger(std::size_t(t)); + return Detail::BufferWriteManip(executor.BufferOut).FastWriteInteger(std::size_t(t)); } }; template struct FormatterType { - static void Format(const T* const t, FormatterExecutor& executor) + [[nodiscard]] static inline std::expected Format(const T* const t, FormatterExecutor& executor) { if (t == nullptr) - return Detail::BufferWriteManip(executor.BufferOut).FastWriteString(executor.Data.Specifiers.GetAsText("null", "nullptr")); + { return Detail::BufferWriteManip(executor.BufferOut).FastWriteString(executor.Data.Specifiers.GetAsText("null", "nullptr")); } if constexpr (Detail::IsCharType::Value) - { - Detail::Forwarders::FormatString(t, std::numeric_limits::max(), executor); - } + { return Detail::Forwarders::FormatString(t, std::numeric_limits::max(), executor); } else - { - Detail::Forwarders::FormatObjectArray(t, std::numeric_limits::max(), executor); - } + { Detail::Forwarders::FormatObjectArray(t, std::numeric_limits::max(), executor); } } }; template struct FormatterType { - static void Format(T const (&t)[SIZE], FormatterExecutor& executor) + [[nodiscard]] static inline std::expected Format(T const (&t)[SIZE], FormatterExecutor& executor) { if constexpr (Detail::IsCharType::Value) { std::size_t size = SIZE; while (t[size - 1] == '\0') --size; - Detail::Forwarders::FormatString(t, size, executor); + return Detail::Forwarders::FormatString(t, size, executor); } else { - Detail::Forwarders::FormatObjectArray(t, SIZE, executor); + return Detail::Forwarders::FormatObjectArray(t, SIZE, executor); } } }; diff --git a/src/StreamFormat/FMT/Context/FormatterExecutor/FormatTextProperties-impl.h b/src/StreamFormat/FMT/Context/FormatterExecutor/FormatTextProperties-impl.h index ed2ca4f0..9b2e8b75 100644 --- a/src/StreamFormat/FMT/Context/FormatterExecutor/FormatTextProperties-impl.h +++ b/src/StreamFormat/FMT/Context/FormatterExecutor/FormatTextProperties-impl.h @@ -11,36 +11,36 @@ namespace StreamFormat::FMT template struct FormatterType { - static void Format(const Detail::TextProperties::ResetProperties, FormatterExecutor& executor) + [[nodiscard]] static std::expected Format(const Detail::TextProperties::ResetProperties, FormatterExecutor& executor) { - executor.TextManager.AllPropertiesReset(); + return executor.TextManager.AllPropertiesReset(); } }; template struct FormatterType { - static void Format(const Detail::TextProperties::TextColor::ResetColor, FormatterExecutor& executor) + [[nodiscard]] static std::expected Format(const Detail::TextProperties::TextColor::ResetColor, FormatterExecutor& executor) { - executor.TextManager.ApplyColorReset(); + return executor.TextManager.ApplyColorReset(); } }; template struct FormatterType { - static void Format(const Detail::TextProperties::TextStyle::ResetStyle, FormatterExecutor& executor) + [[nodiscard]] static std::expected Format(const Detail::TextProperties::TextStyle::ResetStyle, FormatterExecutor& executor) { - executor.TextManager.ApplyStyleReset(); + return executor.TextManager.ApplyStyleReset(); } }; template struct FormatterType { - static void Format(const Detail::TextProperties::TextFront::ResetFront, FormatterExecutor& executor) + [[nodiscard]] static std::expected Format(const Detail::TextProperties::TextFront::ResetFront, FormatterExecutor& executor) { - executor.TextManager.ApplyFrontReset(); + return executor.TextManager.ApplyFrontReset(); } }; @@ -52,9 +52,9 @@ namespace StreamFormat::FMT requires Detail::TextPropertiesColorIsApply struct FormatterType { - static void Format(const T& t, FormatterExecutor& executor) + [[nodiscard]] static std::expected Format(const T& t, FormatterExecutor& executor) { - executor.TextManager.AskApplyColor(t); + return executor.TextManager.AskApplyColor(t); } }; @@ -62,9 +62,9 @@ namespace StreamFormat::FMT requires Detail::TextPropertiesStyleIsApply struct FormatterType { - static void Format(const T& t, FormatterExecutor& executor) + [[nodiscard]] static std::expected Format(const T& t, FormatterExecutor& executor) { - executor.TextManager.AskApplyStyle(t); + return executor.TextManager.AskApplyStyle(t); } }; @@ -72,9 +72,9 @@ namespace StreamFormat::FMT requires Detail::TextPropertiesFrontIsApply struct FormatterType { - static void Format(const T& t, FormatterExecutor& executor) + [[nodiscard]] static std::expected Format(const T& t, FormatterExecutor& executor) { - executor.TextManager.AskApplyFront(t); + return executor.TextManager.AskApplyFront(t); } }; } diff --git a/src/StreamFormat/FMT/Context/FormatterExecutor/FormatterArgs.h b/src/StreamFormat/FMT/Context/FormatterExecutor/FormatterArgs.h index 5cd456b7..eff94688 100644 --- a/src/StreamFormat/FMT/Context/FormatterExecutor/FormatterArgs.h +++ b/src/StreamFormat/FMT/Context/FormatterExecutor/FormatterArgs.h @@ -2,42 +2,44 @@ #pragma once #include "StreamFormat/FMT/Context/BasicContext/BasicArgsInterface.h" -#include "StreamFormat/FMT/Detail/Detail.h" +#include "StreamFormat/FMT/Detail/Prelude.h" #include "FormatterType.h" namespace StreamFormat::FMT::Detail { + /****************************/ + /******** Args tuple ********/ + /****************************/ template struct FormatterArgs; template <> struct FormatterArgs<> { - public: - FormatterArgs() = default; - public: static inline constexpr std::size_t Size() { return 0; } public: template - inline void RunTypeAtIndex(FormatterExecutor&, std::int32_t) + [[nodiscard]] inline std::expected RunTypeAtIndex(FormatterExecutor&, std::int32_t) { - throw Detail::FMTGivenIndexError(); + return std::unexpected(FMTResult::ArgsInterface_Unavaible); } - template - inline std::int32_t GetIndexOfCurrentNamedArg(FormatterExecutor&, std::int32_t) + [[nodiscard]] inline std::expected GetIndexOfCurrentNamedArg(FormatterExecutor&, std::int32_t) { - return std::int32_t{-1}; + return std::unexpected(FMTResult::ArgsInterface_Unavaible); + } + [[nodiscard]] inline std::expected GetPointerIDAt(std::int32_t) + { + return std::unexpected(FMTResult::ArgsInterface_Unavaible); } - - inline PointerID GetTypeAtIndex(std::int32_t) { return PointerID{.TypeInfo = typeid(void), .Ptr = nullptr}; } - template - inline void GetTypeAtIndexConvert(T*, std::int32_t) - {} + [[nodiscard]] inline std::expected GetConvertedTypeAt(T*, std::int32_t) + { + return std::unexpected(FMTResult::ArgsInterface_Unavaible); + } }; template @@ -60,52 +62,56 @@ namespace StreamFormat::FMT::Detail public: template - inline void RunTypeAtIndex(Executor& executor, std::int32_t idx) + [[nodiscard]] inline std::expected RunTypeAtIndex(Executor& executor, std::int32_t idx) { - if (idx == 0) return executor.WriteType(m_Value); + if (idx == 0) + { + return executor.WriteType(m_Value); + } return FormatterArgs::RunTypeAtIndex(executor, idx - 1); } public: template - inline std::int32_t GetIndexOfCurrentNamedArg(BufferInfoView& format, std::int32_t beginSearchIndex) + [[nodiscard]] inline std::expected GetIndexOfCurrentNamedArg(BufferInfoView& format, std::int32_t beginSearchIndex) { if constexpr (Detail::IsANamedArgs>::value) { - if (Detail::FMTBufferParamsManip(format).NextIsNamedArgs(m_Value.GetName())) - return beginSearchIndex; + std::expected currentNamedArg = Detail::FMTBufferParamsManip(format).NextIsNamedArgs(m_Value.GetName()); + if (not currentNamedArg) + { return std::unexpected(FMTResult::BufferManipError); } + return beginSearchIndex; } return FormatterArgs::GetIndexOfCurrentNamedArg(format, beginSearchIndex + 1); } public: - inline PointerID GetTypeAtIndex(std::int32_t idx) + inline PointerID GetPointerIDAt(std::int32_t idx) { - if (idx == 0) return PointerID{.TypeInfo = typeid(const TypeWithoutRef), .Ptr = const_cast(static_cast(&m_Value))}; - return FormatterArgs::GetTypeAtIndex(idx - 1); + if (idx == 0) + return PointerID{.TypeInfo = typeid(const TypeWithoutRef), .Ptr = const_cast(static_cast(&m_Value))}; + return FormatterArgs::GetPointerIDAt(idx - 1); } public: template - inline void GetTypeAtIndexConvert(T* value, std::int32_t idx) + [[nodiscard]] inline std::expected GetConvertedTypeAt(std::int32_t idx) { if (idx == 0) { if constexpr (FMTCanContextConvert) - { - *value = FMTContextConvert::Convert(m_Value); - return; - } + { return FMTContextConvert::Convert(m_Value); } else - { - // Warrning : Need to transmit : 'Could not convert' - return; - } + { return std::unexpected(FMTResult::ArgsInterface_InvalidConversion); } } - return FormatterArgs::template GetTypeAtIndexConvert(value, idx - 1); + return FormatterArgs::template GetConvertedTypeAt(value, idx - 1); } }; + + /********************************/ + /******** Args interface ********/ + /********************************/ template class FormatterArgsInterface : public BasicArgsInterface { @@ -123,37 +129,29 @@ namespace StreamFormat::FMT::Detail public: size_t Size() override { return ArgsInterface.Size(); } - void RunTypeAtIndex(std::int32_t idx) override + [[nodiscard]] std::expected RunTypeAtIndex(std::int32_t idx) override { return ArgsInterface.RunTypeAtIndex(Executor, idx); } - std::int32_t GetIndexOfCurrentNamedArg(BufferInfoView& format) override + [[nodiscard]] std::expected GetIndexOfCurrentNamedArg(BufferInfoView& format) override { return ArgsInterface.GetIndexOfCurrentNamedArg(format, std::int32_t{0}); } - PointerID GetTypeAt(std::int32_t idx) override + PointerID GetPointerIDAt(std::int32_t idx) override { - return ArgsInterface.GetTypeAtIndex(idx); + return ArgsInterface.GetPointerIDAt(idx); } public: - template - T GetTAtConvert(std::int32_t idx) + [[nodiscard]] std::expected, FMTResult> GetStringAt(std::int32_t idx) override { - T res; - ArgsInterface.template GetTypeAtIndexConvert(&res, idx); - return res; + return ArgsInterface.template GetConvertedTypeAt>(idx); } - - std::int32_t GetFormatIndexAt(std::int32_t idx) override { return GetTAtConvert(idx); } - - std::basic_string_view GetStringAt(std::int32_t idx) override + [[nodiscard]] std::expected GetIntAt(std::int32_t idx) override { - return GetTAtConvert>(idx); + return ArgsInterface.template GetConvertedTypeAt(idx); } - std::int64_t GetIntAt(std::int32_t idx) override { return GetTAtConvert(idx); } - protected: FormatterExecutor& Executor; ContextArgsType ArgsInterface; diff --git a/src/StreamFormat/FMT/Context/FormatterExecutor/FormatterTextPropertiesExecutor/FormatterANSITextPropertiesExecutor.h b/src/StreamFormat/FMT/Context/FormatterExecutor/FormatterTextPropertiesExecutor/FormatterANSITextPropertiesExecutor.h index 94f877ce..283ceec4 100644 --- a/src/StreamFormat/FMT/Context/FormatterExecutor/FormatterTextPropertiesExecutor/FormatterANSITextPropertiesExecutor.h +++ b/src/StreamFormat/FMT/Context/FormatterExecutor/FormatterTextPropertiesExecutor/FormatterANSITextPropertiesExecutor.h @@ -14,131 +14,131 @@ namespace StreamFormat::FMT::Detail using IFormatterTextPropertiesExecutor::Buffer; public: - void AllPropertiesReset() override + [[nodiscard]] std::expected AllPropertiesReset() override { NoStrideFunction noStride(*Buffer); - BufferWriteManip(*Buffer).FastWriteStringLitteral("\033[0m"); + return BufferWriteManip(*Buffer).FastWriteStringLitteral("\033[0m"); } public: - void ResetColor() override + [[nodiscard]] std::expected ResetColor() override { NoStrideFunction noStride(*Buffer); - BufferWriteManip(*Buffer).FastWriteStringLitteral("\033[39;49m"); + return BufferWriteManip(*Buffer).FastWriteStringLitteral("\033[39;49m"); } - void ExecuteColor(const TextProperties::TextColor::BasicColorFG& t) + [[nodiscard]] std::expected ExecuteColor(const TextProperties::TextColor::BasicColorFG& t) { NoStrideFunction noStride(*Buffer); - BufferWriteManip(*Buffer).BasicWriteType("\033[", static_cast(t), "m"); + return BufferWriteManip(*Buffer).BasicWriteType("\033[", static_cast(t), "m"); } - void ExecuteColor(const TextProperties::TextColor::BasicColorBG& t) + [[nodiscard]] std::expected ExecuteColor(const TextProperties::TextColor::BasicColorBG& t) { NoStrideFunction noStride(*Buffer); - BufferWriteManip(*Buffer).BasicWriteType("\033[", static_cast(t), "m"); + return BufferWriteManip(*Buffer).BasicWriteType("\033[", static_cast(t), "m"); } - void ExecuteColor(const Detail::TextProperties::TextColor::BasicColor& t) override + [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::BasicColor& t) override { NoStrideFunction noStride(*Buffer); - BufferWriteManip(*Buffer).BasicWriteType("\033[", static_cast(t.Fg), ";", static_cast(t.Bg), "m"); + return BufferWriteManip(*Buffer).BasicWriteType("\033[", static_cast(t.Fg), ";", static_cast(t.Bg), "m"); } - void ExecuteColor(const Detail::TextProperties::TextColor::Color24bFG& t) override + [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::Color24bFG& t) override { NoStrideFunction noStride(*Buffer); - BufferWriteManip(*Buffer).BasicWriteType("\033[38;2;", t.R, ";", t.G, ";", t.B, "m"); + return BufferWriteManip(*Buffer).BasicWriteType("\033[38;2;", t.R, ";", t.G, ";", t.B, "m"); } - void ExecuteColor(const Detail::TextProperties::TextColor::Color24bBG& t) override + [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::Color24bBG& t) override { NoStrideFunction noStride(*Buffer); - BufferWriteManip(*Buffer).BasicWriteType("\033[48;2;", t.R, ";", t.G, ";", t.B, "m"); + return BufferWriteManip(*Buffer).BasicWriteType("\033[48;2;", t.R, ";", t.G, ";", t.B, "m"); } - void ExecuteColor(const Detail::TextProperties::TextColor::Color24b& t) override + [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::Color24b& t) override { NoStrideFunction noStride(*Buffer); - BufferWriteManip(*Buffer).BasicWriteType("\033[38;2;", t.Fg.R, ";", t.Fg.G, ";", t.Fg.B, "; 48; 2;", t.Bg.R, ";", t.Bg.G, ";", t.Bg.B, "m"); + return BufferWriteManip(*Buffer).BasicWriteType("\033[38;2;", t.Fg.R, ";", t.Fg.G, ";", t.Fg.B, "; 48; 2;", t.Bg.R, ";", t.Bg.G, ";", t.Bg.B, "m"); } - void ExecuteColor(const Detail::TextProperties::TextColor::ColorCubeFG& t) override + [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::ColorCubeFG& t) override { NoStrideFunction noStride(*Buffer); - BufferWriteManip(*Buffer).BasicWriteType("\033[38;5;", t.GetColorRef(), "m"); + return BufferWriteManip(*Buffer).BasicWriteType("\033[38;5;", t.GetColorRef(), "m"); } - void ExecuteColor(const Detail::TextProperties::TextColor::ColorCubeBG& t) override + [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::ColorCubeBG& t) override { NoStrideFunction noStride(*Buffer); - BufferWriteManip(*Buffer).BasicWriteType("\033[48;5;", t.GetColorRef(), "m"); + return BufferWriteManip(*Buffer).BasicWriteType("\033[48;5;", t.GetColorRef(), "m"); } - void ExecuteColor(const Detail::TextProperties::TextColor::ColorCube& t) override + [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::ColorCube& t) override { NoStrideFunction noStride(*Buffer); - BufferWriteManip(*Buffer).BasicWriteType("\033[48;5;", t.Fg.GetColorRef(), ";48;5;", t.Bg.GetColorRef(), "m"); + return BufferWriteManip(*Buffer).BasicWriteType("\033[48;5;", t.Fg.GetColorRef(), ";48;5;", t.Bg.GetColorRef(), "m"); } public: - void ResetFront() override + [[nodiscard]] std::expected ResetFront() override { NoStrideFunction noStride(*Buffer); - BufferWriteManip(*Buffer).BasicWriteType("\033[", Detail::TextProperties::TextFront::FrontID::DefaultFrontID, "m"); + return BufferWriteManip(*Buffer).BasicWriteType("\033[", Detail::TextProperties::TextFront::FrontID::DefaultFrontID, "m"); } - void ExecuteFront(const Detail::TextProperties::TextFront::FrontID& t) override + [[nodiscard]] std::expected ExecuteFront(const Detail::TextProperties::TextFront::FrontID& t) override { NoStrideFunction noStride(*Buffer); - BufferWriteManip(*Buffer).BasicWriteType("\033[", t.ID, "m"); + return BufferWriteManip(*Buffer).BasicWriteType("\033[", t.ID, "m"); } public: - void ResetStyle() override + [[nodiscard]] std::expected ResetStyle() override { // TODO NoStrideFunction noStride(*Buffer); - BufferWriteManip(*Buffer).FastWriteStringLitteral("\033[0m"); + return BufferWriteManip(*Buffer).FastWriteStringLitteral("\033[0m"); } - void ExecuteStyle(const Detail::TextProperties::TextStyle::Intensity& t) override + [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Intensity& t) override { NoStrideFunction noStride(*Buffer); - BufferWriteManip(*Buffer).BasicWriteType("\033[", static_cast(t), "m"); + return BufferWriteManip(*Buffer).BasicWriteType("\033[", static_cast(t), "m"); } - void ExecuteStyle(const Detail::TextProperties::TextStyle::Italic& t) override + [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Italic& t) override { NoStrideFunction noStride(*Buffer); - BufferWriteManip(*Buffer).BasicWriteType("\033[", static_cast(t), "m"); + return BufferWriteManip(*Buffer).BasicWriteType("\033[", static_cast(t), "m"); } - void ExecuteStyle(const Detail::TextProperties::TextStyle::Underline& t) override + [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Underline& t) override { NoStrideFunction noStride(*Buffer); - BufferWriteManip(*Buffer).BasicWriteType("\033[", static_cast(t), "m"); + return BufferWriteManip(*Buffer).BasicWriteType("\033[", static_cast(t), "m"); } - void ExecuteStyle(const Detail::TextProperties::TextStyle::UnderlineColor::Color&) override + [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::UnderlineColor::Color&) override { NoStrideFunction noStride(*Buffer); - BufferWriteManip(*Buffer).BasicWriteType("\033[59m"); + return BufferWriteManip(*Buffer).BasicWriteType("\033[59m"); } - void ExecuteStyle(const Detail::TextProperties::TextStyle::UnderlineColor::ColorCube& t) override + [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::UnderlineColor::ColorCube& t) override { NoStrideFunction noStride(*Buffer); - BufferWriteManip(*Buffer).BasicWriteType("\033[58;5;", t.GetColorRef(), "m"); + return BufferWriteManip(*Buffer).BasicWriteType("\033[58;5;", t.GetColorRef(), "m"); } - void ExecuteStyle(const Detail::TextProperties::TextStyle::UnderlineColor::Color24b& t) override + [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::UnderlineColor::Color24b& t) override { NoStrideFunction noStride(*Buffer); - BufferWriteManip(*Buffer).BasicWriteType("\033[58;2;", t.R, ";", t.G, ";", t.B, "m"); + return BufferWriteManip(*Buffer).BasicWriteType("\033[58;2;", t.R, ";", t.G, ";", t.B, "m"); } - void ExecuteStyle(const Detail::TextProperties::TextStyle::Blink& t) override + [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Blink& t) override { NoStrideFunction noStride(*Buffer); - BufferWriteManip(*Buffer).BasicWriteType("\033[", static_cast(t), "m"); + return BufferWriteManip(*Buffer).BasicWriteType("\033[", static_cast(t), "m"); } - void ExecuteStyle(const Detail::TextProperties::TextStyle::Inverted& t) override + [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Inverted& t) override { NoStrideFunction noStride(*Buffer); - BufferWriteManip(*Buffer).BasicWriteType("\033[", static_cast(t), "m"); + return BufferWriteManip(*Buffer).BasicWriteType("\033[", static_cast(t), "m"); } - void ExecuteStyle(const Detail::TextProperties::TextStyle::Ideogram& t) override + [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Ideogram& t) override { NoStrideFunction noStride(*Buffer); - BufferWriteManip(*Buffer).BasicWriteType("\033[", static_cast(t), "m"); + return BufferWriteManip(*Buffer).BasicWriteType("\033[", static_cast(t), "m"); } - void ExecuteStyle(const Detail::TextProperties::TextStyle::Script& t) override + [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Script& t) override { NoStrideFunction noStride(*Buffer); - BufferWriteManip(*Buffer).BasicWriteType("\033[", static_cast(t), "m"); + return BufferWriteManip(*Buffer).BasicWriteType("\033[", static_cast(t), "m"); } }; } diff --git a/src/StreamFormat/FMT/Context/FormatterExecutor/FormatterTextPropertiesExecutor/FormatterTextPropertiesExecutor.h b/src/StreamFormat/FMT/Context/FormatterExecutor/FormatterTextPropertiesExecutor/FormatterTextPropertiesExecutor.h index 0418ca90..0a8b6fb3 100644 --- a/src/StreamFormat/FMT/Context/FormatterExecutor/FormatterTextPropertiesExecutor/FormatterTextPropertiesExecutor.h +++ b/src/StreamFormat/FMT/Context/FormatterExecutor/FormatterTextPropertiesExecutor/FormatterTextPropertiesExecutor.h @@ -32,35 +32,35 @@ namespace StreamFormat::FMT::Detail ~FormatterNOTextPropertiesExecutor() override = default; public: - void AllPropertiesReset() override {} + [[nodiscard]] std::expected AllPropertiesReset() override {} public: - void ResetColor() override {} - void ExecuteColor(const Detail::TextProperties::TextColor::BasicColorFG&) override {} - void ExecuteColor(const Detail::TextProperties::TextColor::BasicColorBG&) override {} - void ExecuteColor(const Detail::TextProperties::TextColor::BasicColor&) override {} - void ExecuteColor(const Detail::TextProperties::TextColor::Color24bFG&) override {} - void ExecuteColor(const Detail::TextProperties::TextColor::Color24bBG&) override {} - void ExecuteColor(const Detail::TextProperties::TextColor::Color24b&) override {} - void ExecuteColor(const Detail::TextProperties::TextColor::ColorCubeFG&) override {} - void ExecuteColor(const Detail::TextProperties::TextColor::ColorCubeBG&) override {} - void ExecuteColor(const Detail::TextProperties::TextColor::ColorCube&) override {} + [[nodiscard]] std::expected ResetColor() override {} + [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::BasicColorFG&) override {} + [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::BasicColorBG&) override {} + [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::BasicColor&) override {} + [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::Color24bFG&) override {} + [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::Color24bBG&) override {} + [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::Color24b&) override {} + [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::ColorCubeFG&) override {} + [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::ColorCubeBG&) override {} + [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::ColorCube&) override {} public: - void ResetFront() override {} - void ExecuteFront(const Detail::TextProperties::TextFront::FrontID&) override {} + [[nodiscard]] std::expected ResetFront() override {} + [[nodiscard]] std::expected ExecuteFront(const Detail::TextProperties::TextFront::FrontID&) override {} public: - void ResetStyle() override {} - void ExecuteStyle(const Detail::TextProperties::TextStyle::Intensity&) override {} - void ExecuteStyle(const Detail::TextProperties::TextStyle::Italic&) override {} - void ExecuteStyle(const Detail::TextProperties::TextStyle::Underline&) override {} - void ExecuteStyle(const Detail::TextProperties::TextStyle::UnderlineColor::Color&) override {} - void ExecuteStyle(const Detail::TextProperties::TextStyle::UnderlineColor::ColorCube&) override {} - void ExecuteStyle(const Detail::TextProperties::TextStyle::UnderlineColor::Color24b&) override {} - void ExecuteStyle(const Detail::TextProperties::TextStyle::Blink&) override {} - void ExecuteStyle(const Detail::TextProperties::TextStyle::Inverted&) override {} - void ExecuteStyle(const Detail::TextProperties::TextStyle::Ideogram&) override {} - void ExecuteStyle(const Detail::TextProperties::TextStyle::Script&) override {} + [[nodiscard]] std::expected ResetStyle() override {} + [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Intensity&) override {} + [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Italic&) override {} + [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Underline&) override {} + [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::UnderlineColor::Color&) override {} + [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::UnderlineColor::ColorCube&) override {} + [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::UnderlineColor::Color24b&) override {} + [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Blink&) override {} + [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Inverted&) override {} + [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Ideogram&) override {} + [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Script&) override {} }; } diff --git a/src/StreamFormat/FMT/Context/FormatterExecutor/FormatterType.h b/src/StreamFormat/FMT/Context/FormatterExecutor/FormatterType.h index eec96c42..fb5af4ac 100644 --- a/src/StreamFormat/FMT/Context/FormatterExecutor/FormatterType.h +++ b/src/StreamFormat/FMT/Context/FormatterExecutor/FormatterType.h @@ -1,23 +1,25 @@ #pragma once -#include "StreamFormat/FMT/Detail/Detail.h" +#include "StreamFormat/FMT/Detail/Prelude.h" #define STREAMFORMAT_FORMATTER_DECLARED namespace StreamFormat::FMT { + enum class FMTResult + { + BufferManip, + }; + template struct FormatterType { - static inline void Format(const T&, FormatterExecutor& executor) + [[nodiscard]] static std::expected Format(const T&, FormatterExecutor& executor) { #ifdef UNKOWN_TYPE_MESSAGE executor.Run("({C:red}FMT unknow type: {})", typeid(T).name()); #endif -#ifdef UNKOWN_TYPE_THROW - throw Detail::FMTShouldNotEndHere{}; -#endif #ifdef UNKOWN_TYPE_FAIL - throw Detail::FMTShouldNotEndHere{}; + static_assert(false); #endif #ifdef UNKOWN_TYPE_DEBUG STREAMFORMAT_DEBUGBREAK(); @@ -26,16 +28,16 @@ namespace StreamFormat::FMT }; } -#define STREAMFORMAT_AUTO_FORMATTER(Type, fmt, ...) \ - template \ - struct StreamFormat::FMT::FormatterType \ - { \ - static void Format(const Type& value, FormatterExecutor& executor) { executor.Run(fmt, __VA_ARGS__); } \ +#define STREAMFORMAT_AUTO_FORMATTER(Type, fmt, ...) \ + template \ + struct StreamFormat::FMT::FormatterType \ + { \ + [[nodiscard]] static std::expected Format(const Type& value, FormatterExecutor& executor) { executor.Run(fmt, __VA_ARGS__); } \ }; -#define STREAMFORMAT_AUTO_FORMATTER_T(Type, fmt, ...) \ - template \ - struct StreamFormat::FMT::FormatterType \ - { \ - static void Format(const Type&, FormatterExecutor& executor) { executor.Run(fmt, __VA_ARGS__); } \ +#define STREAMFORMAT_AUTO_FORMATTER_T(Type, fmt, ...) \ + template \ + struct StreamFormat::FMT::FormatterType \ + { \ + [[nodiscard]] static std::expected Format(const Type&, FormatterExecutor& executor) { executor.Run(fmt, __VA_ARGS__); } \ }; diff --git a/src/StreamFormat/FMT/Context/FormatterExecutor/IndexArgs.h b/src/StreamFormat/FMT/Context/FormatterExecutor/IndexArgs.h index 9235b4e9..9420aefb 100644 --- a/src/StreamFormat/FMT/Context/FormatterExecutor/IndexArgs.h +++ b/src/StreamFormat/FMT/Context/FormatterExecutor/IndexArgs.h @@ -28,9 +28,9 @@ namespace StreamFormat::FMT struct FormatterType, FormatterExecutor> { template - static inline void Format(const FCIndexArgs& t, FormatterExecutor& executor) + [[nodiscard]] static inline std::expected Format(const FCIndexArgs& t, FormatterExecutor& executor) { - executor.WriteType(t.GetValue()); + return executor.WriteType(t.GetValue()); } }; } diff --git a/src/StreamFormat/FMT/Context/FormatterExecutor/NamedArgs.h b/src/StreamFormat/FMT/Context/FormatterExecutor/NamedArgs.h index 9b475886..9355bc10 100644 --- a/src/StreamFormat/FMT/Context/FormatterExecutor/NamedArgs.h +++ b/src/StreamFormat/FMT/Context/FormatterExecutor/NamedArgs.h @@ -33,7 +33,10 @@ namespace StreamFormat::FMT template struct FormatterType, FormatterExecutor> { - static inline void Format(const StringViewNamedArgs& t, FormatterExecutor& executor) { executor.WriteType(t.GetValue()); } + [[nodiscard]] static inline std::expected Format(const StringViewNamedArgs& t, FormatterExecutor& executor) + { + return executor.WriteType(t.GetValue()); + } }; /////---------- stringNamedArgs Allocate memory (Only if necessary) ----------///// @@ -64,7 +67,10 @@ namespace StreamFormat::FMT template struct FormatterType, FormatterExecutor> { - static inline void Format(const StringNamedArgs& t, FormatterExecutor& executor) { executor.WriteType(t.GetValue()); } + [[nodiscard]] static inline std::expected Format(const StringNamedArgs& t, FormatterExecutor& executor) + { + return executor.WriteType(t.GetValue()); + } }; namespace Detail diff --git a/src/StreamFormat/FMT/Context/FormatterExecutor/STDEnumerable.h b/src/StreamFormat/FMT/Context/FormatterExecutor/STDEnumerable.h index 7538c5b5..490dc135 100644 --- a/src/StreamFormat/FMT/Context/FormatterExecutor/STDEnumerable.h +++ b/src/StreamFormat/FMT/Context/FormatterExecutor/STDEnumerable.h @@ -2,7 +2,7 @@ #include "FormatterType.h" #include "StreamFormat/FMT/Context/Utils/ContextFunctions.h" -#include "StreamFormat/FMT/Detail/Detail.h" +#include "StreamFormat/FMT/Detail/Prelude.h" #include #include @@ -88,7 +88,7 @@ namespace StreamFormat::FMT template struct FormatterType, FormatterExecutor> { - static void Format(const T& container, FormatterExecutor& executor) + [[nodiscard]] static inline std::expected Format(const T& container, FormatterExecutor& executor) { STDEnumerable enumerable(container, executor.Data.GetAsText("join", STDEnumerableUtility::DefaultJoin), executor.Data.GetAsText("begin", STDEnumerableUtility::DefaultBegin), @@ -96,7 +96,7 @@ namespace StreamFormat::FMT executor.Data.GetAsNumber("begin", 0), executor.Data.GetAsNumber("size", -1)); - executor.WriteType(enumerable); + return executor.WriteType(enumerable); } }; diff --git a/src/StreamFormat/FMT/Context/FormatterExecutor/UtilityFunctions.h b/src/StreamFormat/FMT/Context/FormatterExecutor/UtilityFunctions.h index d467e28a..23c675b1 100644 --- a/src/StreamFormat/FMT/Context/FormatterExecutor/UtilityFunctions.h +++ b/src/StreamFormat/FMT/Context/FormatterExecutor/UtilityFunctions.h @@ -17,7 +17,7 @@ namespace StreamFormat::FMT { template requires(IsCharType::Value) - void FormatInManager( + std::expected FormatInManager( Detail::BasicBufferOutManager& bufferOutManager, bool newline, BufferInfoView format, @@ -36,7 +36,7 @@ namespace StreamFormat::FMT template requires(IsCharType::Value) - void FormatInManager(Detail::BasicBufferOutManager& bufferOutManager, bool newline, T&& t) + std::expected FormatInManager(Detail::BasicBufferOutManager& bufferOutManager, bool newline, T&& t) { using TCharResolved = std::remove_const_t; @@ -51,7 +51,7 @@ namespace StreamFormat::FMT template requires(Detail::IsCharType::Value && Detail::ConvertibleToBufferInfoView) - void FormatInChar(TChar (&buffer)[BUFFER_SIZE], Format&& formatInput, Args&&... args) + std::expected FormatInChar(TChar (&buffer)[BUFFER_SIZE], Format&& formatInput, Args&&... args) { Detail::GivenBufferOutManager bufferOutManager(buffer); Detail::FormatInManager(bufferOutManager, false, Detail::BufferInfoView{formatInput}, std::forward(args)...); @@ -59,7 +59,7 @@ namespace StreamFormat::FMT template requires(Detail::IsCharType::Value && Detail::ConvertibleToBufferInfoView) - void FormatInChar(TChar* const buffer, const std::size_t bufferSize, Format&& formatInput, Args&&... args) + std::expected FormatInChar(TChar* const buffer, const std::size_t bufferSize, Format&& formatInput, Args&&... args) { Detail::GivenBufferOutManager bufferOutManager(buffer, bufferSize); Detail::FormatInManager(bufferOutManager, false, Detail::BufferInfoView{formatInput}, std::forward(args)...); @@ -67,7 +67,7 @@ namespace StreamFormat::FMT template requires(Detail::IsCharType::Value && Detail::ConvertibleToBufferInfoView) - void CFilePrint(FILE* stream, Format&& formatInput, Args&&... args) + std::expected CFilePrint(FILE* stream, Format&& formatInput, Args&&... args) { Detail::DynamicBufferOutManager bufferOutManager(256); Detail::FormatInManager(bufferOutManager, false, Detail::BufferInfoView{formatInput}, std::forward(args)...); @@ -78,7 +78,7 @@ namespace StreamFormat::FMT template requires(Detail::IsCharType::Value && Detail::ConvertibleToBufferInfoView) - void CFilePrintLn(FILE* stream, Format&& formatInput, Args&&... args) + std::expected CFilePrintLn(FILE* stream, Format&& formatInput, Args&&... args) { Detail::DynamicBufferOutManager bufferOutManager(256); Detail::FormatInManager(bufferOutManager, true, Detail::BufferInfoView{formatInput}, std::forward(args)...); @@ -89,7 +89,7 @@ namespace StreamFormat::FMT template requires(Detail::IsCharType::Value && Detail::ConvertibleToBufferInfoView) - void FilePrint(std::basic_ostream& stream, Format&& formatInput, Args&&... args) + std::expected FilePrint(std::basic_ostream& stream, Format&& formatInput, Args&&... args) { Detail::DynamicBufferOutManager bufferOutManager(256); Detail::FormatInManager(bufferOutManager, false, Detail::BufferInfoView{formatInput}, std::forward(args)...); @@ -100,7 +100,7 @@ namespace StreamFormat::FMT template requires(Detail::IsCharType::Value && Detail::ConvertibleToBufferInfoView) - void FilePrintLn(std::basic_ostream& stream, Format&& formatInput, Args&&... args) + std::expected FilePrintLn(std::basic_ostream& stream, Format&& formatInput, Args&&... args) { Detail::DynamicBufferOutManager bufferOutManager(256); Detail::FormatInManager(bufferOutManager, true, Detail::BufferInfoView{formatInput}, std::forward(args)...); @@ -111,7 +111,7 @@ namespace StreamFormat::FMT template requires(Detail::IsCharType::Value && Detail::ConvertibleToBufferInfoView) - void FormatInString(std::basic_string& str, Format&& formatInput, Args&&... args) + std::expected FormatInString(std::basic_string& str, Format&& formatInput, Args&&... args) { Detail::DynamicBufferOutManager bufferOutManager(256); Detail::FormatInManager(bufferOutManager, false, Detail::BufferInfoView{formatInput}, std::forward(args)...); @@ -120,7 +120,7 @@ namespace StreamFormat::FMT template requires(Detail::IsCharType::Value && Detail::ConvertibleToBufferInfoView) - inline std::basic_string FormatString(Format&& formatInput, Args&&... args) + inline std::expected, FMTResult> FormatString(Format&& formatInput, Args&&... args) { Detail::DynamicBufferOutManager bufferOutManager(256); Detail::FormatInManager(bufferOutManager, false, Detail::BufferInfoView{formatInput}, std::forward(args)...); @@ -131,7 +131,7 @@ namespace StreamFormat::FMT template requires(Detail::IsCharType::Value) - void FormatInChar(TChar (&buffer)[BUFFER_SIZE], T&& t) + std::expected FormatInChar(TChar (&buffer)[BUFFER_SIZE], T&& t) { Detail::GivenBufferOutManager bufferOutManager(buffer, BUFFER_SIZE); Detail::FormatInManager(bufferOutManager, false, std::forward(t)); @@ -139,7 +139,7 @@ namespace StreamFormat::FMT template requires(Detail::IsCharType::Value) - void FormatInChar(TChar* const buffer, const std::size_t bufferSize, T&& t) + std::expected FormatInChar(TChar* const buffer, const std::size_t bufferSize, T&& t) { Detail::GivenBufferOutManager bufferOutManager(buffer, bufferSize); Detail::FormatInManager(bufferOutManager, false, std::forward(t)); @@ -147,7 +147,7 @@ namespace StreamFormat::FMT template requires(Detail::IsCharType::Value) - void CFilePrint(FILE* stream, T&& t) + std::expected CFilePrint(FILE* stream, T&& t) { Detail::DynamicBufferOutManager bufferOutManager(32); Detail::FormatInManager(bufferOutManager, false, std::forward(t)); @@ -158,7 +158,7 @@ namespace StreamFormat::FMT template requires(Detail::IsCharType::Value) - void CFilePrintLn(FILE* stream, T&& t) + std::expected CFilePrintLn(FILE* stream, T&& t) { Detail::DynamicBufferOutManager bufferOutManager(32); Detail::FormatInManager(bufferOutManager, true, std::forward(t)); @@ -169,7 +169,7 @@ namespace StreamFormat::FMT template requires(Detail::IsCharType::Value) - void FilePrint(std::basic_ostream& stream, T&& t) + std::expected FilePrint(std::basic_ostream& stream, T&& t) { Detail::DynamicBufferOutManager bufferOutManager(32); Detail::FormatInManager(bufferOutManager, false, std::forward(t)); @@ -180,7 +180,7 @@ namespace StreamFormat::FMT template requires(Detail::IsCharType::Value) - void FilePrintLn(std::basic_ostream& stream, T&& t) + std::expected FilePrintLn(std::basic_ostream& stream, T&& t) { Detail::DynamicBufferOutManager bufferOutManager(32); Detail::FormatInManager(bufferOutManager, true, std::forward(t)); @@ -191,7 +191,7 @@ namespace StreamFormat::FMT template requires(Detail::IsCharType::Value) - void FormatInString(std::basic_string& str, T&& t) + std::expected FormatInString(std::basic_string& str, T&& t) { Detail::DynamicBufferOutManager bufferOutManager(32); Detail::FormatInManager(bufferOutManager, false, std::forward(t)); @@ -200,7 +200,7 @@ namespace StreamFormat::FMT template requires(Detail::IsCharType::Value) - inline std::basic_string FormatString(T&& t) + inline std::expected, FMTResult> FormatString(T&& t) { Detail::DynamicBufferOutManager bufferOutManager(32); Detail::FormatInManager(bufferOutManager, false, std::forward(t)); diff --git a/src/StreamFormat/FMT/Context/ParserExecutor/BasicParserExecutor.h b/src/StreamFormat/FMT/Context/ParserExecutor/BasicParserExecutor.h index dde08703..0e3c09ba 100644 --- a/src/StreamFormat/FMT/Context/ParserExecutor/BasicParserExecutor.h +++ b/src/StreamFormat/FMT/Context/ParserExecutor/BasicParserExecutor.h @@ -26,7 +26,7 @@ namespace StreamFormat::FMT::Context BasicParserExecutor(Detail::BufferInfoView& bufferIn, Detail::ITextPropertiesExecutor& textPropertiesExecutor); ~BasicParserExecutor() override = default; - void Terminate(); + [[nodiscard]] std::expected Terminate(); public: Detail::BufferInfoView& BufferIn; @@ -35,18 +35,21 @@ namespace StreamFormat::FMT::Context using ContextExecutor::TextManager; protected: - Detail::BufferManipResult ExecRawString(std::basic_string_view sv) override { return Detail::BufferTestManip(BufferIn).IsSameForward(sv.data(), sv.size()); } - void ExecSettings() override {}; + [[nodiscard]] std::expected ExecRawString(std::basic_string_view sv) override + { + return Detail::BufferTestManip(BufferIn).IsSameForward(sv.data(), sv.size()); + } + [[nodiscard]] std::expected ExecSettings() override {}; public: template - void Run_(Detail::BufferInfoView format, Args&&... args); + [[nodiscard]] std::expected Run_(Detail::BufferInfoView format, Args&&... args); template - void Run(Format&& format, Args&&... args); + [[nodiscard]] std::expected Run(Format&& format, Args&&... args); public: template - inline void ReadType(Type& type, Rest&... rest) + [[nodiscard]] inline std::expected ReadType(Type& type, Rest&... rest) { ParserType>::Type, M_Type>::Parse(type, *this); if constexpr (sizeof...(rest) > 0) @@ -66,13 +69,13 @@ namespace StreamFormat::FMT::Context } template - void BasicParserExecutor::Terminate() + [[nodiscard]] std::expected BasicParserExecutor::Terminate() { } template template - void BasicParserExecutor::Run_(Detail::BufferInfoView format, Args&&... args) + [[nodiscard]] std::expected BasicParserExecutor::Run_(Detail::BufferInfoView format, Args&&... args) { auto argsInterface = Detail::ParserArgsInterface, Args...>(*this, std::forward(args)...); @@ -84,7 +87,7 @@ namespace StreamFormat::FMT::Context template template - void BasicParserExecutor::Run(Format&& formatInput, Args&&... args) + [[nodiscard]] std::expected BasicParserExecutor::Run(Format&& formatInput, Args&&... args) { Run_(Detail::BufferInfoView{formatInput}, std::forward(args)...); } diff --git a/src/StreamFormat/FMT/Context/ParserExecutor/ParseBasics-impl.h b/src/StreamFormat/FMT/Context/ParserExecutor/ParseBasics-impl.h index f011b315..c3116638 100644 --- a/src/StreamFormat/FMT/Context/ParserExecutor/ParseBasics-impl.h +++ b/src/StreamFormat/FMT/Context/ParserExecutor/ParseBasics-impl.h @@ -16,7 +16,7 @@ namespace StreamFormat::FMT template struct ParserType { - static void Parse(bool& t, ParserExecutor& executor) + [[nodiscard]] static std::expected Parse(bool& t, ParserExecutor& executor) { if (!executor.Data.PrefixSuffix) { @@ -38,8 +38,6 @@ namespace StreamFormat::FMT else if (Detail::BufferTestManip(executor.BufferIn).IsEqualToForward('1')) { t = false; return; } } - - throw Detail::FMTParseError(); } }; @@ -47,14 +45,16 @@ namespace StreamFormat::FMT requires (std::is_integral_v && !std::is_floating_point_v && !Detail::IsCharType::Value) struct ParserType { - static inline void Parse(T& t, ParserExecutor& executor) { Detail::FMTBufferReadManip(executor.BufferIn).ReadIntegerFormatData(t, executor.Data); } + [[nodiscard]] static inline std::expected Parse(T& t, ParserExecutor& executor) + { return Detail::FMTBufferReadManip(executor.BufferIn).ReadIntegerFormatData(t, executor.Data); } }; template requires std::is_floating_point_v struct ParserType { - static inline void Parse(T& t, ParserExecutor& executor) { Detail::FMTBufferReadManip(executor.BufferIn).ReadFloatFormatData(t, executor.Data); } + [[nodiscard]] static inline std::expected Parse(T& t, ParserExecutor& executor) + { return Detail::FMTBufferReadManip(executor.BufferIn).ReadFloatFormatData(t, executor.Data); } }; //-------------------------------------------------------// @@ -64,7 +64,7 @@ namespace StreamFormat::FMT template struct ParserType { - static inline void Parse(void*&, ParserExecutor&) + [[nodiscard]] static inline std::expected Parse(void*&, ParserExecutor&) { // FIXME // TODO @@ -74,7 +74,7 @@ namespace StreamFormat::FMT template struct ParserType { - static inline void Parse(T*&, ParserExecutor&) + [[nodiscard]] static inline std::expected Parse(T*&, ParserExecutor&) { // FIXME // TODO @@ -84,7 +84,7 @@ namespace StreamFormat::FMT template struct ParserType { - static inline void Parse(T (&)[SIZE], ParserExecutor&) + [[nodiscard]] static inline std::expected Parse(T (&)[SIZE], ParserExecutor&) { // FIXME // TODO diff --git a/src/StreamFormat/FMT/Context/ParserExecutor/ParseTextProperties-impl.h b/src/StreamFormat/FMT/Context/ParserExecutor/ParseTextProperties-impl.h index 219ce945..20f305ce 100644 --- a/src/StreamFormat/FMT/Context/ParserExecutor/ParseTextProperties-impl.h +++ b/src/StreamFormat/FMT/Context/ParserExecutor/ParseTextProperties-impl.h @@ -11,36 +11,36 @@ namespace StreamFormat::FMT template struct ParserType { - static void Parse(Detail::TextProperties::ResetProperties, ParserExecutor& executor) + [[nodiscard]] static inline std::expected Parse(Detail::TextProperties::ResetProperties, ParserExecutor& executor) { - executor.TextManager.AllPropertiesReset(); + return executor.TextManager.AllPropertiesReset(); } }; template struct ParserType { - static void Parse(Detail::TextProperties::TextColor::ResetColor, ParserExecutor& executor) + [[nodiscard]] static inline std::expected Parse(Detail::TextProperties::TextColor::ResetColor, ParserExecutor& executor) { - executor.TextManager.ApplyColorReset(); + return executor.TextManager.ApplyColorReset(); } }; template struct ParserType { - static void Parse(Detail::TextProperties::TextStyle::ResetStyle, ParserExecutor& executor) + [[nodiscard]] static inline std::expected Parse(Detail::TextProperties::TextStyle::ResetStyle, ParserExecutor& executor) { - executor.TextManager.ApplyStyleReset(); + return executor.TextManager.ApplyStyleReset(); } }; template struct ParserType { - static void Parse(Detail::TextProperties::TextFront::ResetFront, ParserExecutor& executor) + [[nodiscard]] static inline std::expected Parse(Detail::TextProperties::TextFront::ResetFront, ParserExecutor& executor) { - executor.TextManager.ApplyFrontReset(); + return executor.TextManager.ApplyFrontReset(); } }; @@ -52,9 +52,9 @@ namespace StreamFormat::FMT requires Detail::TextPropertiesColorIsApply struct ParserType { - static void Parse(T& t, ParserExecutor& executor) + [[nodiscard]] static inline std::expected Parse(T& t, ParserExecutor& executor) { - executor.TextManager.AskApplyColor(t); + return executor.TextManager.AskApplyColor(t); } }; @@ -62,9 +62,9 @@ namespace StreamFormat::FMT requires Detail::TextPropertiesStyleIsApply struct ParserType { - static void Parse(T& t, ParserExecutor& executor) + [[nodiscard]] static inline std::expected Parse(T& t, ParserExecutor& executor) { - executor.TextManager.AskApplyStyle(t); + return executor.TextManager.AskApplyStyle(t); } }; @@ -72,9 +72,9 @@ namespace StreamFormat::FMT requires Detail::TextPropertiesFrontIsApply struct ParserType { - static void Parse(T& t, ParserExecutor& executor) + [[nodiscard]] static inline std::expected Parse(T& t, ParserExecutor& executor) { - executor.TextManager.AskApplyFront(t); + return executor.TextManager.AskApplyFront(t); } }; } diff --git a/src/StreamFormat/FMT/Context/ParserExecutor/ParserArgs.h b/src/StreamFormat/FMT/Context/ParserExecutor/ParserArgs.h index a31ba017..4401357a 100644 --- a/src/StreamFormat/FMT/Context/ParserExecutor/ParserArgs.h +++ b/src/StreamFormat/FMT/Context/ParserExecutor/ParserArgs.h @@ -1,10 +1,13 @@ #pragma once #include "StreamFormat/FMT/Context/BasicContext/BasicArgsInterface.h" -#include "StreamFormat/FMT/Detail/Detail.h" +#include "StreamFormat/FMT/Detail/Prelude.h" namespace StreamFormat::FMT::Detail { + /****************************/ + /******** Args tuple ********/ + /****************************/ template struct ParserArgs; @@ -19,22 +22,24 @@ namespace StreamFormat::FMT::Detail public: template - inline void RunTypeAtIndex(FormatterExecutor&, std::int32_t) + [[nodiscard]] inline std::expected RunTypeAtIndex(FormatterExecutor&, std::int32_t) { - throw Detail::FMTGivenIndexError(); + return std::unexpected(FMTResult::ArgsInterface_Unavaible); } - template - inline std::int32_t GetIndexOfCurrentNamedArg(FormatterExecutor&, std::int32_t) + [[nodiscard]] inline std::expected GetIndexOfCurrentNamedArg(FormatterExecutor&, std::int32_t) { - return std::int32_t{-1}; + return std::unexpected(FMTResult::ArgsInterface_Unavaible); + } + [[nodiscard]] inline std::expected GetPointerIDAt(std::int32_t) + { + return std::unexpected(FMTResult::ArgsInterface_Unavaible); } - - inline PointerID GetTypeAtIndex(std::int32_t) { return {.TypeInfo = typeid(void), .Ptr = nullptr}; } - template - inline void GetTypeAtIndexConvert(T*, std::int32_t) - {} + [[nodiscard]] inline std::expected GetConvertedTypeAt(T*, std::int32_t) + { + return std::unexpected(FMTResult::ArgsInterface_Unavaible); + } }; template @@ -57,51 +62,55 @@ namespace StreamFormat::FMT::Detail public: template - inline void RunTypeAtIndex(Executor& executor, std::int32_t idx) + [[nodiscard]] inline std::expected RunTypeAtIndex(Executor& executor, std::int32_t idx) { - if (idx == 0) return executor.ReadType(m_Value); + if (idx == 0) + { + return executor.ReadType(m_Value); + } return ParserArgs::RunTypeAtIndex(executor, idx - 1); } public: template - inline std::int32_t GetIndexOfCurrentNamedArg(BufferInfoView& format, std::int32_t beginSearchIndex) + [[nodiscard]] inline std::expected GetIndexOfCurrentNamedArg(BufferInfoView& format, std::int32_t beginSearchIndex) { if constexpr (Detail::IsANamedArgs>::value) { - if (Detail::FMTBufferParamsManip(format).NextIsNamedArgs(m_Value.GetName())) return beginSearchIndex; + std::expected currentNamedArg = Detail::FMTBufferParamsManip(format).NextIsNamedArgs(m_Value.GetName()); + if (not currentNamedArg) + { return std::unexpected(FMTResult::BufferManipError); } + return beginSearchIndex; } - return ParserArgs::GetIndexOfCurrentNamedArg(format, beginSearchIndex + 1); + return FormatterArgs::GetIndexOfCurrentNamedArg(format, beginSearchIndex + 1); } public: - inline PointerID GetTypeAtIndex(std::int32_t idx) + inline PointerID GetPointerIDAt(std::int32_t idx) { if (idx == 0) return PointerID{.TypeInfo = typeid(TypeWithoutRef), .Ptr = static_cast(&m_Value)}; - return ParserArgs::GetTypeAtIndex(idx - 1); + return ParserArgs::GetPointerIDAt(idx - 1); } public: template - inline void GetTypeAtIndexConvert(T* value, std::int32_t idx) + [[nodiscard]] inline std::expected GetConvertedTypeAt(std::int32_t idx) { if (idx == 0) { if constexpr (FMTCanContextConvert) - { - *value = FMTContextConvert::Convert(m_Value); - return; - } + { return FMTContextConvert::Convert(m_Value); } else - { - // Warrning : Need to transmit : 'Could not convert' - return; - } + { return std::unexpected(FMTResult::ArgsInterface_InvalidConversion); } } - return ParserArgs::template GetTypeAtIndexConvert(value, idx - 1); + return ParserArgs::template GetConvertedTypeAt(value, idx - 1); } }; + + /********************************/ + /******** Args interface ********/ + /********************************/ template class ParserArgsInterface : public BasicArgsInterface { @@ -118,34 +127,30 @@ namespace StreamFormat::FMT::Detail public: std::size_t Size() override { return ArgsInterface.Size(); } - void RunTypeAtIndex(std::int32_t idx) override + + public: + [[nodiscard]] std::expected RunTypeAtIndex(std::int32_t idx) override { return ArgsInterface.RunTypeAtIndex(Executor, idx); } - std::int32_t GetIndexOfCurrentNamedArg(BufferInfoView& format) override + [[nodiscard]] std::expected GetIndexOfCurrentNamedArg(BufferInfoView& format) override { return ArgsInterface.GetIndexOfCurrentNamedArg(format, std::int32_t{0}); } - PointerID GetTypeAt(std::int32_t idx) override + PointerID GetPointerIDAt(std::int32_t idx) override { - return ArgsInterface.GetTypeAtIndex(idx); + return ArgsInterface.GetPointerIDAt(idx); } public: - template - T GetTAtConvert(std::int32_t idx) + [[nodiscard]] std::expected, FMTResult> GetStringAt(std::int32_t idx) override { - T res; - ArgsInterface.template GetTypeAtIndexConvert(&res, idx); - return res; + return ArgsInterface.template GetConvertedTypeAt>(idx); } - - std::int32_t GetFormatIndexAt(std::int32_t idx) override { return GetTAtConvert(idx); } - typename std::basic_string_view GetStringAt(std::int32_t idx) override + [[nodiscard]] std::expected GetIntAt(std::int32_t idx) override { - return GetTAtConvert>(idx); + return ArgsInterface.template GetConvertedTypeAt(idx); } - int64_t GetIntAt(std::int32_t idx) override { return GetTAtConvert(idx); } protected: ParserExecutor& Executor; diff --git a/src/StreamFormat/FMT/Context/ParserExecutor/ParserTextPropertiesExecutor/ParserANSITextPropertiesExecutor.h b/src/StreamFormat/FMT/Context/ParserExecutor/ParserTextPropertiesExecutor/ParserANSITextPropertiesExecutor.h index 87be930a..cea69085 100644 --- a/src/StreamFormat/FMT/Context/ParserExecutor/ParserTextPropertiesExecutor/ParserANSITextPropertiesExecutor.h +++ b/src/StreamFormat/FMT/Context/ParserExecutor/ParserTextPropertiesExecutor/ParserANSITextPropertiesExecutor.h @@ -14,106 +14,130 @@ namespace StreamFormat::FMT::Detail using IParserTextPropertiesExecutor::Buffer; public: - void AllPropertiesReset() override + std::expected AllPropertiesReset() override { + return std::unexpected(FMTResult::FunctionNotImpl); /*BufferReadManip(Buffer).BasicReadType('\033', '[', 0, 'm');*/ } public: - void ResetColor() override + std::expected ResetColor() override { + return std::unexpected(FMTResult::FunctionNotImpl); /*BufferReadManip(Buffer).BasicReadType('\033', '[', 39, ';', 49, 'm');*/ } - void ExecuteColor(const Detail::TextProperties::TextColor::BasicColorFG&) override + std::expected ExecuteColor(const Detail::TextProperties::TextColor::BasicColorFG&) override { + return std::unexpected(FMTResult::FunctionNotImpl); /*BufferReadManip(Buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ } - void ExecuteColor(const Detail::TextProperties::TextColor::BasicColorBG&) override + std::expected ExecuteColor(const Detail::TextProperties::TextColor::BasicColorBG&) override { + return std::unexpected(FMTResult::FunctionNotImpl); /*BufferReadManip(Buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ } - void ExecuteColor(const Detail::TextProperties::TextColor::BasicColor&) override + std::expected ExecuteColor(const Detail::TextProperties::TextColor::BasicColor&) override { + return std::unexpected(FMTResult::FunctionNotImpl); /*BufferReadManip(Buffer).BasicReadType('\033', '[', static_cast(t.Fg) , ';', static_cast(t.Bg), 'm');*/ } - void ExecuteColor(const Detail::TextProperties::TextColor::Color24bFG&) override + std::expected ExecuteColor(const Detail::TextProperties::TextColor::Color24bFG&) override { + return std::unexpected(FMTResult::FunctionNotImpl); /*BufferReadManip(Buffer).BasicReadType("\033[38;2;", t.R, ';', t.G, ';', t.B, 'm');*/ } - void ExecuteColor(const Detail::TextProperties::TextColor::Color24bBG&) override + std::expected ExecuteColor(const Detail::TextProperties::TextColor::Color24bBG&) override { + return std::unexpected(FMTResult::FunctionNotImpl); /*BufferReadManip(Buffer).BasicReadType("\033[48;2;", t.R, ';', t.G, ';', t.B, 'm');*/ } - void ExecuteColor(const Detail::TextProperties::TextColor::Color24b&) override + std::expected ExecuteColor(const Detail::TextProperties::TextColor::Color24b&) override { + return std::unexpected(FMTResult::FunctionNotImpl); /*BufferReadManip(Buffer).BasicReadType("\033[38;2;", t.Fg.R, ';', t.Fg.G, ';', t.Fg.B, "; 48; 2;", t.Bg.R, ';', t.Bg.G, ';', t.Bg.B, 'm');*/ } - void ExecuteColor(const Detail::TextProperties::TextColor::ColorCubeFG&) override + std::expected ExecuteColor(const Detail::TextProperties::TextColor::ColorCubeFG&) override { + return std::unexpected(FMTResult::FunctionNotImpl); /*BufferReadManip(Buffer).BasicReadType("\033[38;5;", t.GetColorRef(), 'm');*/ } - void ExecuteColor(const Detail::TextProperties::TextColor::ColorCubeBG&) override + std::expected ExecuteColor(const Detail::TextProperties::TextColor::ColorCubeBG&) override { + return std::unexpected(FMTResult::FunctionNotImpl); /*BufferReadManip(Buffer).BasicReadType("\033[48;5;", t.GetColorRef(), 'm');*/ } - void ExecuteColor(const Detail::TextProperties::TextColor::ColorCube&) override + std::expected ExecuteColor(const Detail::TextProperties::TextColor::ColorCube&) override { + return std::unexpected(FMTResult::FunctionNotImpl); /*BufferReadManip(Buffer).BasicReadType("\033[48;5;", t.Fg.GetColorRef(), ";48;5;", t.Bg.GetColorRef(), 'm');*/ } public: - void ResetFront() override + std::expected ResetFront() override { + return std::unexpected(FMTResult::FunctionNotImpl); /*BufferReadManip(Buffer).BasicReadType('\033', '[', Detail::TextProperties::TextFront::FrontID::DefaultFrontID, 'm');*/ } - void ExecuteFront(const Detail::TextProperties::TextFront::FrontID&) override + std::expected ExecuteFront(const Detail::TextProperties::TextFront::FrontID&) override { + return std::unexpected(FMTResult::FunctionNotImpl); /*BufferReadManip(Buffer).BasicReadType('\033', '[', t.ID, 'm');*/ } public: - void ResetStyle() override + std::expected ResetStyle() override { + return std::unexpected(FMTResult::FunctionNotImpl); /*BufferReadManip(Buffer).BasicReadType('\033', '[', 0, 'm');*/ } - void ExecuteStyle(const Detail::TextProperties::TextStyle::Intensity&) override + std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Intensity&) override { + return std::unexpected(FMTResult::FunctionNotImpl); /*BufferReadManip(Buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ } - void ExecuteStyle(const Detail::TextProperties::TextStyle::Italic&) override + std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Italic&) override { + return std::unexpected(FMTResult::FunctionNotImpl); /*BufferReadManip(Buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ } - void ExecuteStyle(const Detail::TextProperties::TextStyle::Underline&) override + std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Underline&) override { + return std::unexpected(FMTResult::FunctionNotImpl); /*BufferReadManip(Buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ } - void ExecuteStyle(const Detail::TextProperties::TextStyle::UnderlineColor::Color&) override + std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::UnderlineColor::Color&) override { + return std::unexpected(FMTResult::FunctionNotImpl); /*BufferReadManip(Buffer).BasicReadType("\033[59m");*/ } - void ExecuteStyle(const Detail::TextProperties::TextStyle::UnderlineColor::ColorCube&) override + std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::UnderlineColor::ColorCube&) override { + return std::unexpected(FMTResult::FunctionNotImpl); /*BufferReadManip(Buffer).BasicReadType("\033[58;5;", t.GetColorRef(), 'm');*/ } - void ExecuteStyle(const Detail::TextProperties::TextStyle::UnderlineColor::Color24b&) override + std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::UnderlineColor::Color24b&) override { + return std::unexpected(FMTResult::FunctionNotImpl); /*BufferReadManip(Buffer).BasicReadType("\033[58;2;", t.R, ';', t.G, ';', t.B, 'm');*/ } - void ExecuteStyle(const Detail::TextProperties::TextStyle::Blink&) override + std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Blink&) override { + return std::unexpected(FMTResult::FunctionNotImpl); /*BufferReadManip(Buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ } - void ExecuteStyle(const Detail::TextProperties::TextStyle::Inverted&) override + std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Inverted&) override { + return std::unexpected(FMTResult::FunctionNotImpl); /*BufferReadManip(Buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ } - void ExecuteStyle(const Detail::TextProperties::TextStyle::Ideogram&) override + std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Ideogram&) override { + return std::unexpected(FMTResult::FunctionNotImpl); /*BufferReadManip(Buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ } - void ExecuteStyle(const Detail::TextProperties::TextStyle::Script&) override + std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Script&) override { + return std::unexpected(FMTResult::FunctionNotImpl); /*BufferReadManip(Buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ } }; diff --git a/src/StreamFormat/FMT/Context/ParserExecutor/ParserTextPropertiesExecutor/ParserTextPropertiesExecutor.h b/src/StreamFormat/FMT/Context/ParserExecutor/ParserTextPropertiesExecutor/ParserTextPropertiesExecutor.h index 57fd4cdf..abdccd9c 100644 --- a/src/StreamFormat/FMT/Context/ParserExecutor/ParserTextPropertiesExecutor/ParserTextPropertiesExecutor.h +++ b/src/StreamFormat/FMT/Context/ParserExecutor/ParserTextPropertiesExecutor/ParserTextPropertiesExecutor.h @@ -1,7 +1,7 @@ #pragma once #include "StreamFormat/FMT/Context/BasicContext/ITextPropertiesExecutor.h" -#include "StreamFormat/FMT/Detail/Detail.h" +#include "StreamFormat/FMT/Detail/Prelude.h" #include "StreamFormat/FMT/Context/ParserExecutor/BasicParserExecutor.h" namespace StreamFormat::FMT::Detail @@ -35,35 +35,35 @@ namespace StreamFormat::FMT::Detail using IParserTextPropertiesExecutor::Buffer; public: - void AllPropertiesReset() override {} + std::expected AllPropertiesReset() override { return {}; } public: - void ResetColor() override {} - void ExecuteColor(const Detail::TextProperties::TextColor::BasicColorFG&) override {} - void ExecuteColor(const Detail::TextProperties::TextColor::BasicColorBG&) override {} - void ExecuteColor(const Detail::TextProperties::TextColor::BasicColor&) override {} - void ExecuteColor(const Detail::TextProperties::TextColor::Color24bFG&) override {} - void ExecuteColor(const Detail::TextProperties::TextColor::Color24bBG&) override {} - void ExecuteColor(const Detail::TextProperties::TextColor::Color24b&) override {} - void ExecuteColor(const Detail::TextProperties::TextColor::ColorCubeFG&) override {} - void ExecuteColor(const Detail::TextProperties::TextColor::ColorCubeBG&) override {} - void ExecuteColor(const Detail::TextProperties::TextColor::ColorCube&) override {} + std::expected ResetColor() override {} + std::expected ExecuteColor(const Detail::TextProperties::TextColor::BasicColorFG&) override { return {}; } + std::expected ExecuteColor(const Detail::TextProperties::TextColor::BasicColorBG&) override { return {}; } + std::expected ExecuteColor(const Detail::TextProperties::TextColor::BasicColor&) override { return {}; } + std::expected ExecuteColor(const Detail::TextProperties::TextColor::Color24bFG&) override { return {}; } + std::expected ExecuteColor(const Detail::TextProperties::TextColor::Color24bBG&) override { return {}; } + std::expected ExecuteColor(const Detail::TextProperties::TextColor::Color24b&) override { return {}; } + std::expected ExecuteColor(const Detail::TextProperties::TextColor::ColorCubeFG&) override { return {}; } + std::expected ExecuteColor(const Detail::TextProperties::TextColor::ColorCubeBG&) override { return {}; } + std::expected ExecuteColor(const Detail::TextProperties::TextColor::ColorCube&) override { return {}; } public: - void ResetFront() override {} - void ExecuteFront(const Detail::TextProperties::TextFront::FrontID&) override {} + std::expected ResetFront() override { return {}; } + std::expected ExecuteFront(const Detail::TextProperties::TextFront::FrontID&) override { return {}; } public: - void ResetStyle() override {} - void ExecuteStyle(const Detail::TextProperties::TextStyle::Intensity&) override {} - void ExecuteStyle(const Detail::TextProperties::TextStyle::Italic&) override {} - void ExecuteStyle(const Detail::TextProperties::TextStyle::Underline&) override {} - void ExecuteStyle(const Detail::TextProperties::TextStyle::UnderlineColor::Color&) override {} - void ExecuteStyle(const Detail::TextProperties::TextStyle::UnderlineColor::ColorCube&) override {} - void ExecuteStyle(const Detail::TextProperties::TextStyle::UnderlineColor::Color24b&) override {} - void ExecuteStyle(const Detail::TextProperties::TextStyle::Blink&) override {} - void ExecuteStyle(const Detail::TextProperties::TextStyle::Inverted&) override {} - void ExecuteStyle(const Detail::TextProperties::TextStyle::Ideogram&) override {} - void ExecuteStyle(const Detail::TextProperties::TextStyle::Script&) override {} + std::expected ResetStyle() override { return {}; } + std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Intensity&) override { return {}; } + std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Italic&) override { return {}; } + std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Underline&) override { return {}; } + std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::UnderlineColor::Color&) override { return {}; } + std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::UnderlineColor::ColorCube&) override { return {}; } + std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::UnderlineColor::Color24b&) override { return {}; } + std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Blink&) override { return {}; } + std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Inverted&) override { return {}; } + std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Ideogram&) override { return {}; } + std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Script&) override { return {}; } }; } diff --git a/src/StreamFormat/FMT/Context/ParserExecutor/ParserType.h b/src/StreamFormat/FMT/Context/ParserExecutor/ParserType.h index f234db17..0e6bfb46 100644 --- a/src/StreamFormat/FMT/Context/ParserExecutor/ParserType.h +++ b/src/StreamFormat/FMT/Context/ParserExecutor/ParserType.h @@ -1,6 +1,6 @@ #pragma once -#include "StreamFormat/FMT/Detail/Detail.h" +#include "StreamFormat/FMT/Detail/Prelude.h" #define STREAMFORMAT_PARSER_DECLARED namespace StreamFormat::FMT @@ -12,14 +12,11 @@ namespace StreamFormat::FMT { #ifdef UNKOWN_TYPE_MESSAGE // FIXME - throw Detail::FMTShouldNotEndHere{}; -#endif -#ifdef UNKOWN_TYPE_THROW - throw Detail::FMTShouldNotEndHere{}; + STREAMFORMAT_DEBUGBREAK(); + // static_cast(false); #endif #ifdef UNKOWN_TYPE_FAIL - // FIXME - throw Detail::FMTShouldNotEndHere{}; + static_cast(false); #endif #ifdef UNKOWN_TYPE_DEBUG STREAMFORMAT_DEBUGBREAK(); diff --git a/src/StreamFormat/FMT/Context/ParserExecutor/UtilityFunctions.h b/src/StreamFormat/FMT/Context/ParserExecutor/UtilityFunctions.h index c214b600..42028577 100644 --- a/src/StreamFormat/FMT/Context/ParserExecutor/UtilityFunctions.h +++ b/src/StreamFormat/FMT/Context/ParserExecutor/UtilityFunctions.h @@ -10,7 +10,7 @@ namespace StreamFormat::FMT { template - void Parse(Buffer&& bufferInput, Format&& formatInput, Args&&... args) + [[nodiscard]] std::expected Parse(Buffer&& bufferInput, Format&& formatInput, Args&&... args) { Detail::BufferInfoView buffer{bufferInput}; Detail::BufferInfoView format{formatInput}; diff --git a/src/StreamFormat/FMT/Detail/ConvertTraits.h b/src/StreamFormat/FMT/Detail/ConvertTraits.h index c270d309..59185934 100644 --- a/src/StreamFormat/FMT/Detail/ConvertTraits.h +++ b/src/StreamFormat/FMT/Detail/ConvertTraits.h @@ -1,6 +1,6 @@ #pragma once -#include "Detail.h" +#include "Prelude.h" namespace StreamFormat::FMT::Detail { diff --git a/src/StreamFormat/FMT/Detail/Exception.h b/src/StreamFormat/FMT/Detail/Exception.h deleted file mode 100644 index e0405ed2..00000000 --- a/src/StreamFormat/FMT/Detail/Exception.h +++ /dev/null @@ -1,50 +0,0 @@ -#pragma once - -#include "StreamFormat/Core/Core.h" - -#include - -// TODO: Better error msg -namespace StreamFormat::FMT::Detail -{ - class FMTException : public std::exception - { - }; - class FMTError : public FMTException - { - public: - const char* what() const noexcept override { return "FMTError"; } - }; - - class FMTParseError : public FMTError - { - public: - const char* what() const noexcept override { return "FMTParseError"; } - }; - class FMTGivenTypeError : public FMTParseError - { - public: - const char* what() const noexcept override { return "FMTGivenTypeError"; } - }; - class FMTGivenIndexError : public FMTParseError - { - public: - const char* what() const noexcept override { return "FMTGivenIndexError"; } - }; - - class FMTImplError : public FMTError - { - public: - const char* what() const noexcept override { return "FMTImplError"; } - }; - class FMTShouldNotEndHere : public FMTImplError - { - public: - const char* what() const noexcept override { return "FMTShouldNotEndHere"; } - }; - class FMTNotImplYet : public FMTImplError - { - public: - const char* what() const noexcept override { return "FMTNotImplYet"; } - }; -} diff --git a/src/StreamFormat/FMT/Detail/FMTResult.h b/src/StreamFormat/FMT/Detail/FMTResult.h new file mode 100644 index 00000000..9e9ba96a --- /dev/null +++ b/src/StreamFormat/FMT/Detail/FMTResult.h @@ -0,0 +1,26 @@ +#pragma once + +namespace StreamFormat::FMT +{ + enum class FMTResult + { + FunctionNotImpl, + + Buffer_NonValid, + Buffer_OutOfBoundAccess, + Buffer_UnableToReserveMemory, + Parse_NonValidDigit, + + ArgsInterface_Unavaible, + ArgsInterface_InvalidTypeID, + ArgsInterface_InvalidConversion, + + Specifers_Full, + Specifers_Invalid, + Specifers_DoesNotExist, + + Context_ParsingFormat, + Context_ArgumentIndexResolution, + Context_CannotApplyType, + }; +} diff --git a/src/StreamFormat/FMT/Detail/IndentHandlers.h b/src/StreamFormat/FMT/Detail/IndentHandlers.h index 4bbefa46..ee102aad 100644 --- a/src/StreamFormat/FMT/Detail/IndentHandlers.h +++ b/src/StreamFormat/FMT/Detail/IndentHandlers.h @@ -1,6 +1,6 @@ #pragma once -#include "StreamFormat/FMT/Detail/Detail.h" +#include "StreamFormat/FMT/Detail/Prelude.h" #include "StreamFormat/FMT/Buffer/FMTBufferOutManip.h" namespace StreamFormat::FMT::Detail diff --git a/src/StreamFormat/FMT/Detail/Detail.h b/src/StreamFormat/FMT/Detail/Prelude.h similarity index 81% rename from src/StreamFormat/FMT/Detail/Detail.h rename to src/StreamFormat/FMT/Detail/Prelude.h index 7efa6c34..09b12642 100644 --- a/src/StreamFormat/FMT/Detail/Detail.h +++ b/src/StreamFormat/FMT/Detail/Prelude.h @@ -1,12 +1,8 @@ #pragma once -#include "StreamFormat/Core/Core.h" - +#include "StreamFormat/Core/Prelude.h" #include "TypesTraits.h" - -#include "Exception.h" -#include "IndentHandlers.h" -#include "Specifiers.h" +#include "FMTResult.h" #define UNKOWN_TYPE_MESSAGE @@ -36,7 +32,7 @@ namespace StreamFormat::FMT::Context template class BasicFormatterExecutor; - struct ParserContextError; + struct ParserFMTError; template class BasicParserExecutor; diff --git a/src/StreamFormat/FMT/Detail/Specifiers.h b/src/StreamFormat/FMT/Detail/Specifiers.h index 13120cbe..d934e2ee 100644 --- a/src/StreamFormat/FMT/Detail/Specifiers.h +++ b/src/StreamFormat/FMT/Detail/Specifiers.h @@ -1,6 +1,7 @@ #pragma once -#include "StreamFormat/Core/Core.h" +#include "StreamFormat/Core/Prelude.h" +#include "StreamFormat/Core/Prelude.h" #include #include @@ -56,11 +57,6 @@ namespace StreamFormat::FMT::Detail public: constexpr bool BeforeIsADigit() const { return Before >= '0' && Before <= '9'; } - - constexpr void ValidateForNumber() - { - if (After >= '0' && After <= '9') After = ' '; - } }; public: @@ -185,22 +181,25 @@ namespace StreamFormat::FMT::Detail } public: - void Pushback(const FormatSpecifier& specifier) + [[nodiscard]] std::expected Pushback(const FormatSpecifier& specifier) { - if (SpecifierCount < SIZE) - Specifier[SpecifierCount++] = specifier; + if (SpecifierCount => SIZE) + return std::unexpected(FMTResult::Specifers_Full); + Specifier[SpecifierCount++] = specifier; + return {}; } - void Concat(const FormatSpecifier& specifier) + [[nodiscard]] std::expected Concat(const FormatSpecifier& specifier) { FormatSpecifier* local = Get(specifier.Name); if (local == nullptr) - return Pushback(specifier); + return SF_TRY(Pushback(specifier)); if (specifier.HasText) { local->HasText = true; local->AsText = specifier.AsText; } if (specifier.HasNumber) { local->HasNumber = true; local->AsNumber = specifier.AsNumber; } + return {}; } }; diff --git a/src/StreamFormat/FMT/Detail/TypesTraits.h b/src/StreamFormat/FMT/Detail/TypesTraits.h index d2147ac4..e36bd63e 100644 --- a/src/StreamFormat/FMT/Detail/TypesTraits.h +++ b/src/StreamFormat/FMT/Detail/TypesTraits.h @@ -1,22 +1,14 @@ #pragma once -#include "StreamFormat/Core/Core.h" +#include "StreamFormat/Core/Prelude.h" #include namespace StreamFormat::FMT::Detail { - //--------------------------------------------// - //----------------- BaseType -----------------// - //--------------------------------------------// - template using GetBaseType = std::remove_cv_t>; - //------------------------------------------------------// - //----------------- CXX Types Concepts -----------------// - //------------------------------------------------------// - template struct IsCharType { diff --git a/src/StreamFormat/FMT/Serializers/CompilationData.h b/src/StreamFormat/FMT/Serializers/CompilationData.h index 6d7d7825..33cd5f9d 100644 --- a/src/StreamFormat/FMT/Serializers/CompilationData.h +++ b/src/StreamFormat/FMT/Serializers/CompilationData.h @@ -1,6 +1,6 @@ #pragma once -#include "StreamFormat/Core/Core.h" +#include "StreamFormat/Core/Prelude.h" #include "StreamFormat/FLog.h" namespace StreamFormat::FMT::Detail @@ -48,7 +48,7 @@ namespace StreamFormat::FMT template struct FormatterType { - static void Format(const Detail::FileLocation& t, FormatterExecutor& executor) + [[nodiscard]] static inline std::expected Format(const Detail::FileLocation& t, FormatterExecutor& executor) { executor.WriteType(t.FileName); executor.BufferOut.Pushback(':'); @@ -59,7 +59,7 @@ namespace StreamFormat::FMT template struct FormatterType { - static void Format(const Detail::FunctionProperties& t, FormatterExecutor& executor) + [[nodiscard]] static inline std::expected Format(const Detail::FunctionProperties& t, FormatterExecutor& executor) { executor.WriteType(t.Location); executor.BufferOut.WriteCharArray(" @ "); diff --git a/src/StreamFormat/FMT/Serializers/FormatChrono.h b/src/StreamFormat/FMT/Serializers/FormatChrono.h index b6d34660..a5a8d566 100644 --- a/src/StreamFormat/FMT/Serializers/FormatChrono.h +++ b/src/StreamFormat/FMT/Serializers/FormatChrono.h @@ -19,12 +19,12 @@ namespace StreamFormat::FMT::Detail }; template - BufferManipResult WriteSubTime_(const std::chrono::time_point& value, BufferInfoView& pattern, FMTBufferOutInfo& buffer, TimePrintMode mode) + [[nodiscard]] std::expected WriteSubTime_(const std::chrono::time_point& value, BufferInfoView& pattern, FMTBufferOutInfo& buffer, TimePrintMode mode) { ShiftInfo shift; shift.Type = Detail::ShiftInfo::ShiftType::Right; shift.Print = Detail::ShiftInfo::ShiftPrint('0', ' '); - BufferReadManip(pattern).FastReadInteger(shift.Size); + SF_TRY(BufferReadManip(pattern).FastReadInteger(shift.Size)); if (mode == TimePrintMode::Mod && shift.Size < 0) shift.Size = 3; @@ -34,7 +34,7 @@ namespace StreamFormat::FMT::Detail std::uint32_t ns = static_cast(std::chrono::time_point_cast(value).time_since_epoch().count()); if (mode == TimePrintMode::Mod) ns = ns % 1000; - FMTBufferWriteManip(buffer).WriteInteger(static_cast(ns) % 1000, shift); + SF_TRY(FMTBufferWriteManip(buffer).WriteInteger(static_cast(ns) % 1000, shift)); } else if (BufferTestManip(pattern).IsSameForward("us", 2)) { @@ -43,7 +43,7 @@ namespace StreamFormat::FMT::Detail us = us % 1000; else if (mode == TimePrintMode::Sub) us = us / 1000; - FMTBufferWriteManip(buffer).WriteInteger(static_cast(us) % 1000, shift); + SF_TRY(FMTBufferWriteManip(buffer).WriteInteger(static_cast(us) % 1000, shift)); } else if (BufferTestManip(pattern).IsSameForward("ms", 2)) { @@ -52,7 +52,7 @@ namespace StreamFormat::FMT::Detail ms = ms % 1000; else if (mode == TimePrintMode::Sub) ms = ms / 1000000; - FMTBufferWriteManip(buffer).WriteInteger(static_cast(ms) % 1000, shift); + SF_TRY(FMTBufferWriteManip(buffer).WriteInteger(static_cast(ms) % 1000, shift)); } else if (BufferTestManip(pattern).IsEqualToForward('s')) { @@ -61,28 +61,28 @@ namespace StreamFormat::FMT::Detail sec = sec % 60; else if (mode == TimePrintMode::Sub) sec = sec / 1000000000; - FMTBufferWriteManip(buffer).WriteInteger(static_cast(sec) % 1000, shift); + SF_TRY(FMTBufferWriteManip(buffer).WriteInteger(static_cast(sec) % 1000, shift)); } else if (BufferTestManip(pattern).IsEqualToForward('m')) { std::uint32_t min = static_cast(std::chrono::time_point_cast(value).time_since_epoch().count()); if (mode == TimePrintMode::Mod) min = min % 60; - FMTBufferWriteManip(buffer).WriteInteger(static_cast(min) % 1000, shift); + SF_TRY(FMTBufferWriteManip(buffer).WriteInteger(static_cast(min) % 1000, shift)); } else if (BufferTestManip(pattern).IsEqualToForward('h')) { std::uint32_t min = static_cast(std::chrono::time_point_cast(value).time_since_epoch().count()); if (mode == TimePrintMode::Mod) min = min % 24; - FMTBufferWriteManip(buffer).WriteInteger(static_cast(min) % 1000, shift); + SF_TRY(FMTBufferWriteManip(buffer).WriteInteger(static_cast(min) % 1000, shift)); } return true; } template - BufferManipResult WriteTime(const std::chrono::time_point& value, BufferInfoView pattern, FMTBufferOutInfo& buffer) + [[nodiscard]] std::expected WriteTime(const std::chrono::time_point& value, BufferInfoView pattern, FMTBufferOutInfo& buffer) { BufferWriteManip(buffer).FastWriteString( BufferTestManip(pattern).ViewExec( @@ -118,7 +118,7 @@ namespace StreamFormat::FMT template struct FormatterType, FormatterExecutor> { - static void Format(const std::chrono::time_point& t, FormatterExecutor& executor) + [[nodiscard]] static inline std::expected Format(const std::chrono::time_point& t, FormatterExecutor& executor) { Detail::WriteTime(t, Detail::BufferInfoView(executor.Data.Specifiers.GetAsText("pattern", "%h:%m:%s.%ms")), executor.BufferOut); } @@ -127,7 +127,7 @@ namespace StreamFormat::FMT template struct FormatterType, FormatterExecutor> { - static void Format(const std::chrono::duration& t, FormatterExecutor& executor) + [[nodiscard]] static inline std::expected Format(const std::chrono::duration& t, FormatterExecutor& executor) { if (executor.Data.Specifiers.Has("pattern")) { diff --git a/src/StreamFormat/FMT/Serializers/FormatSTDLib.h b/src/StreamFormat/FMT/Serializers/FormatSTDLib.h index 945a7e25..c31722fb 100644 --- a/src/StreamFormat/FMT/Serializers/FormatSTDLib.h +++ b/src/StreamFormat/FMT/Serializers/FormatSTDLib.h @@ -16,19 +16,19 @@ namespace StreamFormat::FMT template struct FormatterType, FormatterExecutor> { - static inline void Format(const std::basic_string& t, FormatterExecutor& executor) { Detail::BufferWriteManip(executor.BufferOut).FastWriteString(t); } + [[nodiscard]] static inline std::expected Format(const std::basic_string& t, FormatterExecutor& executor) { Detail::BufferWriteManip(executor.BufferOut).FastWriteString(t); } }; template struct FormatterType, FormatterExecutor> { - static inline void Format(std::basic_string_view t, FormatterExecutor& executor) { Detail::BufferWriteManip(executor.BufferOut).FastWriteString(t); } + [[nodiscard]] static inline std::expected Format(std::basic_string_view t, FormatterExecutor& executor) { Detail::BufferWriteManip(executor.BufferOut).FastWriteString(t); } }; template struct FormatterType, FormatterExecutor> { - static inline void Format(const std::basic_stringstream& t, FormatterExecutor& executor) { Detail::BufferWriteManip(executor.BufferOut).FastWriteCharArray(t.str(), t.size()); } + [[nodiscard]] static inline std::expected Format(const std::basic_stringstream& t, FormatterExecutor& executor) { Detail::BufferWriteManip(executor.BufferOut).FastWriteCharArray(t.str(), t.size()); } }; //------------------------------------------// @@ -39,7 +39,7 @@ namespace StreamFormat::FMT template struct FormatterType, FormatterExecutor> { - static inline void Format(const std::unique_ptr& t, FormatterExecutor& executor) + [[nodiscard]] static inline std::expected Format(const std::unique_ptr& t, FormatterExecutor& executor) { if (executor.Data.TrueValue) FormatterType::Format(t.get(), executor); @@ -52,7 +52,7 @@ namespace StreamFormat::FMT template struct FormatterType, FormatterExecutor> { - static inline void Format(const std::shared_ptr& t, FormatterExecutor& executor) + [[nodiscard]] static inline std::expected Format(const std::shared_ptr& t, FormatterExecutor& executor) { if (executor.Data.TrueValue) FormatterType::Format(t.get(), executor); @@ -65,6 +65,6 @@ namespace StreamFormat::FMT template struct FormatterType, FormatterExecutor> { - static inline void Format(const std::weak_ptr& t, FormatterExecutor& executor) { FormatterType, FormatterExecutor>::Format(t.lock(), executor); } + [[nodiscard]] static inline std::expected Format(const std::weak_ptr& t, FormatterExecutor& executor) { FormatterType, FormatterExecutor>::Format(t.lock(), executor); } }; } diff --git a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_array.h b/src/StreamFormat/FMT/Serializers/STDContainer/FMT_array.h index 867b10cc..9fbc4b52 100644 --- a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_array.h +++ b/src/StreamFormat/FMT/Serializers/STDContainer/FMT_array.h @@ -8,7 +8,7 @@ namespace StreamFormat::FMT template struct FormatterType, FormatterExecutor> { - static void Format(const std::array& t, FormatterExecutor& executor) + [[nodiscard]] static inline std::expected Format(const std::array& t, FormatterExecutor& executor) { FormatterType>, FormatterExecutor>::Format(t, executor); } diff --git a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_deque.h b/src/StreamFormat/FMT/Serializers/STDContainer/FMT_deque.h index 4aca7324..b6835db7 100644 --- a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_deque.h +++ b/src/StreamFormat/FMT/Serializers/STDContainer/FMT_deque.h @@ -8,6 +8,6 @@ namespace StreamFormat::FMT template struct FormatterType, FormatterExecutor> { - static void Format(const std::deque& t, FormatterExecutor& executor) { FormatterType>, FormatterExecutor>::Format(t, executor); } + [[nodiscard]] static inline std::expected Format(const std::deque& t, FormatterExecutor& executor) { FormatterType>, FormatterExecutor>::Format(t, executor); } }; } diff --git a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_forward_list.h b/src/StreamFormat/FMT/Serializers/STDContainer/FMT_forward_list.h index 3b7224c0..d84e5ca2 100644 --- a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_forward_list.h +++ b/src/StreamFormat/FMT/Serializers/STDContainer/FMT_forward_list.h @@ -8,7 +8,7 @@ namespace StreamFormat::FMT template struct FormatterType, FormatterExecutor> { - static void Format(const std::forward_list& t, FormatterExecutor& executor) + [[nodiscard]] static inline std::expected Format(const std::forward_list& t, FormatterExecutor& executor) { FormatterType>, FormatterExecutor>::Format(t, executor); } diff --git a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_list.h b/src/StreamFormat/FMT/Serializers/STDContainer/FMT_list.h index 807d0d3e..8a1aab04 100644 --- a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_list.h +++ b/src/StreamFormat/FMT/Serializers/STDContainer/FMT_list.h @@ -8,6 +8,6 @@ namespace StreamFormat::FMT template struct FormatterType, FormatterExecutor> { - static void Format(const std::list& t, FormatterExecutor& executor) { FormatterType>, FormatterExecutor>::Format(t, executor); } + [[nodiscard]] static inline std::expected Format(const std::list& t, FormatterExecutor& executor) { FormatterType>, FormatterExecutor>::Format(t, executor); } }; } diff --git a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_map.h b/src/StreamFormat/FMT/Serializers/STDContainer/FMT_map.h index 4fca5892..750130d0 100644 --- a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_map.h +++ b/src/StreamFormat/FMT/Serializers/STDContainer/FMT_map.h @@ -10,13 +10,13 @@ namespace StreamFormat::FMT template struct FormatterType, FormatterExecutor> { - static void Format(const std::map& t, FormatterExecutor& executor) { FormatterType>, FormatterExecutor>::Format(t, executor); } + [[nodiscard]] static inline std::expected Format(const std::map& t, FormatterExecutor& executor) { FormatterType>, FormatterExecutor>::Format(t, executor); } }; template struct FormatterType, FormatterExecutor> { - static void Format(const std::multimap& t, FormatterExecutor& executor) + [[nodiscard]] static inline std::expected Format(const std::multimap& t, FormatterExecutor& executor) { FormatterType>, FormatterExecutor>::Format(t, executor); } diff --git a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_queue.h b/src/StreamFormat/FMT/Serializers/STDContainer/FMT_queue.h index ec5e4901..4d0075c7 100644 --- a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_queue.h +++ b/src/StreamFormat/FMT/Serializers/STDContainer/FMT_queue.h @@ -8,6 +8,6 @@ namespace StreamFormat::FMT template struct FormatterType, FormatterExecutor> { - static void Format(const std::queue& t, FormatterExecutor& executor) {} + [[nodiscard]] static inline std::expected Format(const std::queue& t, FormatterExecutor& executor) {} }; } diff --git a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_set.h b/src/StreamFormat/FMT/Serializers/STDContainer/FMT_set.h index abe66fbf..bc5ca78e 100644 --- a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_set.h +++ b/src/StreamFormat/FMT/Serializers/STDContainer/FMT_set.h @@ -8,12 +8,12 @@ namespace StreamFormat::FMT template struct FormatterType, FormatterExecutor> { - static void Format(const std::set& t, FormatterExecutor& executor) { FormatterType>, FormatterExecutor>::Format(t, executor); } + [[nodiscard]] static inline std::expected Format(const std::set& t, FormatterExecutor& executor) { FormatterType>, FormatterExecutor>::Format(t, executor); } }; template struct FormatterType, FormatterExecutor> { - static void Format(const std::multiset& t, FormatterExecutor& executor) { FormatterType>, FormatterExecutor>::Format(t, executor); } + [[nodiscard]] static inline std::expected Format(const std::multiset& t, FormatterExecutor& executor) { FormatterType>, FormatterExecutor>::Format(t, executor); } }; } diff --git a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_stack.h b/src/StreamFormat/FMT/Serializers/STDContainer/FMT_stack.h index d46dc35a..7468b1e7 100644 --- a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_stack.h +++ b/src/StreamFormat/FMT/Serializers/STDContainer/FMT_stack.h @@ -9,7 +9,7 @@ namespace StreamFormat::FMT template struct FormatterType, FormatterExecutor> { - static void Format(const std::stack& t, FormatterExecutor& executor) { + [[nodiscard]] static inline std::expected Format(const std::stack& t, FormatterExecutor& executor) { } }; */ diff --git a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_tuple.h b/src/StreamFormat/FMT/Serializers/STDContainer/FMT_tuple.h index c5010805..2aefd205 100644 --- a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_tuple.h +++ b/src/StreamFormat/FMT/Serializers/STDContainer/FMT_tuple.h @@ -17,17 +17,17 @@ namespace StreamFormat::FMT::TupleDetail } template - static void TupleFormatRec(FormatterExecutor& executor) + [[nodiscard]] static inline std::expected TupleFormatRec(FormatterExecutor& executor) {} template - static void TupleFormatRec(FormatterExecutor& executor, const T& t) + [[nodiscard]] static inline std::expected TupleFormatRec(FormatterExecutor& executor, const T& t) { executor.WriteType(t); } template - static void TupleFormatRec(FormatterExecutor& executor, const T& t, Args&&... args) + [[nodiscard]] static inline std::expected TupleFormatRec(FormatterExecutor& executor, const T& t, Args&&... args) { executor.WriteType(t); executor.BufferOut.Pushback(','); @@ -41,7 +41,7 @@ namespace StreamFormat::FMT template struct FormatterType, FormatterExecutor> { - static void Format(const std::tuple& t, FormatterExecutor& executor) + [[nodiscard]] static inline std::expected Format(const std::tuple& t, FormatterExecutor& executor) { executor.BufferOut.Pushback('<'); std::apply([&context](auto&&... args) { TupleDetail::TupleFormatRec(context, args...); }, t); @@ -52,7 +52,7 @@ namespace StreamFormat::FMT template struct FormatterType, FormatterExecutor> { - static void Format(const std::pair& t, FormatterExecutor& executor) + [[nodiscard]] static inline std::expected Format(const std::pair& t, FormatterExecutor& executor) { executor.BufferOut.Pushback('<'); executor.WriteType(t.first); diff --git a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_unordered_map.h b/src/StreamFormat/FMT/Serializers/STDContainer/FMT_unordered_map.h index a5843f51..d554dc0d 100644 --- a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_unordered_map.h +++ b/src/StreamFormat/FMT/Serializers/STDContainer/FMT_unordered_map.h @@ -10,7 +10,7 @@ namespace StreamFormat::FMT template struct FormatterType, FormatterExecutor> { - static void Format(const std::unordered_map& t, FormatterExecutor& executor) + [[nodiscard]] static inline std::expected Format(const std::unordered_map& t, FormatterExecutor& executor) { FormatterType>, FormatterExecutor>::Format(t, executor); } @@ -19,7 +19,7 @@ namespace StreamFormat::FMT template struct FormatterType, FormatterExecutor> { - static void Format(const std::unordered_multimap& t, FormatterExecutor& executor) + [[nodiscard]] static inline std::expected Format(const std::unordered_multimap& t, FormatterExecutor& executor) { FormatterType>, FormatterExecutor>::Format(t, executor); } diff --git a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_unordered_set.h b/src/StreamFormat/FMT/Serializers/STDContainer/FMT_unordered_set.h index fd113ae0..b7ea41ae 100644 --- a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_unordered_set.h +++ b/src/StreamFormat/FMT/Serializers/STDContainer/FMT_unordered_set.h @@ -8,7 +8,7 @@ namespace StreamFormat::FMT template struct FormatterType, FormatterExecutor> { - static void Format(const std::unordered_set& t, FormatterExecutor& executor) + [[nodiscard]] static inline std::expected Format(const std::unordered_set& t, FormatterExecutor& executor) { FormatterType>, FormatterExecutor>::Format(t, executor); } @@ -17,7 +17,7 @@ namespace StreamFormat::FMT template struct FormatterType, FormatterExecutor> { - static void Format(const std::unordered_multiset& t, FormatterExecutor& executor) + [[nodiscard]] static inline std::expected Format(const std::unordered_multiset& t, FormatterExecutor& executor) { FormatterType>, FormatterExecutor>::Format(t, executor); } diff --git a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_vector.h b/src/StreamFormat/FMT/Serializers/STDContainer/FMT_vector.h index acbc42c1..de90d079 100644 --- a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_vector.h +++ b/src/StreamFormat/FMT/Serializers/STDContainer/FMT_vector.h @@ -8,6 +8,6 @@ namespace StreamFormat::FMT template struct FormatterType, FormatterExecutor> { - static void Format(const std::vector& t, FormatterExecutor& executor) { FormatterType>, FormatterExecutor>::Format(t, executor); } + [[nodiscard]] static inline std::expected Format(const std::vector& t, FormatterExecutor& executor) { FormatterType>, FormatterExecutor>::Format(t, executor); } }; } diff --git a/src/StreamFormat/FMT/TextProperties/BaseTextProperties.h b/src/StreamFormat/FMT/TextProperties/BaseTextProperties.h index de5eecad..158fad39 100644 --- a/src/StreamFormat/FMT/TextProperties/BaseTextProperties.h +++ b/src/StreamFormat/FMT/TextProperties/BaseTextProperties.h @@ -1,6 +1,6 @@ #pragma once -#include "StreamFormat/Core/Core.h" +#include "StreamFormat/Core/Prelude.h" // According to : https://en.wikipedia.org/wiki/ANSI_escape_code diff --git a/src/StreamFormat/Json/JsonParser.cpp b/src/StreamFormat/Json/JsonParser.cpp index b1ec4537..ff4977bb 100644 --- a/src/StreamFormat/Json/JsonParser.cpp +++ b/src/StreamFormat/Json/JsonParser.cpp @@ -18,13 +18,13 @@ namespace StreamFormat::JSON::Detail if (parser.IsJsonStringBegin()) { - manip.Skip('"'); + manip.SkipOneOf('"'); while (true) { manip.GoTo('"'); if (FMT::Detail::BufferTestAccess(parser.BufferIn).PrevIsNotEqualTo('\\')) break; } - manip.Skip('"'); + manip.SkipOneOf('"'); } else if (parser.IsJsonNumberBegin()) { diff --git a/src/StreamFormat/Json/JsonParser.h b/src/StreamFormat/Json/JsonParser.h index 3672345e..4d7c4569 100644 --- a/src/StreamFormat/Json/JsonParser.h +++ b/src/StreamFormat/Json/JsonParser.h @@ -18,12 +18,12 @@ namespace StreamFormat::JSON::Detail {} public: - inline FMT::Detail::BufferManipResult IsJsonStringBegin() const { return FMT::Detail::BufferTestAccess(BufferIn).IsEqualTo('"'); } - inline FMT::Detail::BufferManipResult IsJsonNumberBegin() const { return FMT::Detail::BufferTestAccess(BufferIn).IsADigit() || FMT::Detail::BufferTestAccess(BufferIn).IsEqualTo('+', '-', '.'); } - inline FMT::Detail::BufferManipResult IsJsonBooleanBegin() const { return FMT::Detail::BufferTestAccess(BufferIn).IsEqualTo('t', 'f'); } - inline FMT::Detail::BufferManipResult IsJsonStructBegin() const { return FMT::Detail::BufferTestAccess(BufferIn).IsEqualTo('{'); } - inline FMT::Detail::BufferManipResult IsJsonArrayBegin() const { return FMT::Detail::BufferTestAccess(BufferIn).IsEqualTo('['); } - inline FMT::Detail::BufferManipResult IsJsonNullBegin() const { return FMT::Detail::BufferTestAccess(BufferIn).IsEqualTo('n'); } + inline bool IsJsonStringBegin() const { return FMT::Detail::BufferTestAccess(BufferIn).IsEqualTo('"'); } + inline bool IsJsonNumberBegin() const { return FMT::Detail::BufferTestAccess(BufferIn).IsADigit() || FMT::Detail::BufferTestAccess(BufferIn).IsEqualTo('+', '-', '.'); } + inline bool IsJsonBooleanBegin() const { return FMT::Detail::BufferTestAccess(BufferIn).IsEqualTo('t', 'f'); } + inline bool IsJsonStructBegin() const { return FMT::Detail::BufferTestAccess(BufferIn).IsEqualTo('{'); } + inline bool IsJsonArrayBegin() const { return FMT::Detail::BufferTestAccess(BufferIn).IsEqualTo('['); } + inline bool IsJsonNullBegin() const { return FMT::Detail::BufferTestAccess(BufferIn).IsEqualTo('n'); } public: FMT::Detail::BufferInfo BufferIn; diff --git a/src/StreamFormat/Json/JsonSerializer.h b/src/StreamFormat/Json/JsonSerializer.h index fb3c589d..8d9bbcb5 100644 --- a/src/StreamFormat/Json/JsonSerializer.h +++ b/src/StreamFormat/Json/JsonSerializer.h @@ -171,7 +171,7 @@ namespace StreamFormat::JSON FMT::Detail::BufferTestAccess access(parser.BufferIn); FMT::Detail::BufferTestManip manip(parser.BufferIn); - manip.Skip('{'); + manip.SkipOneOf('{'); std::size_t idx = 0; while (FMT::Detail::BufferAccess(parser.BufferIn).IsEndOfString() == false) @@ -183,16 +183,16 @@ namespace StreamFormat::JSON JsonStringSerializer::ParseSTDString(name, parser); manip.SkipAllBlanks(); - manip.Skip(':'); + manip.SkipOneOf(':'); manip.SkipAllBlanks(); subObjectParsingFunction(t, idx++, std::move(name), parser); manip.GoTo(',', '}'); - manip.Skip(','); + manip.SkipOneOf(','); } - manip.Skip('}'); + manip.SkipOneOf('}'); } template @@ -236,7 +236,7 @@ namespace StreamFormat::JSON FMT::Detail::BufferTestAccess access(parser.BufferIn); FMT::Detail::BufferTestManip manip(parser.BufferIn); - manip.Skip('['); + manip.SkipOneOf('['); std::size_t idx = 0; while (FMT::Detail::BufferAccess(parser.BufferIn).IsEndOfString() == false) @@ -248,10 +248,10 @@ namespace StreamFormat::JSON subObjectParsingFunction(t, idx++, parser); manip.GoTo(',', ']'); - manip.Skip(','); + manip.SkipOneOf(','); } - manip.Skip(']'); + manip.SkipOneOf(']'); } template diff --git a/src/StreamFormat/ProfilerManager/Event.h b/src/StreamFormat/ProfilerManager/Event.h index 57cca1d0..54bfccc1 100644 --- a/src/StreamFormat/ProfilerManager/Event.h +++ b/src/StreamFormat/ProfilerManager/Event.h @@ -2,7 +2,7 @@ #include "Detail.h" #include "EventData.h" -#include "StreamFormat/Core/Core.h" +#include "StreamFormat/Core/Prelude.h" #include "StreamFormat/FMT.h" #include diff --git a/src/StreamFormat/ProfilerManager/Profiler.h b/src/StreamFormat/ProfilerManager/Profiler.h index d5a20e2f..103ceaa6 100644 --- a/src/StreamFormat/ProfilerManager/Profiler.h +++ b/src/StreamFormat/ProfilerManager/Profiler.h @@ -1,6 +1,6 @@ #pragma once -#include "StreamFormat/Core/Core.h" +#include "StreamFormat/Core/Prelude.h" #include "StreamFormat/FLog.h" #include "AllEvents.h" From e76ae945cdd642352bdbec2d387ff00861e3767b Mon Sep 17 00:00:00 2001 From: BELLIER Sacha Date: Sun, 24 Nov 2024 22:59:07 +0100 Subject: [PATCH 03/42] fix: it compile now --- Tests/FMT/Globber.cpp | 30 ++-- Tests/FMT/Limits.cpp | 34 ++-- Tests/FMT/TextProperties.cpp | 4 +- src/StreamFormat/Core/Prelude.h | 14 +- src/StreamFormat/FMT/Buffer/BufferManip.h | 26 +++ .../BufferOutManager/BasicBufferOutManager.h | 1 + src/StreamFormat/FMT/Buffer/BufferOutManip.h | 2 +- src/StreamFormat/FMT/Buffer/BufferReadManip.h | 17 +- src/StreamFormat/FMT/Buffer/BufferTestManip.h | 35 +++- .../FMT/Buffer/BufferWriteManip.h | 5 +- .../FMT/Buffer/FMTBufferOutManip.h | 2 +- .../FMT/Buffer/FMTBufferReadManip.h | 28 ++-- .../FMT/Buffer/Utils/BufferGlobberManip.h | 14 +- .../FMT/Buffer/Utils/BufferShiftManip.h | 23 +-- .../FMT/Buffer/Utils/BufferUtils.h | 15 +- .../FMT/Context/BasicContext/BasicContext.h | 21 +-- .../BasicContext/BasicContextParse-impl.h | 158 ++++++++++-------- .../BasicContext/TextPropertiesManager-impl.h | 143 ++++++++-------- .../BasicContext/TextPropertiesManager.cpp | 10 +- .../BasicContext/TextPropertiesManager.h | 125 +++++++------- .../BasicFormatterExecutor.h | 18 +- .../FormatterExecutor/FormatBasics-impl.h | 7 +- .../Context/FormatterExecutor/FormatterArgs.h | 19 +-- .../FormatterANSITextPropertiesExecutor.h | 1 + .../Context/FormatterExecutor/FormatterType.h | 5 - .../FormatterExecutor/UtilityFunctions.h | 76 ++++----- .../ParserExecutor/BasicParserExecutor.h | 3 +- .../Context/ParserExecutor/ParseBasics-impl.h | 29 +++- .../FMT/Context/ParserExecutor/ParserArgs.h | 21 ++- .../ParserANSITextPropertiesExecutor.h | 48 +++--- .../ParserTextPropertiesExecutor.h | 48 +++--- src/StreamFormat/FMT/Detail/FMTResult.h | 3 + src/StreamFormat/FMT/Detail/Specifiers.h | 4 +- .../FMT/Serializers/FormatChrono.h | 34 ++-- src/StreamFormat/Json/JsonFormatter.h | 6 +- src/StreamFormat/Json/JsonObjects.h | 2 +- src/StreamFormat/Json/JsonParser.cpp | 7 +- src/StreamFormat/Json/JsonSerializer.h | 58 +++---- .../ProfilerManager/ProfilerFactory.cpp | 2 +- src/StreamFormat/Tester/TestSuite/TestSuite.h | 28 ++-- 40 files changed, 600 insertions(+), 526 deletions(-) diff --git a/Tests/FMT/Globber.cpp b/Tests/FMT/Globber.cpp index 32171173..824cd53f 100644 --- a/Tests/FMT/Globber.cpp +++ b/Tests/FMT/Globber.cpp @@ -5,14 +5,14 @@ #include "StreamFormat/FMT/Buffer/Utils/BufferGlobberManip.h" PCT_TEST_GROUP(FMT, GLOBBER); -#define TEST_GLOBBER(data, glob) \ - { \ - StreamFormat::FMT::Detail::BufferInfoView p_buffer(data); \ - StreamFormat::FMT::Detail::BufferInfoView p_glob(glob); \ - StreamFormat::FMT::Detail::Globber::BufferInExecGlob(p_buffer, \ - p_glob); \ - PCT_ASSERT( \ - StreamFormat::FMT::Detail::BufferAccess(p_buffer).IsEndOfString()); \ +#define TEST_GLOBBER(data, glob) \ + { \ + StreamFormat::FMT::Detail::BufferInfoView p_buffer(data); \ + StreamFormat::FMT::Detail::BufferInfoView p_glob(glob); \ + StreamFormat::FMT::Detail::Globber::BufferInExecGlob(p_buffer, \ + p_glob).value(); \ + PCT_ASSERT( \ + StreamFormat::FMT::Detail::BufferAccess(p_buffer).IsEndOfString()); \ } PCT_TEST_FUNC(GLOBBER, BASIC_WILDCARD){ @@ -25,36 +25,36 @@ PCT_TEST_FUNC(GLOBBER, BASIC_WILDCARD){ PCT_TEST_GROUP(FMT, PARSE_GLOBBER); PCT_TEST_FUNC(PARSE_GLOBBER, PG_BASIC_WILDCARD) { int k = 0; - StreamFormat::FMT::Parse("|123|", "|{}|", k); + StreamFormat::FMT::Parse("|123|", "|{}|", k).value(); PCT_EQ(k, 123); { char test[5]; - StreamFormat::FMT::Parse("|test|", "|{}|", test); + StreamFormat::FMT::Parse("|test|", "|{}|", test).value(); // PCT_EQ(std::string(test), std::string("test")); } { char test[4]; - StreamFormat::FMT::Parse("|test|", "|{:no-zero-end}|", test); + StreamFormat::FMT::Parse("|test|", "|{:no-zero-end}|", test).value(); // PCT_EQ(std::string(test, 4), std::string("test")); } { char test[4]; - StreamFormat::FMT::Parse("|test|", "|{}t|", test); + StreamFormat::FMT::Parse("|test|", "|{}t|", test).value(); // PCT_EQ(std::string(test), std::string("tes")); } { char test[11]; - StreamFormat::FMT::Parse("|test123456|", "|{}|", test); + StreamFormat::FMT::Parse("|test123456|", "|{}|", test).value(); // PCT_EQ(std::string(test), std::string("test123456")); } { char test[11]; - StreamFormat::FMT::Parse("|test123456|", "|{:glob='*1'}23456|", test); + StreamFormat::FMT::Parse("|test123456|", "|{:glob='*1'}23456|", test).value(); // PCT_EQ(std::string(test), std::string("test1")); } @@ -66,7 +66,7 @@ PCT_TEST_FUNC(PARSE_GLOBBER, PG_BASIC_WILDCARD) { "?" "?" "?'}123456|", - test); + test).value(); // PCT_EQ(std::string(test), std::string("test")); } } diff --git a/Tests/FMT/Limits.cpp b/Tests/FMT/Limits.cpp index 2ce24103..3af6e564 100644 --- a/Tests/FMT/Limits.cpp +++ b/Tests/FMT/Limits.cpp @@ -8,7 +8,7 @@ PCT_TEST_GROUP(FMT, LIMITS); #define PCT_TEST_FUNC_LowBufferSize(k) \ PCT_TEST_FUNC(LIMITS, LowBufferSize##k) { \ char buffer[k] = {0}; \ - StreamFormat::FMT::FormatInChar(buffer, "0123456789"); \ + StreamFormat::FMT::FormatInChar(buffer, "0123456789").value(); \ for (int i = 0; i < k; ++i) \ PCT_EQ(buffer[i] - '0', i); \ } @@ -26,28 +26,28 @@ PCT_TEST_FUNC_LowBufferSize(1); PCT_TEST_FUNC(LIMITS, PlainLowBufferSize10) { char buffer[10] = {0}; - StreamFormat::FMT::FormatInChar(buffer, "0123456789"); + StreamFormat::FMT::FormatInChar(buffer, "0123456789").value(); for (int i = 0; i < 10; ++i) PCT_EQ(buffer[i] - '0', i); } PCT_TEST_FUNC(LIMITS, PlainLowBufferSize1) { char buffer[1] = {0}; - StreamFormat::FMT::FormatInChar(buffer, "0"); + StreamFormat::FMT::FormatInChar(buffer, "0").value(); for (int i = 0; i < 1; ++i) PCT_EQ(buffer[i] - '0', i); } -#define PCT_TEST_FUNC_LowBufferSizeArray(k) \ - PCT_TEST_FUNC(LIMITS, LowBufferSizeArray##k) { \ - char buffer[k] = {0}; \ - const char fmtBuffer[] = { \ - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; \ - StreamFormat::FMT::Detail::BufferInfoView format(fmtBuffer, k); \ - StreamFormat::FMT::Detail::GivenBufferOutManager manager(buffer, k); \ - StreamFormat::FMT::Detail::FormatInManager(manager, false, format); \ - for (int i = 0; i < k; ++i) \ - PCT_EQ(buffer[i] - '0', i); \ +#define PCT_TEST_FUNC_LowBufferSizeArray(k) \ + PCT_TEST_FUNC(LIMITS, LowBufferSizeArray##k) { \ + char buffer[k] = {0}; \ + const char fmtBuffer[] = { \ + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; \ + StreamFormat::FMT::Detail::BufferInfoView format(fmtBuffer, k); \ + StreamFormat::FMT::Detail::GivenBufferOutManager manager(buffer, k); \ + StreamFormat::FMT::Detail::FormatInManager(manager, false, format).value(); \ + for (int i = 0; i < k; ++i) \ + PCT_EQ(buffer[i] - '0', i); \ } PCT_TEST_FUNC_LowBufferSizeArray(10); @@ -66,7 +66,7 @@ PCT_TEST_FUNC(LIMITS, PlainLowBufferSizeArray10) { const char fmtBuffer[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; StreamFormat::FMT::Detail::BufferInfoView fmt(fmtBuffer, 10); StreamFormat::FMT::Detail::GivenBufferOutManager manager(buffer, 10); - StreamFormat::FMT::Detail::FormatInManager(manager, false, fmt); + StreamFormat::FMT::Detail::FormatInManager(manager, false, fmt).value(); for (int i = 0; i < 10; ++i) PCT_EQ(buffer[i] - '0', i); } @@ -76,7 +76,7 @@ PCT_TEST_FUNC(LIMITS, PlainLowBufferSizeArray1) { const char fmtBuffer[] = {'0'}; StreamFormat::FMT::Detail::BufferInfoView fmt(fmtBuffer, 1); StreamFormat::FMT::Detail::GivenBufferOutManager manager(buffer, 1); - StreamFormat::FMT::Detail::FormatInManager(manager, false, fmt); + StreamFormat::FMT::Detail::FormatInManager(manager, false, fmt).value(); for (int i = 0; i < 1; ++i) PCT_EQ(buffer[i] - '0', i); } @@ -88,7 +88,7 @@ PCT_TEST_FUNC(LIMITS, LowBufferSizeArray10FMT30) { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; StreamFormat::FMT::Detail::BufferInfoView fmt(fmtBuffer, 30); StreamFormat::FMT::Detail::GivenBufferOutManager manager(buffer, 10); - StreamFormat::FMT::Detail::FormatInManager(manager, false, fmt); + StreamFormat::FMT::Detail::FormatInManager(manager, false, fmt).value(); for (int k = 0; k < 10; ++k) PCT_EQ(buffer[k] - '0', k); } @@ -98,7 +98,7 @@ PCT_TEST_FUNC(LIMITS, LowBufferSizeArray5Number9) { StreamFormat::FMT::Detail::BufferInfoView fmt("{}"); StreamFormat::FMT::Detail::GivenBufferOutManager manager(buffer, 10); std::uint64_t i = 9'876'543'210; - StreamFormat::FMT::Detail::FormatInManager(manager, false, fmt, i); + StreamFormat::FMT::Detail::FormatInManager(manager, false, fmt, i).value(); for (int k = 0; k < 10; ++k) PCT_EQ(buffer[k] - '0', 9 - k); } diff --git a/Tests/FMT/TextProperties.cpp b/Tests/FMT/TextProperties.cpp index ba9351f2..954e347d 100644 --- a/Tests/FMT/TextProperties.cpp +++ b/Tests/FMT/TextProperties.cpp @@ -5,7 +5,7 @@ PCT_TEST_GROUP(FMT, TEXT_PROPERTIES); -#define TEST_FMT(fmt_test, expected) PCT_EQ(Escaper(StreamFormat::FMT::FormatString(fmt_test, 0)), Escaper(expected)) +#define TEST_FMT(fmt_test, expected) PCT_EQ(Escaper(StreamFormat::FMT::FormatString(fmt_test, 0).value()), Escaper(expected)) static std::string Escaper(const std::string& str) { @@ -83,7 +83,7 @@ class TEST_FMT_ContextOut }; STREAMFORMAT_AUTO_FORMATTER_T(TEST_FMT_ContextOut, "{C:red} TEST_FMT_ContextOut {} ", 0); -#define TEST_FMT_CONTEXT(fmt_test, expected) PCT_EQ(Escaper(StreamFormat::FMT::FormatString(fmt_test, TEST_FMT_ContextOut{})), Escaper(expected)) +#define TEST_FMT_CONTEXT(fmt_test, expected) PCT_EQ(Escaper(StreamFormat::FMT::FormatString(fmt_test, TEST_FMT_ContextOut{}).value()), Escaper(expected)) PCT_TEST_FUNC(TEXT_PROPERTIES, ContextOut) { diff --git a/src/StreamFormat/Core/Prelude.h b/src/StreamFormat/Core/Prelude.h index f722589b..9704d8ce 100644 --- a/src/StreamFormat/Core/Prelude.h +++ b/src/StreamFormat/Core/Prelude.h @@ -30,21 +30,21 @@ #define STREAMFORMAT_DEBUGBREAK() #endif +// https://github.com/SerenityOS/serenity/blob/50642f85ac547a3caee353affcb08872cac49456/AK/Try.h #include #include -// https://github.com/SerenityOS/serenity/blob/50642f85ac547a3caee353affcb08872cac49456/AK/Try.h +#include + #define SF_TRY(exp) ({ \ auto __expected = exp; \ if (not __expected) [[unlikely]] \ - return __expected; \ + return std::unexpected(__expected.error()); \ __expected.value(); \ }); -#define SF_TRY_TERR(exp, transform_error) ({ \ +#define SF_TRY_OR(exp, error) ({ \ auto __expected = exp; \ if (not __expected) [[unlikely]] \ - return __expected.transform_error(transform_error); \ + return std::unexpected(error); \ __expected.value(); \ - }); - -#define SF_TRY_OR(exp, new_error) SF_TRY_TERR(exp, [](auto){return new_error;}) \ No newline at end of file + }); \ No newline at end of file diff --git a/src/StreamFormat/FMT/Buffer/BufferManip.h b/src/StreamFormat/FMT/Buffer/BufferManip.h index 222c9078..9c390178 100644 --- a/src/StreamFormat/FMT/Buffer/BufferManip.h +++ b/src/StreamFormat/FMT/Buffer/BufferManip.h @@ -25,6 +25,19 @@ namespace StreamFormat::FMT::Detail constexpr inline bool IsEmpty() const noexcept { return Buffer.CurrentPos >= Buffer.BufferEnd; } constexpr inline bool IsEndOfString() const noexcept { return IsEmpty() || Buffer.Get() == 0; } + [[nodiscard]] constexpr inline std::expected, FMTResult> GetNext(const std::size_t count = 1) const + { + if (BufferAccess(Buffer).CanMoveForward(count) == false) + return std::unexpected(FMTResult::Buffer_OutOfBoundAccess); + return BufferManip(Buffer).GetNextForce(count); + } + [[nodiscard]] constexpr inline std::expected, FMTResult> GetPrev(const std::size_t count = 1) const + { + if (BufferAccess(Buffer).CanMoveBackward(count) == false) + return std::unexpected(FMTResult::Buffer_OutOfBoundAccess); + return BufferManip(Buffer).GetPrevForce(count); + } + constexpr inline TChar GetNextForce(const std::size_t count = 1) const noexcept { return *(Buffer.CurrentPos + count); } constexpr inline TChar GetPrevForce(const std::size_t count = 1) const noexcept { return *(Buffer.CurrentPos - count); } }; @@ -73,6 +86,19 @@ namespace StreamFormat::FMT::Detail return {}; } + [[nodiscard]] constexpr inline std::expected, FMTResult> GetAndForward() + { + if (BufferAccess(Buffer).CanMoveForward(1) == false) + return std::unexpected(FMTResult::Buffer_OutOfBoundAccess); + return *Buffer.CurrentPos++; + } + [[nodiscard]] constexpr inline std::expected, FMTResult> GetAndBackward() + { + if (BufferAccess(Buffer).CanMoveBackward(1) == false) + return std::unexpected(FMTResult::Buffer_OutOfBoundAccess); + return *Buffer.CurrentPos--; + } + constexpr inline TChar GetAndForceForward() noexcept { return *Buffer.CurrentPos++; } constexpr inline TChar GetAndForceBackward() noexcept { return *Buffer.CurrentPos--; } }; diff --git a/src/StreamFormat/FMT/Buffer/BufferOutManager/BasicBufferOutManager.h b/src/StreamFormat/FMT/Buffer/BufferOutManager/BasicBufferOutManager.h index 03721d90..ee0de785 100644 --- a/src/StreamFormat/FMT/Buffer/BufferOutManager/BasicBufferOutManager.h +++ b/src/StreamFormat/FMT/Buffer/BufferOutManager/BasicBufferOutManager.h @@ -15,6 +15,7 @@ namespace StreamFormat::FMT::Detail class BasicBufferOutManager { public: + BasicBufferOutManager() = default; virtual ~BasicBufferOutManager() = default; BasicBufferOutManager(BasicBufferOutManager&) = delete; BasicBufferOutManager& operator=(BasicBufferOutManager&) = delete; diff --git a/src/StreamFormat/FMT/Buffer/BufferOutManip.h b/src/StreamFormat/FMT/Buffer/BufferOutManip.h index a5f9b461..c7046ba7 100644 --- a/src/StreamFormat/FMT/Buffer/BufferOutManip.h +++ b/src/StreamFormat/FMT/Buffer/BufferOutManip.h @@ -65,7 +65,7 @@ namespace StreamFormat::FMT::Detail [[nodiscard]] std::expected AddSize(const std::size_t count) noexcept { if (Buffer.Manager == nullptr) - return std::unexpected(FMTResult::NonValidBuffer); + return std::unexpected(FMTResult::Buffer_NonValid); std::size_t currentSize = BufferAccess(Buffer).GetBufferCurrentSize(); if (not Buffer.Manager->AddSize(count)) return std::unexpected(FMTResult::Buffer_UnableToReserveMemory); diff --git a/src/StreamFormat/FMT/Buffer/BufferReadManip.h b/src/StreamFormat/FMT/Buffer/BufferReadManip.h index 545a7450..76558a48 100644 --- a/src/StreamFormat/FMT/Buffer/BufferReadManip.h +++ b/src/StreamFormat/FMT/Buffer/BufferReadManip.h @@ -19,7 +19,7 @@ namespace StreamFormat::FMT::Detail { bool sign = false; if constexpr (std::is_signed_v) - { sign = BufferTestManip(Buffer).IsEqualToForward('-'); } + { sign = SF_TRY(BufferTestManip(Buffer).IsEqualToForward('-')); } if (!BufferTestAccess(Buffer).IsADigit()) { return std::unexpected(FMTResult::Parse_NonValidDigit); } @@ -47,14 +47,11 @@ namespace StreamFormat::FMT::Detail bool sign = SF_TRY(manip.IsEqualToForward('-')); if (access.IsADigit()) - { - SF_TRY(FastReadInteger(intpart)); - } - else if (access.IsEqualTo('.') == false) - { - SF_TRY(manip.Forward()); - return std::unexpected(FMTResult::Parse_NonValidDigit); - } + { SF_TRY(FastReadInteger(intpart)); } + else if (access.IsEqualTo('.')) + { SF_TRY(Detail::BufferManip(Buffer).Forward()); } + else + { return std::unexpected(FMTResult::Parse_NonValidDigit); } if (floatPrecision < 0) { @@ -92,8 +89,8 @@ namespace StreamFormat::FMT::Detail } // TODO : Opti with bigger types - while (sizeToCopy-- != 0) { *str++ = BufferManip(Buffer).GetAndForward(); } + while (sizeToCopy-- != 0) if (isZeroEnded) { *str = 0; } return {}; diff --git a/src/StreamFormat/FMT/Buffer/BufferTestManip.h b/src/StreamFormat/FMT/Buffer/BufferTestManip.h index e5569eef..c5c7da60 100644 --- a/src/StreamFormat/FMT/Buffer/BufferTestManip.h +++ b/src/StreamFormat/FMT/Buffer/BufferTestManip.h @@ -80,14 +80,20 @@ namespace StreamFormat::FMT::Detail [[nodiscard]] constexpr inline std::expected IsEqualToForward(const CharToTest... ele) noexcept { if (Access().IsEqualTo(ele...)) - { return BufferManip(Buffer).Forward().transform([]{return true;}); } + { + SF_TRY(BufferManip(Buffer).Forward()); + return true; + } return false; } template [[nodiscard]] constexpr inline std::expected IsNotEqualForward(const CharToTest... ele) noexcept { if (Access().IsNotEqualTo(ele...)) - { return BufferManip(Buffer).Forward().transform([]{return true;}); } + { + SF_TRY(BufferManip(Buffer).Forward()); + return true; + } return false; } @@ -96,20 +102,31 @@ namespace StreamFormat::FMT::Detail [[nodiscard]] constexpr std::expected IsSameForward(const CharToTest* str, std::size_t size) noexcept { if (Access().IsSame(str, size)) - { return BufferManip(Buffer).Forward().transform([]{return true;}); } + { + SF_TRY(BufferManip(Buffer).Forward()); + return true; + } return false; } template [[nodiscard]] constexpr inline std::expected IsSameForward(std::basic_string_view sv) noexcept { if (Access().IsSame(sv)) - { return BufferManip(Buffer).Forward().transform([]{return true;}); } + { + SF_TRY(BufferManip(Buffer).Forward()); + return true; + } return false; } public: template - [[nodiscard]] inline std::expected SkipOneOf(const CharToTest... ele) noexcept { return IsEqualToForward(ele...).transform([]{}); } + [[nodiscard]] inline std::expected SkipOneOf(const CharToTest... ele) noexcept + { + SF_TRY(IsEqualToForward(ele...)); + return {}; + } + template inline void SkipEvery(const CharToTest... ele) noexcept { @@ -140,18 +157,18 @@ namespace StreamFormat::FMT::Detail public: template - std::basic_string_view ViewExec(Func&& func) + [[nodiscard]] std::expected, FMTResult> ViewExec(Func&& func) { TChar* begin = Buffer.CurrentPos; - func(); + SF_TRY(func()); TChar* end = Buffer.CurrentPos; return std::basic_string_view(begin, end - begin); } template - inline std::basic_string_view ViewUntil(CharToTest&&... c) + [[nodiscard]] inline std::expected, FMTResult> ViewUntil(CharToTest&&... c) { - return ViewExec([&]{BufferTestManip(Buffer).GoTo(std::forward(c)...);}); + return ViewExec([&] -> std::expected { BufferTestManip(Buffer).GoTo(std::forward(c)...); return {}; }); } }; } diff --git a/src/StreamFormat/FMT/Buffer/BufferWriteManip.h b/src/StreamFormat/FMT/Buffer/BufferWriteManip.h index 2bcea37e..16ec2508 100644 --- a/src/StreamFormat/FMT/Buffer/BufferWriteManip.h +++ b/src/StreamFormat/FMT/Buffer/BufferWriteManip.h @@ -118,12 +118,15 @@ namespace StreamFormat::FMT::Detail template [[nodiscard]] constexpr std::expected FastWriteCharArray(const CharInput* str, std::size_t size) { - if (BufferOutManip(Buffer).Reserve(size) == false) + auto reserve = BufferOutManip(Buffer).Reserve(size); + if (reserve.has_value() == false) return FastWriteCharArray(str, BufferAccess(Buffer).GetBufferRemainingSize()); // TODO: Opti with bigger types while (size-- != 0 && *str != 0) BufferOutManip(Buffer).ForcePushback(*str++); + + return {}; } template [[nodiscard]] inline constexpr std::expected FastWriteString(std::basic_string_view sv) diff --git a/src/StreamFormat/FMT/Buffer/FMTBufferOutManip.h b/src/StreamFormat/FMT/Buffer/FMTBufferOutManip.h index d4a2bb9b..f94661e7 100644 --- a/src/StreamFormat/FMT/Buffer/FMTBufferOutManip.h +++ b/src/StreamFormat/FMT/Buffer/FMTBufferOutManip.h @@ -56,7 +56,7 @@ namespace StreamFormat::FMT::Detail [[nodiscard]] constexpr inline std::expected PushbackCheckIndent(const TChar c) { SF_TRY(BufferOutManip(Buffer).Pushback(c)); - return if (c == '\n') BufferOutManip(Buffer).Pushback(' ', Buffer.Indent); + if (c == '\n') return BufferOutManip(Buffer).Pushback(' ', Buffer.Indent); } }; diff --git a/src/StreamFormat/FMT/Buffer/FMTBufferReadManip.h b/src/StreamFormat/FMT/Buffer/FMTBufferReadManip.h index ebe77f24..288edb51 100644 --- a/src/StreamFormat/FMT/Buffer/FMTBufferReadManip.h +++ b/src/StreamFormat/FMT/Buffer/FMTBufferReadManip.h @@ -30,7 +30,7 @@ namespace StreamFormat::FMT::Detail bool sign = false; if constexpr (std::is_signed_v) { - sign = manip.IsEqualToForward('-'); + sign = SF_TRY(manip.IsEqualToForward('-')); if (sign) --shift.Size; } @@ -38,7 +38,8 @@ namespace StreamFormat::FMT::Detail while (access.IsADigit()) { - res = res * 10 + (BufferManipException(Buffer).GetAndForward() - '0'); + char c = SF_TRY(BufferManip(Buffer).GetAndForward()); + res = res * 10 + (c - '0'); --shift.Size; } @@ -48,7 +49,7 @@ namespace StreamFormat::FMT::Detail } public: template - [[nodiscard]] std::expected ReadFloat(T& i, std::int32_t floatPrecision = -1, ShiftInfo shift = ShiftInfo{}) + [[nodiscard]] std::expected ReadFloat(T& t, std::int32_t floatPrecision = -1, ShiftInfo shift = ShiftInfo{}) { BufferShiftReadManip shiftManip(Buffer); Detail::BufferTestAccess access(Buffer); @@ -59,22 +60,20 @@ namespace StreamFormat::FMT::Detail bool sign = manip.IsEqualToForward('-'); if (sign) --shift.Size; - T res = 0; - - bool hasIntPart = false; - if (access.IsNotEqualTo('.')) + T intpart = static_cast(0); + if (access.IsADigit()) { - hasIntPart = access.IsADigit(); - if (hasIntPart == false) return; while (access.IsADigit()) { - res = res * 10 + (BufferManipException(Buffer).GetAndForward() - '0'); + char c = SF_TRY(BufferManip(Buffer).GetAndForward()); + intpart = intpart * 10 + (c - '0'); --shift.Size; } } - - sign ? i = -res : i = res; - if (manip.IsEqualToForward('.') == false) return; + else if (access.IsEqualTo('.')) + { SF_TRY(Detail::BufferManip(Buffer).Forward()); } + else + { return std::unexpected(FMTResult::Parse_NonValidDigit); } if (floatPrecision <= 0) while (access.IsADigit() && access.IsEndOfString() == false) @@ -102,7 +101,8 @@ namespace StreamFormat::FMT::Detail shiftManip.SkipShiftEnd(shift); - sign ? i = -res - dec : i = res + dec; + t = sign ? - intpart - dec : intpart + dec; + return {}; } public: diff --git a/src/StreamFormat/FMT/Buffer/Utils/BufferGlobberManip.h b/src/StreamFormat/FMT/Buffer/Utils/BufferGlobberManip.h index f5ff4859..5c249bc3 100644 --- a/src/StreamFormat/FMT/Buffer/Utils/BufferGlobberManip.h +++ b/src/StreamFormat/FMT/Buffer/Utils/BufferGlobberManip.h @@ -16,7 +16,7 @@ namespace StreamFormat::FMT::Detail }; private: - static const TChar* BufferInExecGlob_(BufferInfo& bufferIn, BufferInfo& glob) + [[nodiscard]] static std::expected BufferInExecGlob_(BufferInfo& bufferIn, BufferInfo& glob) { if (BufferAccess(glob).IsEndOfString()) return bufferIn.CurrentPos; @@ -31,11 +31,11 @@ namespace StreamFormat::FMT::Detail else if (BufferTestAccess(glob).IsEqualTo('*')) { BufferManip(glob).Forward(); - const TChar* further = BufferInExecGlob_(bufferIn, glob); + const TChar* further = SF_TRY(BufferInExecGlob_(bufferIn, glob)); while (BufferAccess(bufferIn).CanMoveForward()) { BufferManip(bufferIn).Forward(); - const TChar* last = BufferInExecGlob_(bufferIn, glob); + const TChar* last = SF_TRY(BufferInExecGlob_(bufferIn, glob)); if (last > further || further == nullptr) further = last; } return further; @@ -49,8 +49,8 @@ namespace StreamFormat::FMT::Detail BufferInfoView charSet(begin, end - begin); - bool is_inverted = BufferTestManip(glob).IsEqualToForward('!'); - TChar toMatch = BufferManipException(bufferIn).GetAndForward(); + bool is_inverted = SF_TRY(BufferTestManip(glob).IsEqualToForward('!')); + TChar toMatch = SF_TRY(BufferManip(bufferIn).GetAndForward()); bool found = false; while (found == false && BufferAccess(charSet).CanMoveForward()) @@ -92,9 +92,9 @@ namespace StreamFormat::FMT::Detail } public: - static void BufferInExecGlob(BufferInfo& bufferIn, BufferInfo& glob, [[maybe_unused]] PatternMatchType patternMatchtype = PatternMatchType::MatchBiggest) + [[nodiscard]] static std::expected BufferInExecGlob(BufferInfo& bufferIn, BufferInfo& glob, [[maybe_unused]] PatternMatchType patternMatchtype = PatternMatchType::MatchBiggest) { - const TChar* furtherPointMatched = BufferInExecGlob_(bufferIn, glob); + const TChar* furtherPointMatched = SF_TRY(BufferInExecGlob_(bufferIn, glob)); if (furtherPointMatched != nullptr) bufferIn.CurrentPos = furtherPointMatched; } diff --git a/src/StreamFormat/FMT/Buffer/Utils/BufferShiftManip.h b/src/StreamFormat/FMT/Buffer/Utils/BufferShiftManip.h index dfe258b1..49e29903 100644 --- a/src/StreamFormat/FMT/Buffer/Utils/BufferShiftManip.h +++ b/src/StreamFormat/FMT/Buffer/Utils/BufferShiftManip.h @@ -20,7 +20,7 @@ namespace StreamFormat::FMT::Detail { std::int32_t shift_ = shift.Size / 2; if (shift.Type == Detail::ShiftInfo::ShiftType::CenterLeft) shift_ = (shift.Size + 1) / 2; - BufferOutManip(Buffer).Pushback(shift.Print.Before, shift.Size - shift_); + SF_TRY(BufferOutManip(Buffer).Pushback(shift.Print.Before, shift.Size - shift_)); shift.Size = shift_; } } @@ -28,31 +28,31 @@ namespace StreamFormat::FMT::Detail [[nodiscard]] inline std::expected WriteShiftCenterEnd(Detail::ShiftInfo& shift) { if (shift.Type == Detail::ShiftInfo::ShiftType::CenterRight || shift.Type == Detail::ShiftInfo::ShiftType::CenterLeft) - BufferOutManip(Buffer).Pushback(shift.Print.After, shift.Size); + return BufferOutManip(Buffer).Pushback(shift.Print.After, shift.Size); } [[nodiscard]] inline std::expected WriteShiftRightAll(Detail::ShiftInfo& shift) { if (shift.Type == Detail::ShiftInfo::ShiftType::Right) - BufferOutManip(Buffer).Pushback(shift.Print.Before, shift.Size); + return BufferOutManip(Buffer).Pushback(shift.Print.Before, shift.Size); } [[nodiscard]] inline std::expected WriteShiftLeftAll(Detail::ShiftInfo& shift) { if (shift.Type == Detail::ShiftInfo::ShiftType::Left) - BufferOutManip(Buffer).Pushback(shift.Print.After, shift.Size); + return BufferOutManip(Buffer).Pushback(shift.Print.After, shift.Size); } [[nodiscard]] inline std::expected WriteShiftBegin(Detail::ShiftInfo& shift) { - WriteShiftCenterBegin(shift); - WriteShiftRightAll(shift); + SF_TRY(WriteShiftCenterBegin(shift)); + return WriteShiftRightAll(shift); } [[nodiscard]] inline std::expected WriteShiftEnd(Detail::ShiftInfo& shift) { - WriteShiftLeftAll(shift); - WriteShiftCenterEnd(shift); + SF_TRY(WriteShiftLeftAll(shift)); + return WriteShiftCenterEnd(shift); } }; @@ -67,11 +67,12 @@ namespace StreamFormat::FMT::Detail public: [[nodiscard]] std::expected SkipShiftBeginSpace(Detail::ShiftInfo& shift) { - if (shift.Print.BeforeIsADigit() == false) return; + if (shift.Print.BeforeIsADigit() == false) + return {}; if (shift.Type == Detail::ShiftInfo::ShiftType::Right || shift.Type == Detail::ShiftInfo::ShiftType::CenterLeft || shift.Type == Detail::ShiftInfo::ShiftType::CenterRight) while (Buffer.Get() == ' ') { - BufferManip(Buffer).Forward(); + SF_TRY(BufferManip(Buffer).Forward()); --shift.Size; } } @@ -81,7 +82,7 @@ namespace StreamFormat::FMT::Detail if (shift.Type == Detail::ShiftInfo::ShiftType::Left || shift.Type == Detail::ShiftInfo::ShiftType::CenterLeft || shift.Type == Detail::ShiftInfo::ShiftType::CenterRight) while (Buffer.Get() == ' ' && shift.Size > 0) { - BufferManip(Buffer).Forward(); + SF_TRY(BufferManip(Buffer).Forward()); --shift.Size; } } diff --git a/src/StreamFormat/FMT/Buffer/Utils/BufferUtils.h b/src/StreamFormat/FMT/Buffer/Utils/BufferUtils.h index 627fd036..8b8da918 100644 --- a/src/StreamFormat/FMT/Buffer/Utils/BufferUtils.h +++ b/src/StreamFormat/FMT/Buffer/Utils/BufferUtils.h @@ -39,12 +39,13 @@ namespace StreamFormat::FMT::Detail using DictPairs = std::pair, T>; template - [[nodiscard]] std::expected GetWordFromDictPairs(const DictPairs (&data)[SIZE]) + [[nodiscard]] std::expected GetWordFromDictPairs(const DictPairs (&data)[SIZE]) { for (std::size_t idx = 0; idx < SIZE; ++idx) { bool found = SF_TRY(BufferTestManip(Buffer).IsSameForward(data[idx].first)); - if (found) return data[idx].second; + if (found) + return data[idx].second; } return std::unexpected(FMTResult::Specifers_Invalid); } @@ -59,9 +60,8 @@ namespace StreamFormat::FMT::Detail SF_TRY(Detail::BufferTestManip(buffer).SkipOneOf('"')); while (Detail::BufferAccess(buffer).IsEndOfString() == false) { - SF_TRY(Detail::BufferWriteManip(stringOut).FastWriteString( - Detail::BufferTestManip(buffer).ViewUntil('"', '\\') - )); + auto view = SF_TRY(Detail::BufferTestManip(buffer).ViewUntil('"', '\\')); + SF_TRY(Detail::BufferWriteManip(stringOut).FastWriteString(view)); if (Detail::BufferTestAccess(buffer).IsEqualTo('"')) break; @@ -94,9 +94,8 @@ namespace StreamFormat::FMT::Detail SF_TRY(Detail::BufferOutManip(buffer).Pushback('"')); while (Detail::BufferAccess(stringIn).IsEndOfString() == false) { - SF_TRY(Detail::BufferWriteManip(buffer).FastWriteString( - Detail::BufferTestManip(stringIn).ViewUntil('\\') - )); + auto view = SF_TRY(Detail::BufferTestManip(stringIn).ViewUntil('\\')); + SF_TRY(Detail::BufferWriteManip(buffer).FastWriteString(view)); if (Detail::BufferAccess(stringIn).IsEndOfString()) break; diff --git a/src/StreamFormat/FMT/Context/BasicContext/BasicContext.h b/src/StreamFormat/FMT/Context/BasicContext/BasicContext.h index 9e0dc3e7..452a9aa7 100644 --- a/src/StreamFormat/FMT/Context/BasicContext/BasicContext.h +++ b/src/StreamFormat/FMT/Context/BasicContext/BasicContext.h @@ -2,6 +2,7 @@ #include "StreamFormat/FMT/Detail/ConvertTraits.h" #include "StreamFormat/FMT/Detail/Prelude.h" +#include "StreamFormat/FMT/Detail/Specifiers.h" #include "StreamFormat/FMT/Buffer/BufferInfo.h" #include "StreamFormat/FMT/Buffer/BufferManip.h" @@ -67,10 +68,10 @@ namespace StreamFormat::FMT::Context [[nodiscard]] std::expected FormatReadParameter(const T& defaultValue); protected: - std::expected FormatDataApplyNextOverride(); + void FormatDataApplyNextOverride(); protected: - std::basic_string_view ParseNextOverrideFormatData(); + [[nodiscard]] std::expected, FMTResult> ParseNextOverrideFormatData(); [[nodiscard]] std::expected ParseFormatDataBase(); [[nodiscard]] std::expected ParseFormatDataSpecial(); @@ -110,7 +111,7 @@ namespace StreamFormat::FMT::Context {} template - std::expected BasicContext::Run() + [[nodiscard]] std::expected BasicContext::Run() { while (!Detail::BufferAccess(Format).IsEndOfString()) { @@ -124,11 +125,7 @@ namespace StreamFormat::FMT::Context SF_TRY(Executor.ExecRawString(std::basic_string_view(beginContinousString, sizeContinousString))); if (Detail::BufferAccess(Format).IsEndOfString() == false && Detail::BufferTestAccess(Format).IsEqualTo('{')) - { - bool parseArg = Parse(); - if (parseArg == false) - SF_TRY(Executor.ExecRawString("{")); - } + { Parse(); } } } @@ -156,14 +153,12 @@ namespace StreamFormat::FMT::Context } // SubIndex - std::int32_t formatIdx = SF_TRY(GetFormatIndex(formatIdx)); SF_TRY(Detail::BufferTestManip(Format).SkipOneOf('}')); + std::int32_t formatIdx = SF_TRY(GetFormatIndex()); if constexpr (std::is_convertible_v) - i = static_cast(ArgsInterface.GetIntAt(formatIdx)); + return ArgsInterface.GetIntAt(formatIdx); else if constexpr (std::is_convertible_v>) - i = static_cast(ArgsInterface.GetStringAt(formatIdx)); - - return true; + return ArgsInterface.GetStringAt(formatIdx); } } diff --git a/src/StreamFormat/FMT/Context/BasicContext/BasicContextParse-impl.h b/src/StreamFormat/FMT/Context/BasicContext/BasicContextParse-impl.h index 0327f784..d380e9b1 100644 --- a/src/StreamFormat/FMT/Context/BasicContext/BasicContextParse-impl.h +++ b/src/StreamFormat/FMT/Context/BasicContext/BasicContextParse-impl.h @@ -12,7 +12,7 @@ namespace StreamFormat::FMT::Context { template - std::basic_string_view BasicContext::ParseNextOverrideFormatData() + [[nodiscard]] std::expected, FMTResult> BasicContext::ParseNextOverrideFormatData() { Detail::BufferTestAccess access(Format); Detail::BufferTestManip manip(Format); @@ -43,26 +43,26 @@ namespace StreamFormat::FMT::Context } template - std::expected BasicContext::ParseFormatDataBase() + [[nodiscard]] std::expected BasicContext::ParseFormatDataBase() { Detail::BufferTestManip manip(Format); if (manip.IsEqualToForward('C')) - Executor.TextManager.ParseColor(*this); + { SF_TRY(Executor.TextManager.ParseColor(*this)); } else if (manip.IsEqualToForward('S')) - Executor.TextManager.ParseStyle(*this); + { SF_TRY(Executor.TextManager.ParseStyle(*this)); } else if (manip.IsEqualToForward('F')) - Executor.TextManager.ParseFront(*this); + { SF_TRY(Executor.TextManager.ParseFront(*this)); } else if (manip.IsEqualToForward('K')) - Executor.Data.KeepNewStyle = true; + { Executor.Data.KeepNewStyle = true; } else if (manip.IsEqualToForward('N')) - Executor.Data.NextOverride = ParseNextOverrideFormatData(); + { Executor.Data.NextOverride = SF_TRY(ParseNextOverrideFormatData()); } } template - std::expected BasicContext::ParseFormatDataSpecial_ShiftType(const Detail::ShiftInfo::ShiftType type) + [[nodiscard]] std::expected BasicContext::ParseFormatDataSpecial_ShiftType(const Detail::ShiftInfo::ShiftType type) { Executor.Data.Shift.Type = type; Executor.Data.Shift.Size = SF_TRY(FormatReadParameter(-1)); @@ -70,32 +70,45 @@ namespace StreamFormat::FMT::Context { Executor.Data.Shift.Print.Before = SF_TRY(Detail::BufferManip(Format).GetAndForward()); Executor.Data.Shift.Print.After = Executor.Data.Shift.Print.Before; - if (SF_TRY(Detail::BufferTestManip(Format).IsEqualToForward('|'))) + if (Detail::BufferTestAccess(Format).IsEqualTo('|')) + { + Detail::BufferManip(Format).Forward(); Executor.Data.Shift.Print.After = SF_TRY(Detail::BufferManip(Format).GetAndForward()); + } } } template - std::expected BasicContext::ParseFormatDataSpecial() + [[nodiscard]] std::expected BasicContext::ParseFormatDataSpecial() { Detail::BufferTestAccess access(Format); Detail::BufferTestManip manip(Format); - if (manip.IsEqualToForward('{')) + if (access.IsEqualTo('{')) { - std::int32_t formatIndex = 0; - if (GetFormatIndex(formatIndex) == false) return; - - if ((Executor.Data.TestApply(ArgsInterface.template GetTypeAt>(formatIndex)) || - Executor.Data.TestApply(ArgsInterface.template GetTypeAt>(formatIndex)) || - Executor.Data.TestApply(ArgsInterface.template GetTypeAt(formatIndex)) || - Executor.Data.TestApply(ArgsInterface.template GetTypeAt(formatIndex))) == false) - return std::unexpected(FMTResult::CannotApplyType); + SF_TRY(Detail::BufferManip(Format).Forward()); + std::int32_t formatIndex = (std::int32_t)SF_TRY(GetFormatIndex()); + bool ableToApply = false; + + auto applyFormatData = SF_TRY(ArgsInterface.template GetTypeAt>(formatIndex)); + ableToApply |= Executor.Data.TestApply(applyFormatData); + auto applyFormatSpecifier = SF_TRY(ArgsInterface.template GetTypeAt>(formatIndex)); + ableToApply |= Executor.Data.TestApply(applyFormatSpecifier); + auto applyIntegerPrintBase = SF_TRY(ArgsInterface.template GetTypeAt(formatIndex)); + ableToApply |= Executor.Data.TestApply(applyIntegerPrintBase); + auto applyShiftInfo = SF_TRY(ArgsInterface.template GetTypeAt(formatIndex)); + ableToApply |= Executor.Data.TestApply(applyShiftInfo); + + if (not ableToApply) + return std::unexpected(FMTResult::Context_CannotApplyType); SF_TRY(manip.IsEqualToForward('}')); } - else if (manip.IsEqualToForward('.')) + else if (access.IsEqualTo('.')) + { + SF_TRY(Detail::BufferManip(Format).Forward()); Executor.Data.FloatPrecision = SF_TRY(FormatReadParameter(-1)); + } else if (access.IsEqualTo('d', 'b', 'B', 'o', 'O', 'x', 'X')) { @@ -103,26 +116,38 @@ namespace StreamFormat::FMT::Context Executor.Data.IntegerPrint = static_cast(get); } - else if (manip.IsEqualToForward('#')) + else if (access.IsEqualTo('#')) + { + SF_TRY(Detail::BufferManip(Format).Forward()); Executor.Data.PrefixSuffix = true; + } - - else if (manip.IsEqualToForward('>')) - ParseFormatDataSpecial_ShiftType(Detail::ShiftInfo::ShiftType::Right); - - else if (manip.IsEqualToForward('<')) - ParseFormatDataSpecial_ShiftType(Detail::ShiftInfo::ShiftType::Left); - - else if (manip.IsEqualToForward('^')) + else if (access.IsEqualTo('>')) + { + SF_TRY(Detail::BufferManip(Format).Forward()); + SF_TRY(ParseFormatDataSpecial_ShiftType(Detail::ShiftInfo::ShiftType::Right)); + } + else if (access.IsEqualTo('<')) { - if (manip.IsEqualToForward('<')) - ParseFormatDataSpecial_ShiftType(Detail::ShiftInfo::ShiftType::CenterLeft); + SF_TRY(Detail::BufferManip(Format).Forward()); + SF_TRY(ParseFormatDataSpecial_ShiftType(Detail::ShiftInfo::ShiftType::Left)); + } + else if (access.IsEqualTo('^')) + { + SF_TRY(Detail::BufferManip(Format).Forward()); + if (access.IsEqualTo('<')) + { + SF_TRY(Detail::BufferManip(Format).Forward()); + SF_TRY(ParseFormatDataSpecial_ShiftType(Detail::ShiftInfo::ShiftType::CenterLeft)); + } else { - manip.IsEqualToForward('>'); - ParseFormatDataSpecial_ShiftType(Detail::ShiftInfo::ShiftType::CenterRight); + SF_TRY(manip.IsEqualToForward('>')); + SF_TRY(ParseFormatDataSpecial_ShiftType(Detail::ShiftInfo::ShiftType::CenterRight)); } } + + return {}; } template @@ -131,36 +156,37 @@ namespace StreamFormat::FMT::Context Detail::BufferTestAccess access(Format); Detail::BufferTestManip manip(Format); - std::basic_string_view name = manip.ViewExec( - [&]{Detail::FMTBufferParamsManip(Format).ParamGoTo(' ', '=', '\'', '{', ',');} - ); + std::basic_string_view name = SF_TRY(manip.ViewExec( + [&] -> std::expected { Detail::FMTBufferParamsManip(Format).ParamGoTo(' ', '=', '\'', '{', ','); return {}; } + )); Detail::FMTBufferParamsManip(Format).ParamGoTo('=', '\'', '{', ','); - manip.IsEqualToForward('='); + SF_TRY(manip.IsEqualToForward('=')); manip.SkipAllSpaces(); if (manip.IsEqualToForward('\'')) { - std::basic_string_view value = Detail::BufferTestManip(Format).ViewUntil('\''); - Executor.Data.Specifiers.Concat(Detail::FormatSpecifier{name, value}); + std::basic_string_view value = SF_TRY(Detail::BufferTestManip(Format).ViewUntil('\'')); + SF_TRY(Executor.Data.Specifiers.Concat(Detail::FormatSpecifier{name, value})); } else if (access.IsADigit()) { std::int32_t value = 0; - Detail::BufferReadManip(Format).FastReadInteger(value); - Executor.Data.Specifiers.Concat(Detail::FormatSpecifier{name, value}); + SF_TRY(Detail::BufferReadManip(Format).FastReadInteger(value)); + SF_TRY(Executor.Data.Specifiers.Concat(Detail::FormatSpecifier{name, value})); } else if (manip.IsEqualToForward('{')) { - std::int32_t idx = 0; - GetFormatIndex(idx); + std::int32_t idx = SF_TRY(GetFormatIndex()); // TODO / FIXME // Executor.Data.Specifiers.Concat(Detail::FormatSpecifier{name, GetTypeAtIndexAuto(idx)}); - manip.IsEqualToForward('}'); + SF_TRY(manip.IsEqualToForward('}')); } else if (access.IsEqualTo(',', '}')) { - Executor.Data.Specifiers.Concat(Detail::FormatSpecifier{name}); + SF_TRY(Executor.Data.Specifiers.Concat(Detail::FormatSpecifier{name})); } + + return {}; } /////---------- Impl ----------///// @@ -188,7 +214,7 @@ namespace StreamFormat::FMT::Context } template - std::expected BasicContext::GetFormatIndex() + [[nodiscard]] std::expected BasicContext::GetFormatIndex() { const TChar* mainSubFormat = Format.CurrentPos; @@ -198,20 +224,14 @@ namespace StreamFormat::FMT::Context // I : if there is no number specified : ':' or '}' if (access.IsEqualTo(':') || access.IsEqualTo('}')) if (ValuesIndex < ArgsInterface.Size()) - { - idx = ValuesIndex++; - return true; - } + { return ValuesIndex++; } // II: A number(idx) std::int32_t subIndex = -1; if (Detail::BufferReadManip(Format).FastReadInteger(subIndex).has_value()) if (access.IsEqualTo(':') || access.IsEqualTo('}')) if (subIndex >= 0 && subIndex < ArgsInterface.Size()) - { - idx = subIndex; - return true; - } + { return subIndex; } Format.CurrentPos = mainSubFormat; // III : A name @@ -220,10 +240,7 @@ namespace StreamFormat::FMT::Context { std::int32_t indexOfNamedArg = currentNamedArg.value(); if (indexOfNamedArg >= 0 && indexOfNamedArg < ArgsInterface.Size()) - { - idx = indexOfNamedArg; - return true; - } + { return indexOfNamedArg; } Format.CurrentPos = mainSubFormat; } @@ -232,22 +249,22 @@ namespace StreamFormat::FMT::Context { SF_TRY(Detail::BufferManip(Format).Forward()); std::int32_t recIndex = SF_TRY(GetFormatIndex()); - if (manip.IsEqualTo('}') && recIndex >= 0 && recIndex < ArgsInterface.Size()) + if (access.IsEqualTo('}') && recIndex >= 0 && recIndex < ArgsInterface.Size()) { SF_TRY(Detail::BufferManip(Format).Forward()); manip.SkipAllSpaces(); if (access.IsEqualTo(':', '}')) { - std::int32_t finalRecIndex = SF_TRY(ArgsInterface.GetFormatIndexAt(recIndex)); + std::int32_t finalRecIndex = (std::int32_t)SF_TRY(ArgsInterface.GetIntAt(recIndex)); if (finalRecIndex >= 0 && finalRecIndex < ArgsInterface.Size()) return finalRecIndex; - return false; + return std::unexpected(FMTResult::Context_ArgumentIndexResolution); } } } Format.CurrentPos = mainSubFormat; - return std::unexpected(FMTResult::ArgumentIndexResolution); + return std::unexpected(FMTResult::Context_ArgumentIndexResolution); } template @@ -278,19 +295,18 @@ namespace StreamFormat::FMT::Context if (Detail::BufferTestAccess(Format).IsUpperCase()) { - ParseFormatData(); - Detail::FMTBufferParamsManip(Format).ParamGoToForward(); // Skip } - return true; + SF_TRY(ParseFormatData()); + return Detail::FMTBufferParamsManip(Format).ParamGoToForward(); // Skip } } - std::int32_t formatIdx = -1; - if (GetFormatIndex(formatIdx) && formatIdx >= 0 && formatIdx < ArgsInterface.Size()) + std::int32_t formatIdx = SF_TRY(GetFormatIndex()); + if (formatIdx >= 0 && formatIdx < ArgsInterface.Size()) { - ParseVariable(formatIdx); - Detail::FMTBufferParamsManip(Format).ParamGoToForward(); // Skip } - return true; + SF_TRY(ParseVariable(formatIdx)); + return Detail::FMTBufferParamsManip(Format).ParamGoToForward(); // Skip } } - return false; + SF_TRY(Executor.ExecRawString("{")); + return {}; } } diff --git a/src/StreamFormat/FMT/Context/BasicContext/TextPropertiesManager-impl.h b/src/StreamFormat/FMT/Context/BasicContext/TextPropertiesManager-impl.h index d4c9f4b6..a4f722a9 100644 --- a/src/StreamFormat/FMT/Context/BasicContext/TextPropertiesManager-impl.h +++ b/src/StreamFormat/FMT/Context/BasicContext/TextPropertiesManager-impl.h @@ -11,61 +11,64 @@ namespace StreamFormat::FMT::Detail { template - std::expected Detail::TextPropertiesManager::ApplyColorOnIndex(Context::BasicContext& context, std::int32_t index) + [[nodiscard]] std::expected Detail::TextPropertiesManager::ApplyColorOnIndex(Context::BasicContext& context, std::int32_t index) { - context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextColor::Color& data) { this->ReloadColor(data); }); - context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextColor::BasicColorFG& data) { this->AskApplyColor(data); }); - context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextColor::BasicColorBG& data) { this->AskApplyColor(data); }); - context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextColor::ColorCubeFG& data) { this->AskApplyColor(data); }); - context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextColor::ColorCubeBG& data) { this->AskApplyColor(data); }); - context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextColor::Color24bFG& data) { this->AskApplyColor(data); }); - context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextColor::Color24bBG& data) { this->AskApplyColor(data); }); + SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( + index, [this](const Detail::TextProperties::TextColor::Color& data) { this->ReloadColor(data); })); + SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( + index, [this](const Detail::TextProperties::TextColor::BasicColorFG& data) { this->AskApplyColor(data); })); + SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( + index, [this](const Detail::TextProperties::TextColor::BasicColorBG& data) { this->AskApplyColor(data); })); + SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( + index, [this](const Detail::TextProperties::TextColor::ColorCubeFG& data) { this->AskApplyColor(data); })); + SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( + index, [this](const Detail::TextProperties::TextColor::ColorCubeBG& data) { this->AskApplyColor(data); })); + SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( + index, [this](const Detail::TextProperties::TextColor::Color24bFG& data) { this->AskApplyColor(data); })); + SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( + index, [this](const Detail::TextProperties::TextColor::Color24bBG& data) { this->AskApplyColor(data); })); + return {}; } template - std::expected Detail::TextPropertiesManager::ApplyFrontOnIndex(Context::BasicContext& context, std::int32_t index) + [[nodiscard]] std::expected Detail::TextPropertiesManager::ApplyFrontOnIndex(Context::BasicContext& context, std::int32_t index) { - context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextFront::Front& data) { this->ReloadFront(data); }); - context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextFront::FrontID& data) { this->AskApplyFront(data); }); + SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( + index, [this](const Detail::TextProperties::TextFront::Front& data) { this->ReloadFront(data); })); + SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( + index, [this](const Detail::TextProperties::TextFront::FrontID& data) { this->AskApplyFront(data); })); + return {}; } template - std::expected Detail::TextPropertiesManager::ApplyStyleOnIndex(Context::BasicContext& context, std::int32_t index) + [[nodiscard]] std::expected Detail::TextPropertiesManager::ApplyStyleOnIndex(Context::BasicContext& context, std::int32_t index) { - context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextStyle::Style& data) { return this->ReloadStyle(data); }); - context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextStyle::Intensity& data) { return this->AskApplyStyle(data); }); - context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextStyle::Italic& data) { return this->AskApplyStyle(data); }); - context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextStyle::Underline& data) { return this->AskApplyStyle(data); }); - context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextStyle::Blink& data) { return this->AskApplyStyle(data); }); - context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextStyle::Inverted& data) { return this->AskApplyStyle(data); }); - context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextStyle::Ideogram& data) { return this->AskApplyStyle(data); }); - context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextStyle::Script& data) { return this->AskApplyStyle(data); }); - - context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextStyle::UnderlineColor::ColorCube& data) { this->AskApplyStyle(data); }); - context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextStyle::UnderlineColor::Color24b& data) { this->AskApplyStyle(data); }); + SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( + index, [this](const Detail::TextProperties::TextStyle::Style& data) { return this->ReloadStyle(data); })); + SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( + index, [this](const Detail::TextProperties::TextStyle::Intensity& data) { return this->AskApplyStyle(data); })); + SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( + index, [this](const Detail::TextProperties::TextStyle::Italic& data) { return this->AskApplyStyle(data); })); + SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( + index, [this](const Detail::TextProperties::TextStyle::Underline& data) { return this->AskApplyStyle(data); })); + SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( + index, [this](const Detail::TextProperties::TextStyle::Blink& data) { return this->AskApplyStyle(data); })); + SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( + index, [this](const Detail::TextProperties::TextStyle::Inverted& data) { return this->AskApplyStyle(data); })); + SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( + index, [this](const Detail::TextProperties::TextStyle::Ideogram& data) { return this->AskApplyStyle(data); })); + SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( + index, [this](const Detail::TextProperties::TextStyle::Script& data) { return this->AskApplyStyle(data); })); + + SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( + index, [this](const Detail::TextProperties::TextStyle::UnderlineColor::ColorCube& data) { this->AskApplyStyle(data); })); + SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( + index, [this](const Detail::TextProperties::TextStyle::UnderlineColor::Color24b& data) { this->AskApplyStyle(data); })); + return {}; } template - std::expected Detail::TextPropertiesManager::ParseColor(Context::BasicContext& context) + [[nodiscard]] std::expected Detail::TextPropertiesManager::ParseColor(Context::BasicContext& context) { if (BufferTestManip(context.Format).IsEqualToForward(':')) { @@ -78,39 +81,37 @@ namespace StreamFormat::FMT::Detail } else { - Detail::TextProperties::TextColor::BasicColorFG colorFg; - bool colorFgFound = SF_TRY(GetColorCode(context.Format, colorFg)); - + auto colorFg = GetColorCode(context.Format); FMTBufferParamsManip(context.Format).ParamGoTo('-', ','); if (BufferTestManip(context.Format).IsEqualToForward('-')) { BufferTestManip(context.Format).SkipAllSpaces(); - Detail::TextProperties::TextColor::BasicColorBG colorBg; - bool colorBgFound = SF_TRY(GetColorCode(context.Format, colorBg)); - if (colorBgFound && colorFgFound) - AskApplyColor(Detail::TextProperties::TextColor::BasicColor{colorFg, colorBg}); + auto colorBg = GetColorCode(context.Format); + if (colorBg.has_value() && colorFg.has_value()) + return AskApplyColor(Detail::TextProperties::TextColor::BasicColor{colorFg.value(), colorBg.value()}); else - ReloadDefaultColor(); + return ReloadDefaultColor(); } else { - if (colorFgFound) - AskApplyColor(colorFg); + if (colorFg.has_value()) + return AskApplyColor(colorFg.value()); else - ReloadDefaultColor(); + return ReloadDefaultColor(); } } } else - ReloadDefaultColor(); + return ReloadDefaultColor(); + return {}; } template - std::expected Detail::TextPropertiesManager::ParseStyle(Context::BasicContext& context) + [[nodiscard]] std::expected Detail::TextPropertiesManager::ParseStyle(Context::BasicContext& context) { if (BufferTestAccess(context.Format).IsEqualTo(':')) { - SF_TRY(BufferTestManip(context.Format).Forward()); + SF_TRY(BufferManip(context.Format).Forward()); if (!BufferTestAccess(context.Format).IsEqualTo('}', ',')) { bool l = true; @@ -119,7 +120,7 @@ namespace StreamFormat::FMT::Detail BufferTestManip(context.Format).SkipAllSpaces(); if (BufferTestManip(context.Format).IsEqualToForward('{')) { - std::int32_t idx = SF_TRY(context.GetFormatIndex(idx)); + std::int32_t idx = SF_TRY(context.GetFormatIndex()); ApplyStyleOnIndex(context, idx); BufferTestManip(context.Format).IsEqualToForward('}'); } @@ -137,10 +138,11 @@ namespace StreamFormat::FMT::Detail } else return ReloadDefaultStyle(); + return {}; } template - std::expected Detail::TextPropertiesManager::ParseStyleNamed(BufferInfoView& format) + [[nodiscard]] std::expected Detail::TextPropertiesManager::ParseStyleNamed(BufferInfoView& format) { Detail::BufferUtilsManip utils(format); @@ -182,33 +184,34 @@ namespace StreamFormat::FMT::Detail {"subscript", Detail::TextProperties::TextStyle::Script::Subscript}, {"n-script", Detail::TextProperties::TextStyle::Script::AllDisable}}; - std::uint8_t code = (std::uint8_t)BufferUtilsManip(format).GetWordFromDictPairs(styleIntensity); + std::uint8_t code = (std::uint8_t)SF_TRY(BufferUtilsManip(format).GetWordFromDictPairs(styleIntensity)); if (code != 255) return ApplyStyle(Detail::TextProperties::TextStyle::Intensity{code}); - code = (std::uint8_t)BufferUtilsManip(format).GetWordFromDictPairs(styleItalic); + code = (std::uint8_t)SF_TRY(BufferUtilsManip(format).GetWordFromDictPairs(styleItalic)); if (code != 255) return ApplyStyle(Detail::TextProperties::TextStyle::Italic{code}); - code = (std::uint8_t)BufferUtilsManip(format).GetWordFromDictPairs(styleBlink); + code = (std::uint8_t)SF_TRY(BufferUtilsManip(format).GetWordFromDictPairs(styleBlink)); if (code != 255) return ApplyStyle(Detail::TextProperties::TextStyle::Blink{code}); - code = (std::uint8_t)BufferUtilsManip(format).GetWordFromDictPairs(styleInverted); + code = (std::uint8_t)SF_TRY(BufferUtilsManip(format).GetWordFromDictPairs(styleInverted)); if (code != 255) return ApplyStyle(Detail::TextProperties::TextStyle::Inverted{code}); - code = (std::uint8_t)BufferUtilsManip(format).GetWordFromDictPairs(styleIdeogram); + code = (std::uint8_t)SF_TRY(BufferUtilsManip(format).GetWordFromDictPairs(styleIdeogram)); if (code != 255) return ApplyStyle(Detail::TextProperties::TextStyle::Ideogram{code}); - code = (std::uint8_t)BufferUtilsManip(format).GetWordFromDictPairs(styleScript); + code = (std::uint8_t)SF_TRY(BufferUtilsManip(format).GetWordFromDictPairs(styleScript)); if (code != 255) return ApplyStyle(Detail::TextProperties::TextStyle::Script{code}); - code = (std::uint8_t)BufferUtilsManip(format).GetWordFromDictPairs(styleUnderline); + code = (std::uint8_t)SF_TRY(BufferUtilsManip(format).GetWordFromDictPairs(styleUnderline)); if (code != 255) { if (code == (std::uint8_t)Detail::TextProperties::TextStyle::Underline::SelectUnderlinedColor) { - Detail::TextProperties::TextStyle::UnderlineColor::ColorCube underlineColor = SelectUnderlinedColorStyle(format); + Detail::TextProperties::TextStyle::UnderlineColor::ColorCube underlineColor = SF_TRY(SelectUnderlinedColorStyle(format)); return ApplyStyle(underlineColor); } return ApplyStyle(Detail::TextProperties::TextStyle::Underline{code}); } + return {}; } template - std::expected TextPropertiesManager::SelectUnderlinedColorStyle(BufferInfoView& format) + [[nodiscard]] std::expected TextPropertiesManager::SelectUnderlinedColorStyle(BufferInfoView& format) { // TODO // FIXME @@ -216,11 +219,11 @@ namespace StreamFormat::FMT::Detail } template - std::expected Detail::TextPropertiesManager::ParseFront(Context::BasicContext& context) + [[nodiscard]] std::expected Detail::TextPropertiesManager::ParseFront(Context::BasicContext& context) { static constexpr std::string_view frontCode[] = {"default", "front0", "front1", "front2", "front3", "front4", "front5", "front6", "front7", "front8", "front9"}; - if (BufferTestManip(context.Format).IsEqualTo(':')) + if (BufferTestAccess(context.Format).IsEqualTo(':')) { SF_TRY(BufferManip(context.Format).Forward()); BufferTestManip(context.Format).SkipAllSpaces(); diff --git a/src/StreamFormat/FMT/Context/BasicContext/TextPropertiesManager.cpp b/src/StreamFormat/FMT/Context/BasicContext/TextPropertiesManager.cpp index 5e08461b..7442c0b1 100644 --- a/src/StreamFormat/FMT/Context/BasicContext/TextPropertiesManager.cpp +++ b/src/StreamFormat/FMT/Context/BasicContext/TextPropertiesManager.cpp @@ -2,7 +2,7 @@ namespace StreamFormat::FMT::Detail { - std::expected TextPropertiesApplyManager::ReloadColorFG(const TextProperties::TextColor::ColorFG& target) + [[nodiscard]] std::expected TextPropertiesApplyManager::ReloadColorFG(const TextProperties::TextColor::ColorFG& target) { if (target.Type != m_CurrentContextProperties.Color.Fg.Type) { @@ -37,7 +37,7 @@ namespace StreamFormat::FMT::Detail return {}; } - std::expected TextPropertiesApplyManager::ReloadColorBG(const TextProperties::TextColor::ColorBG& target) + [[nodiscard]] std::expected TextPropertiesApplyManager::ReloadColorBG(const TextProperties::TextColor::ColorBG& target) { if (target.Type != m_CurrentContextProperties.Color.Bg.Type) { @@ -72,7 +72,7 @@ namespace StreamFormat::FMT::Detail return {}; } - std::expected TextPropertiesApplyManager::ReloadStyle(const TextProperties::TextStyle::Style& target) + [[nodiscard]] std::expected TextPropertiesApplyManager::ReloadStyle(const TextProperties::TextStyle::Style& target) { if (target.Intensity != m_CurrentContextProperties.Style.Intensity) { @@ -107,7 +107,7 @@ namespace StreamFormat::FMT::Detail if (target.Underline != m_CurrentContextProperties.Style.Underline) { - ApplyStyle(target.Underline); + SF_TRY(ApplyStyle(target.Underline)); m_CurrentContextProperties.Style.Underline = target.Underline; } @@ -154,7 +154,7 @@ namespace StreamFormat::FMT::Detail return {}; } - std::expected TextPropertiesApplyManager::ReloadFront(const TextProperties::TextFront::Front& target) + [[nodiscard]] std::expected TextPropertiesApplyManager::ReloadFront(const TextProperties::TextFront::Front& target) { if (m_CurrentContextProperties.Front == target) return {}; diff --git a/src/StreamFormat/FMT/Context/BasicContext/TextPropertiesManager.h b/src/StreamFormat/FMT/Context/BasicContext/TextPropertiesManager.h index 437b87b8..06b15c99 100644 --- a/src/StreamFormat/FMT/Context/BasicContext/TextPropertiesManager.h +++ b/src/StreamFormat/FMT/Context/BasicContext/TextPropertiesManager.h @@ -17,48 +17,48 @@ namespace StreamFormat::FMT::Detail , m_CurrentContextProperties{} {} - std::expected Terminate() { return ReloadDefault(); } + [[nodiscard]] std::expected Terminate() { return ReloadDefault(); } public: template requires Detail::TextPropertiesColorCanApply - std::expected ApplyColor(const T& modif) + [[nodiscard]] std::expected ApplyColor(const T& modif) { m_CurrentContextProperties.Color.Apply(modif); return m_TextPropertiesExecutor.ExecuteColor(modif); } template requires Detail::TextPropertiesStyleCanApply - std::expected ApplyStyle(const T& modif) + [[nodiscard]] std::expected ApplyStyle(const T& modif) { m_CurrentContextProperties.Style.Apply(modif); return m_TextPropertiesExecutor.ExecuteStyle(modif); } template requires Detail::TextPropertiesFrontCanApply - std::expected ApplyFront(const T& modif) + [[nodiscard]] std::expected ApplyFront(const T& modif) { m_CurrentContextProperties.Front.Apply(modif); return m_TextPropertiesExecutor.ExecuteFront(modif); } - std::expected AllPropertiesReset() + [[nodiscard]] std::expected AllPropertiesReset() { SF_TRY(ApplyColorReset()); SF_TRY(ApplyStyleReset()); return ApplyFrontReset(); } - std::expected ApplyColorReset() + [[nodiscard]] std::expected ApplyColorReset() { m_CurrentContextProperties.Color.ModifyReset(); return m_TextPropertiesExecutor.ResetColor(); } - std::expected ApplyStyleReset() + [[nodiscard]] std::expected ApplyStyleReset() { m_CurrentContextProperties.Style.ModifyReset(); return m_TextPropertiesExecutor.ResetStyle(); } - std::expected ApplyFrontReset() + [[nodiscard]] std::expected ApplyFrontReset() { m_CurrentContextProperties.Front.ModifyReset(); return m_TextPropertiesExecutor.ResetFront(); @@ -68,38 +68,38 @@ namespace StreamFormat::FMT::Detail Detail::TextProperties::Properties Save() { return m_CurrentContextProperties; } public: - std::expected ReloadDefault() + [[nodiscard]] std::expected ReloadDefault() { - ReloadDefaultColor(); - ReloadDefaultStyle(); - ReloadDefaultFront(); + SF_TRY(ReloadDefaultColor()); + SF_TRY(ReloadDefaultStyle()); + return ReloadDefaultFront(); } - std::expected ReloadDefaultColor() + [[nodiscard]] std::expected ReloadDefaultColor() { - ReloadDefaultColorFG(); - ReloadDefaultColorBG(); + SF_TRY(ReloadDefaultColorFG()); + return ReloadDefaultColorBG(); } - std::expected ReloadDefaultColorFG() { ReloadColorFG(Detail::TextProperties::TextColor::ColorFG{}); } - std::expected ReloadDefaultColorBG() { ReloadColorBG(Detail::TextProperties::TextColor::ColorBG{}); } - std::expected ReloadDefaultStyle() { ReloadStyle(Detail::TextProperties::TextStyle::Style{}); } - std::expected ReloadDefaultFront() { ReloadFront(Detail::TextProperties::TextFront::Front{}); } + [[nodiscard]] std::expected ReloadDefaultColorFG() { return ReloadColorFG(Detail::TextProperties::TextColor::ColorFG{}); } + [[nodiscard]] std::expected ReloadDefaultColorBG() { return ReloadColorBG(Detail::TextProperties::TextColor::ColorBG{}); } + [[nodiscard]] std::expected ReloadDefaultStyle() { return ReloadStyle(Detail::TextProperties::TextStyle::Style{}); } + [[nodiscard]] std::expected ReloadDefaultFront() { return ReloadFront(Detail::TextProperties::TextFront::Front{}); } - std::expected Reload(const Detail::TextProperties::Properties& target) + [[nodiscard]] std::expected Reload(const Detail::TextProperties::Properties& target) { - ReloadColor(target.Color); - ReloadStyle(target.Style); - ReloadFront(target.Front); + SF_TRY(ReloadColor(target.Color)); + SF_TRY(ReloadStyle(target.Style)); + return ReloadFront(target.Front); } - std::expected ReloadColor(const Detail::TextProperties::TextColor::Color& target) + [[nodiscard]] std::expected ReloadColor(const Detail::TextProperties::TextColor::Color& target) { - ReloadColorFG(target.Fg); - ReloadColorBG(target.Bg); + SF_TRY(ReloadColorFG(target.Fg)); + return ReloadColorBG(target.Bg); } - std::expected ReloadColorFG(const Detail::TextProperties::TextColor::ColorFG& target); - std::expected ReloadColorBG(const Detail::TextProperties::TextColor::ColorBG& target); - std::expected ReloadStyle(const Detail::TextProperties::TextStyle::Style& target); - std::expected ReloadFront(const Detail::TextProperties::TextFront::Front& target); + [[nodiscard]] std::expected ReloadColorFG(const Detail::TextProperties::TextColor::ColorFG& target); + [[nodiscard]] std::expected ReloadColorBG(const Detail::TextProperties::TextColor::ColorBG& target); + [[nodiscard]] std::expected ReloadStyle(const Detail::TextProperties::TextStyle::Style& target); + [[nodiscard]] std::expected ReloadFront(const Detail::TextProperties::TextFront::Front& target); public: ITextPropertiesExecutor& GetTextPropertiesExecutor() { return m_TextPropertiesExecutor; } @@ -112,56 +112,64 @@ namespace StreamFormat::FMT::Detail public: template requires Detail::TextPropertiesColorCanApply - inline std::expected AskApplyColor(const T& modif) + [[nodiscard]] inline std::expected AskApplyColor(const T& modif) { - if (m_CurrentContextProperties.Color.NeedModif(modif)) ApplyColor(modif); + if (m_CurrentContextProperties.Color.NeedModif(modif)) + return ApplyColor(modif); } template requires Detail::TextPropertiesStyleCanApply - inline std::expected AskApplyStyle(const T& modif) + [[nodiscard]] inline std::expected AskApplyStyle(const T& modif) { - if (m_CurrentContextProperties.Style.NeedModif(modif)) ApplyStyle(modif); + if (m_CurrentContextProperties.Style.NeedModif(modif)) + return ApplyStyle(modif); } template requires Detail::TextPropertiesFrontCanApply - inline std::expected AskApplyFront(const T& modif) + [[nodiscard]] inline std::expected AskApplyFront(const T& modif) { - if (m_CurrentContextProperties.Front.NeedModif(modif)) ApplyFront(modif); + if (m_CurrentContextProperties.Front.NeedModif(modif)) + return ApplyFront(modif); } - std::expected AskApplyColor(const Detail::TextProperties::TextColor::BasicColor& modif) + [[nodiscard]] std::expected AskApplyColor(const Detail::TextProperties::TextColor::BasicColor& modif) { if (m_CurrentContextProperties.Color.NeedModif(modif.Fg)) { - if (m_CurrentContextProperties.Color.NeedModif(modif.Bg)) ApplyColor(modif); + if (m_CurrentContextProperties.Color.NeedModif(modif.Bg)) + return ApplyColor(modif); return ApplyColor(modif.Fg); } - if (m_CurrentContextProperties.Color.NeedModif(modif.Fg)) return ApplyColor(modif.Bg); + if (m_CurrentContextProperties.Color.NeedModif(modif.Fg)) + return ApplyColor(modif.Bg); } - std::expected AskApplyColor(const Detail::TextProperties::TextColor::ColorCube& modif) + [[nodiscard]] std::expected AskApplyColor(const Detail::TextProperties::TextColor::ColorCube& modif) { if (m_CurrentContextProperties.Color.NeedModif(modif.Fg)) { - if (m_CurrentContextProperties.Color.NeedModif(modif)) return ApplyColor(modif); + if (m_CurrentContextProperties.Color.NeedModif(modif)) + return ApplyColor(modif); return ApplyColor(modif.Fg); } - if (m_CurrentContextProperties.Color.NeedModif(modif.Fg)) return ApplyColor(modif.Bg); + if (m_CurrentContextProperties.Color.NeedModif(modif.Fg)) + return ApplyColor(modif.Bg); } - std::expected AskApplyColor(const Detail::TextProperties::TextColor::Color24b& modif) + [[nodiscard]] std::expected AskApplyColor(const Detail::TextProperties::TextColor::Color24b& modif) { if (m_CurrentContextProperties.Color.NeedModif(modif.Fg)) { - if (m_CurrentContextProperties.Color.NeedModif(modif)) return ApplyColor(modif); + if (m_CurrentContextProperties.Color.NeedModif(modif)) + return ApplyColor(modif); return ApplyColor(modif.Fg); } if (m_CurrentContextProperties.Color.NeedModif(modif.Fg)) return ApplyColor(modif.Bg); } - std::expected AskApplyColor(const Detail::TextProperties::TextColor::ColorFG& modif) { ReloadColorFG(modif); } - std::expected AskApplyColor(const Detail::TextProperties::TextColor::ColorBG& modif) { ReloadColorBG(modif); } - std::expected AskApplyColor(const Detail::TextProperties::TextColor::Color& modif) { ReloadColor(modif); } + [[nodiscard]] std::expected AskApplyColor(const Detail::TextProperties::TextColor::ColorFG& modif) { return ReloadColorFG(modif); } + [[nodiscard]] std::expected AskApplyColor(const Detail::TextProperties::TextColor::ColorBG& modif) { return ReloadColorBG(modif); } + [[nodiscard]] std::expected AskApplyColor(const Detail::TextProperties::TextColor::Color& modif) { return ReloadColor(modif); } }; template @@ -173,20 +181,20 @@ namespace StreamFormat::FMT::Detail {} public: - std::expected ApplyColorOnIndex(Context::BasicContext& context, std::int32_t index); - std::expected ApplyStyleOnIndex(Context::BasicContext& context, std::int32_t index); - std::expected ApplyFrontOnIndex(Context::BasicContext& context, std::int32_t index); + [[nodiscard]] std::expected ApplyColorOnIndex(Context::BasicContext& context, std::int32_t index); + [[nodiscard]] std::expected ApplyStyleOnIndex(Context::BasicContext& context, std::int32_t index); + [[nodiscard]] std::expected ApplyFrontOnIndex(Context::BasicContext& context, std::int32_t index); public: - std::expected ParseColor(Context::BasicContext& context); - std::expected ParseStyle(Context::BasicContext& context); - std::expected ParseFront(Context::BasicContext& context); + [[nodiscard]] std::expected ParseColor(Context::BasicContext& context); + [[nodiscard]] std::expected ParseStyle(Context::BasicContext& context); + [[nodiscard]] std::expected ParseFront(Context::BasicContext& context); private: template - std::expected GetColorCode(BufferInfoView& format, T& t); - std::expected ParseStyleNamed(BufferInfoView& format); - std::expected SelectUnderlinedColorStyle(BufferInfoView& format); + [[nodiscard]] std::expected GetColorCode(BufferInfoView& format); + [[nodiscard]] std::expected ParseStyleNamed(BufferInfoView& format); + [[nodiscard]] std::expected SelectUnderlinedColorStyle(BufferInfoView& format); }; } @@ -194,15 +202,14 @@ namespace StreamFormat::FMT::Detail { template template - std::expected Detail::TextPropertiesManager::GetColorCode(BufferInfoView& format) + [[nodiscard]] std::expected Detail::TextPropertiesManager::GetColorCode(BufferInfoView& format) { static constexpr std::string_view colorCode[] = {"black", "red", "green", "yellow", "blue", "magenta", "cyan", "white", " ", "default"}; bool bright = SF_TRY(BufferTestManip(format).IsEqualToForward('+')); std::uint8_t step = static_cast(bright ? T::BaseBStep : T::BaseStep); std::uint8_t code = (std::uint8_t)SF_TRY(BufferUtilsManip(format).GetWordFromList(colorCode));; - t = static_cast(code + step); - return true; + return static_cast(code + step); } } diff --git a/src/StreamFormat/FMT/Context/FormatterExecutor/BasicFormatterExecutor.h b/src/StreamFormat/FMT/Context/FormatterExecutor/BasicFormatterExecutor.h index 9ec10e73..3835e65c 100644 --- a/src/StreamFormat/FMT/Context/FormatterExecutor/BasicFormatterExecutor.h +++ b/src/StreamFormat/FMT/Context/FormatterExecutor/BasicFormatterExecutor.h @@ -26,7 +26,7 @@ namespace StreamFormat::FMT::Context BasicFormatterExecutor(Detail::FMTBufferOutInfo& bufferOut, Detail::ITextPropertiesExecutor& textPropertiesExecutor); ~BasicFormatterExecutor() override = default; - std::expected Terminate(); + [[nodiscard]] std::expected Terminate(); public: Detail::FMTBufferOutInfo& BufferOut; @@ -39,17 +39,17 @@ namespace StreamFormat::FMT::Context { return Detail::BufferWriteManip(BufferOut).FastWriteString(sv); } - std::expected ExecSettings() override; + [[nodiscard]] std::expected ExecSettings() override; public: template - std::expected Run_(Detail::BufferInfoView format, Args&&... args); + [[nodiscard]] std::expected Run_(Detail::BufferInfoView format, Args&&... args); template - std::expected Run(Format&& format, Args&&... args); + [[nodiscard]] std::expected Run(Format&& format, Args&&... args); public: template - inline std::expected WriteType(Type&& type, Rest&&... rest) + [[nodiscard]] inline std::expected WriteType(Type&& type, Rest&&... rest) { FormatterType>::Type, M_Type>::Format(std::forward(type), *this); if constexpr (sizeof...(rest) > 0) @@ -69,7 +69,7 @@ namespace StreamFormat::FMT::Context } template - std::expected BasicFormatterExecutor::Terminate() + [[nodiscard]] std::expected BasicFormatterExecutor::Terminate() { Detail::BufferOutManip(BufferOut).ComputeGeneratedSize(); @@ -79,7 +79,7 @@ namespace StreamFormat::FMT::Context } template - std::expected BasicFormatterExecutor::ExecSettings() + [[nodiscard]] std::expected BasicFormatterExecutor::ExecSettings() { // Indent auto indent = Data.Specifiers.Get("indent"); @@ -89,7 +89,7 @@ namespace StreamFormat::FMT::Context template template - std::expected BasicFormatterExecutor::Run_(Detail::BufferInfoView format, Args&&... args) + [[nodiscard]] std::expected BasicFormatterExecutor::Run_(Detail::BufferInfoView format, Args&&... args) { auto argsInterface = Detail::FormatterArgsInterface, Args...>(*this, std::forward(args)...); @@ -101,7 +101,7 @@ namespace StreamFormat::FMT::Context template template - std::expected BasicFormatterExecutor::Run(Format&& formatInput, Args&&... args) + [[nodiscard]] std::expected BasicFormatterExecutor::Run(Format&& formatInput, Args&&... args) { Run_(Detail::BufferInfoView{formatInput}, std::forward(args)...); } diff --git a/src/StreamFormat/FMT/Context/FormatterExecutor/FormatBasics-impl.h b/src/StreamFormat/FMT/Context/FormatterExecutor/FormatBasics-impl.h index 2662a18c..2a379fd6 100644 --- a/src/StreamFormat/FMT/Context/FormatterExecutor/FormatBasics-impl.h +++ b/src/StreamFormat/FMT/Context/FormatterExecutor/FormatBasics-impl.h @@ -38,10 +38,7 @@ namespace StreamFormat::FMT std::size_t size = executor.Data.Specifiers.GetAsNumber("size", totalsize - beginIdx); if (size == std::numeric_limits::max()) - { - Detail::BufferWriteManip(executor.BufferOut).FastWriteString(""); - return; - } + { return std::unexpected(FMTResult::GivenArgs_UnableToDeduceSize); } Detail::BufferWriteManip(executor.BufferOut).FastWriteString(executor.Data.Specifiers.GetAsText("begin", STDEnumerableUtility::DefaultBegin)); @@ -72,7 +69,7 @@ namespace StreamFormat::FMT if (executor.Data.Specifiers.Has("array")) return FormatObjectArray(buffer, size, executor); - if (beginIdx > size) return; + if (beginIdx > size) return {}; const T* begin = buffer + beginIdx; // TODO: current indent ignore shift diff --git a/src/StreamFormat/FMT/Context/FormatterExecutor/FormatterArgs.h b/src/StreamFormat/FMT/Context/FormatterExecutor/FormatterArgs.h index eff94688..a3ebe5e8 100644 --- a/src/StreamFormat/FMT/Context/FormatterExecutor/FormatterArgs.h +++ b/src/StreamFormat/FMT/Context/FormatterExecutor/FormatterArgs.h @@ -26,8 +26,8 @@ namespace StreamFormat::FMT::Detail { return std::unexpected(FMTResult::ArgsInterface_Unavaible); } - template - [[nodiscard]] inline std::expected GetIndexOfCurrentNamedArg(FormatterExecutor&, std::int32_t) + template + [[nodiscard]] inline std::expected GetIndexOfCurrentNamedArg(BufferInfoView&, std::int32_t) { return std::unexpected(FMTResult::ArgsInterface_Unavaible); } @@ -36,7 +36,7 @@ namespace StreamFormat::FMT::Detail return std::unexpected(FMTResult::ArgsInterface_Unavaible); } template - [[nodiscard]] inline std::expected GetConvertedTypeAt(T*, std::int32_t) + [[nodiscard]] inline std::expected GetConvertedTypeAt(std::int32_t) { return std::unexpected(FMTResult::ArgsInterface_Unavaible); } @@ -77,16 +77,15 @@ namespace StreamFormat::FMT::Detail { if constexpr (Detail::IsANamedArgs>::value) { - std::expected currentNamedArg = Detail::FMTBufferParamsManip(format).NextIsNamedArgs(m_Value.GetName()); - if (not currentNamedArg) - { return std::unexpected(FMTResult::BufferManipError); } - return beginSearchIndex; + bool currentIsANamedArg = SF_TRY(Detail::FMTBufferParamsManip(format).NextIsNamedArgs(m_Value.GetName())); + if (currentIsANamedArg) + return beginSearchIndex; } return FormatterArgs::GetIndexOfCurrentNamedArg(format, beginSearchIndex + 1); } public: - inline PointerID GetPointerIDAt(std::int32_t idx) + [[nodiscard]] inline std::expected GetPointerIDAt(std::int32_t idx) { if (idx == 0) return PointerID{.TypeInfo = typeid(const TypeWithoutRef), .Ptr = const_cast(static_cast(&m_Value))}; @@ -104,7 +103,7 @@ namespace StreamFormat::FMT::Detail else { return std::unexpected(FMTResult::ArgsInterface_InvalidConversion); } } - return FormatterArgs::template GetConvertedTypeAt(value, idx - 1); + return FormatterArgs::template GetConvertedTypeAt(idx - 1); } }; @@ -137,7 +136,7 @@ namespace StreamFormat::FMT::Detail { return ArgsInterface.GetIndexOfCurrentNamedArg(format, std::int32_t{0}); } - PointerID GetPointerIDAt(std::int32_t idx) override + [[nodiscard]] std::expected GetPointerIDAt(std::int32_t idx) override { return ArgsInterface.GetPointerIDAt(idx); } diff --git a/src/StreamFormat/FMT/Context/FormatterExecutor/FormatterTextPropertiesExecutor/FormatterANSITextPropertiesExecutor.h b/src/StreamFormat/FMT/Context/FormatterExecutor/FormatterTextPropertiesExecutor/FormatterANSITextPropertiesExecutor.h index 283ceec4..eabfe8ff 100644 --- a/src/StreamFormat/FMT/Context/FormatterExecutor/FormatterTextPropertiesExecutor/FormatterANSITextPropertiesExecutor.h +++ b/src/StreamFormat/FMT/Context/FormatterExecutor/FormatterTextPropertiesExecutor/FormatterANSITextPropertiesExecutor.h @@ -1,6 +1,7 @@ #pragma once #include "FormatterTextPropertiesExecutor.h" +#include "StreamFormat/FMT/Detail/IndentHandlers.h" namespace StreamFormat::FMT::Detail { diff --git a/src/StreamFormat/FMT/Context/FormatterExecutor/FormatterType.h b/src/StreamFormat/FMT/Context/FormatterExecutor/FormatterType.h index fb5af4ac..201d6b30 100644 --- a/src/StreamFormat/FMT/Context/FormatterExecutor/FormatterType.h +++ b/src/StreamFormat/FMT/Context/FormatterExecutor/FormatterType.h @@ -5,11 +5,6 @@ #define STREAMFORMAT_FORMATTER_DECLARED namespace StreamFormat::FMT { - enum class FMTResult - { - BufferManip, - }; - template struct FormatterType { diff --git a/src/StreamFormat/FMT/Context/FormatterExecutor/UtilityFunctions.h b/src/StreamFormat/FMT/Context/FormatterExecutor/UtilityFunctions.h index 23c675b1..52c843be 100644 --- a/src/StreamFormat/FMT/Context/FormatterExecutor/UtilityFunctions.h +++ b/src/StreamFormat/FMT/Context/FormatterExecutor/UtilityFunctions.h @@ -17,7 +17,7 @@ namespace StreamFormat::FMT { template requires(IsCharType::Value) - std::expected FormatInManager( + [[nodiscard]] std::expected FormatInManager( Detail::BasicBufferOutManager& bufferOutManager, bool newline, BufferInfoView format, @@ -29,48 +29,48 @@ namespace StreamFormat::FMT Detail::FormatterANSITextPropertiesExecutor textPropertiesExecutor; Detail::FMTBufferOutInfo bufferOut{bufferOutManager}; Context::BasicFormatterExecutor executor(bufferOut, textPropertiesExecutor); - executor.Run(format, std::forward(args)...); - if (newline) BufferOutManip(bufferOut).Pushback('\n'); - executor.Terminate(); + executor.Run(format, std::forward(args)...).value(); + if (newline) BufferOutManip(bufferOut).Pushback('\n').value(); + executor.Terminate().value(); } template requires(IsCharType::Value) - std::expected FormatInManager(Detail::BasicBufferOutManager& bufferOutManager, bool newline, T&& t) + [[nodiscard]] std::expected FormatInManager(Detail::BasicBufferOutManager& bufferOutManager, bool newline, T&& t) { using TCharResolved = std::remove_const_t; Detail::FormatterANSITextPropertiesExecutor textPropertiesExecutor; Detail::FMTBufferOutInfo bufferOut{bufferOutManager}; Context::BasicFormatterExecutor executor(bufferOut, textPropertiesExecutor); - executor.WriteType(std::forward(t)); - if (newline) BufferOutManip(bufferOut).Pushback('\n'); - executor.Terminate(); + executor.WriteType(std::forward(t)).value(); + if (newline) BufferOutManip(bufferOut).Pushback('\n').value(); + executor.Terminate().value(); } } template requires(Detail::IsCharType::Value && Detail::ConvertibleToBufferInfoView) - std::expected FormatInChar(TChar (&buffer)[BUFFER_SIZE], Format&& formatInput, Args&&... args) + [[nodiscard]] std::expected FormatInChar(TChar (&buffer)[BUFFER_SIZE], Format&& formatInput, Args&&... args) { Detail::GivenBufferOutManager bufferOutManager(buffer); - Detail::FormatInManager(bufferOutManager, false, Detail::BufferInfoView{formatInput}, std::forward(args)...); + Detail::FormatInManager(bufferOutManager, false, Detail::BufferInfoView{formatInput}, std::forward(args)...).value(); } template requires(Detail::IsCharType::Value && Detail::ConvertibleToBufferInfoView) - std::expected FormatInChar(TChar* const buffer, const std::size_t bufferSize, Format&& formatInput, Args&&... args) + [[nodiscard]] std::expected FormatInChar(TChar* const buffer, const std::size_t bufferSize, Format&& formatInput, Args&&... args) { Detail::GivenBufferOutManager bufferOutManager(buffer, bufferSize); - Detail::FormatInManager(bufferOutManager, false, Detail::BufferInfoView{formatInput}, std::forward(args)...); + Detail::FormatInManager(bufferOutManager, false, Detail::BufferInfoView{formatInput}, std::forward(args)...).value(); } template requires(Detail::IsCharType::Value && Detail::ConvertibleToBufferInfoView) - std::expected CFilePrint(FILE* stream, Format&& formatInput, Args&&... args) + [[nodiscard]] std::expected CFilePrint(FILE* stream, Format&& formatInput, Args&&... args) { Detail::DynamicBufferOutManager bufferOutManager(256); - Detail::FormatInManager(bufferOutManager, false, Detail::BufferInfoView{formatInput}, std::forward(args)...); + Detail::FormatInManager(bufferOutManager, false, Detail::BufferInfoView{formatInput}, std::forward(args)...).value(); std::fwrite(bufferOutManager.GetBuffer(), bufferOutManager.GetLastGeneratedDataSize(), 1, stream); std::fflush(stream); @@ -78,10 +78,10 @@ namespace StreamFormat::FMT template requires(Detail::IsCharType::Value && Detail::ConvertibleToBufferInfoView) - std::expected CFilePrintLn(FILE* stream, Format&& formatInput, Args&&... args) + [[nodiscard]] std::expected CFilePrintLn(FILE* stream, Format&& formatInput, Args&&... args) { Detail::DynamicBufferOutManager bufferOutManager(256); - Detail::FormatInManager(bufferOutManager, true, Detail::BufferInfoView{formatInput}, std::forward(args)...); + Detail::FormatInManager(bufferOutManager, true, Detail::BufferInfoView{formatInput}, std::forward(args)...).value(); std::fwrite(bufferOutManager.GetBuffer(), bufferOutManager.GetLastGeneratedDataSize(), 1, stream); std::fflush(stream); @@ -89,10 +89,10 @@ namespace StreamFormat::FMT template requires(Detail::IsCharType::Value && Detail::ConvertibleToBufferInfoView) - std::expected FilePrint(std::basic_ostream& stream, Format&& formatInput, Args&&... args) + [[nodiscard]] std::expected FilePrint(std::basic_ostream& stream, Format&& formatInput, Args&&... args) { Detail::DynamicBufferOutManager bufferOutManager(256); - Detail::FormatInManager(bufferOutManager, false, Detail::BufferInfoView{formatInput}, std::forward(args)...); + Detail::FormatInManager(bufferOutManager, false, Detail::BufferInfoView{formatInput}, std::forward(args)...).value(); stream.write(bufferOutManager.GetBuffer(), bufferOutManager.GetLastGeneratedDataSize()); stream.flush(); @@ -100,10 +100,10 @@ namespace StreamFormat::FMT template requires(Detail::IsCharType::Value && Detail::ConvertibleToBufferInfoView) - std::expected FilePrintLn(std::basic_ostream& stream, Format&& formatInput, Args&&... args) + [[nodiscard]] std::expected FilePrintLn(std::basic_ostream& stream, Format&& formatInput, Args&&... args) { Detail::DynamicBufferOutManager bufferOutManager(256); - Detail::FormatInManager(bufferOutManager, true, Detail::BufferInfoView{formatInput}, std::forward(args)...); + Detail::FormatInManager(bufferOutManager, true, Detail::BufferInfoView{formatInput}, std::forward(args)...).value(); stream.write(bufferOutManager.GetBuffer(), bufferOutManager.GetLastGeneratedDataSize()); stream.flush(); @@ -111,19 +111,19 @@ namespace StreamFormat::FMT template requires(Detail::IsCharType::Value && Detail::ConvertibleToBufferInfoView) - std::expected FormatInString(std::basic_string& str, Format&& formatInput, Args&&... args) + [[nodiscard]] std::expected FormatInString(std::basic_string& str, Format&& formatInput, Args&&... args) { Detail::DynamicBufferOutManager bufferOutManager(256); - Detail::FormatInManager(bufferOutManager, false, Detail::BufferInfoView{formatInput}, std::forward(args)...); + Detail::FormatInManager(bufferOutManager, false, Detail::BufferInfoView{formatInput}, std::forward(args)...).value(); str = bufferOutManager.GetLastGeneratedString(); } template requires(Detail::IsCharType::Value && Detail::ConvertibleToBufferInfoView) - inline std::expected, FMTResult> FormatString(Format&& formatInput, Args&&... args) + [[nodiscard]] inline std::expected, FMTResult> FormatString(Format&& formatInput, Args&&... args) { Detail::DynamicBufferOutManager bufferOutManager(256); - Detail::FormatInManager(bufferOutManager, false, Detail::BufferInfoView{formatInput}, std::forward(args)...); + Detail::FormatInManager(bufferOutManager, false, Detail::BufferInfoView{formatInput}, std::forward(args)...).value(); return bufferOutManager.GetLastGeneratedString(); } @@ -131,7 +131,7 @@ namespace StreamFormat::FMT template requires(Detail::IsCharType::Value) - std::expected FormatInChar(TChar (&buffer)[BUFFER_SIZE], T&& t) + [[nodiscard]] std::expected FormatInChar(TChar (&buffer)[BUFFER_SIZE], T&& t) { Detail::GivenBufferOutManager bufferOutManager(buffer, BUFFER_SIZE); Detail::FormatInManager(bufferOutManager, false, std::forward(t)); @@ -139,7 +139,7 @@ namespace StreamFormat::FMT template requires(Detail::IsCharType::Value) - std::expected FormatInChar(TChar* const buffer, const std::size_t bufferSize, T&& t) + [[nodiscard]] std::expected FormatInChar(TChar* const buffer, const std::size_t bufferSize, T&& t) { Detail::GivenBufferOutManager bufferOutManager(buffer, bufferSize); Detail::FormatInManager(bufferOutManager, false, std::forward(t)); @@ -147,10 +147,10 @@ namespace StreamFormat::FMT template requires(Detail::IsCharType::Value) - std::expected CFilePrint(FILE* stream, T&& t) + [[nodiscard]] std::expected CFilePrint(FILE* stream, T&& t) { Detail::DynamicBufferOutManager bufferOutManager(32); - Detail::FormatInManager(bufferOutManager, false, std::forward(t)); + Detail::FormatInManager(bufferOutManager, false, std::forward(t)).value(); std::fwrite(bufferOutManager.GetBuffer(), static_cast(bufferOutManager.GetLastGeneratedDataSize()), 1, stream); std::fflush(stream); @@ -158,10 +158,10 @@ namespace StreamFormat::FMT template requires(Detail::IsCharType::Value) - std::expected CFilePrintLn(FILE* stream, T&& t) + [[nodiscard]] std::expected CFilePrintLn(FILE* stream, T&& t) { Detail::DynamicBufferOutManager bufferOutManager(32); - Detail::FormatInManager(bufferOutManager, true, std::forward(t)); + Detail::FormatInManager(bufferOutManager, true, std::forward(t)).value(); std::fwrite(bufferOutManager.GetBuffer(), static_cast(bufferOutManager.GetLastGeneratedDataSize()), 1, stream); std::fflush(stream); @@ -169,10 +169,10 @@ namespace StreamFormat::FMT template requires(Detail::IsCharType::Value) - std::expected FilePrint(std::basic_ostream& stream, T&& t) + [[nodiscard]] std::expected FilePrint(std::basic_ostream& stream, T&& t) { Detail::DynamicBufferOutManager bufferOutManager(32); - Detail::FormatInManager(bufferOutManager, false, std::forward(t)); + Detail::FormatInManager(bufferOutManager, false, std::forward(t)).value(); stream.write(bufferOutManager.GetBuffer(), static_cast(bufferOutManager.GetLastGeneratedDataSize())); stream.flush(); @@ -180,10 +180,10 @@ namespace StreamFormat::FMT template requires(Detail::IsCharType::Value) - std::expected FilePrintLn(std::basic_ostream& stream, T&& t) + [[nodiscard]] std::expected FilePrintLn(std::basic_ostream& stream, T&& t) { Detail::DynamicBufferOutManager bufferOutManager(32); - Detail::FormatInManager(bufferOutManager, true, std::forward(t)); + Detail::FormatInManager(bufferOutManager, true, std::forward(t)).value(); stream.write(bufferOutManager.GetBuffer(), static_cast(bufferOutManager.GetLastGeneratedDataSize())); stream.flush(); @@ -191,19 +191,19 @@ namespace StreamFormat::FMT template requires(Detail::IsCharType::Value) - std::expected FormatInString(std::basic_string& str, T&& t) + [[nodiscard]] std::expected FormatInString(std::basic_string& str, T&& t) { Detail::DynamicBufferOutManager bufferOutManager(32); - Detail::FormatInManager(bufferOutManager, false, std::forward(t)); + Detail::FormatInManager(bufferOutManager, false, std::forward(t)).value(); str = bufferOutManager.GetLastGeneratedString(); } template requires(Detail::IsCharType::Value) - inline std::expected, FMTResult> FormatString(T&& t) + [[nodiscard]] inline std::expected, FMTResult> FormatString(T&& t) { Detail::DynamicBufferOutManager bufferOutManager(32); - Detail::FormatInManager(bufferOutManager, false, std::forward(t)); + Detail::FormatInManager(bufferOutManager, false, std::forward(t)).value(); return bufferOutManager.GetLastGeneratedString(); } } diff --git a/src/StreamFormat/FMT/Context/ParserExecutor/BasicParserExecutor.h b/src/StreamFormat/FMT/Context/ParserExecutor/BasicParserExecutor.h index 0e3c09ba..d349ef88 100644 --- a/src/StreamFormat/FMT/Context/ParserExecutor/BasicParserExecutor.h +++ b/src/StreamFormat/FMT/Context/ParserExecutor/BasicParserExecutor.h @@ -37,7 +37,8 @@ namespace StreamFormat::FMT::Context protected: [[nodiscard]] std::expected ExecRawString(std::basic_string_view sv) override { - return Detail::BufferTestManip(BufferIn).IsSameForward(sv.data(), sv.size()); + SF_TRY(Detail::BufferTestManip(BufferIn).IsSameForward(sv.data(), sv.size())); + return {}; } [[nodiscard]] std::expected ExecSettings() override {}; diff --git a/src/StreamFormat/FMT/Context/ParserExecutor/ParseBasics-impl.h b/src/StreamFormat/FMT/Context/ParserExecutor/ParseBasics-impl.h index c3116638..3b03df0e 100644 --- a/src/StreamFormat/FMT/Context/ParserExecutor/ParseBasics-impl.h +++ b/src/StreamFormat/FMT/Context/ParserExecutor/ParseBasics-impl.h @@ -16,28 +16,43 @@ namespace StreamFormat::FMT template struct ParserType { - [[nodiscard]] static std::expected Parse(bool& t, ParserExecutor& executor) + [[nodiscard]] static std::expected Parse(bool& t, ParserExecutor& executor) { if (!executor.Data.PrefixSuffix) { - if (Detail::BufferTestManip(executor.BufferIn).IsEqualToForward('t', 'T')) + if (Detail::BufferTestManip(executor.BufferIn).IsEqualTo('t', 'T')) { - if (Detail::BufferTestManip(executor.BufferIn).IsSameForward("rue")) + SF_TRY(Detail::BufferManip(executor.BufferIn).Forward()); + if (Detail::BufferTestManip(executor.BufferIn).IsSame("rue")) + { + SF_TRY(Detail::BufferManip(executor.BufferIn).Forward()); t = true; + } } else if (Detail::BufferTestManip(executor.BufferIn).IsEqualToForward('f', 'F')) { + SF_TRY(Detail::BufferManip(executor.BufferIn).Forward()); if (Detail::BufferTestManip(executor.BufferIn).IsSameForward("alse")) + { + SF_TRY(Detail::BufferManip(executor.BufferIn).Forward()); t = false; + } } } else { - if (Detail::BufferTestManip(executor.BufferIn).IsEqualToForward('1')) - { t = true; return; } - else if (Detail::BufferTestManip(executor.BufferIn).IsEqualToForward('1')) - { t = false; return; } + if (Detail::BufferTestManip(executor.BufferIn).IsEqualTo('1')) + { + SF_TRY(Detail::BufferManip(executor.BufferIn).Forward()); + t = true; + } + else if (Detail::BufferTestManip(executor.BufferIn).IsEqualTo('0')) + { + SF_TRY(Detail::BufferManip(executor.BufferIn).Forward()); + t = false; + } } + return {}; } }; diff --git a/src/StreamFormat/FMT/Context/ParserExecutor/ParserArgs.h b/src/StreamFormat/FMT/Context/ParserExecutor/ParserArgs.h index 4401357a..6e1696ec 100644 --- a/src/StreamFormat/FMT/Context/ParserExecutor/ParserArgs.h +++ b/src/StreamFormat/FMT/Context/ParserExecutor/ParserArgs.h @@ -26,8 +26,8 @@ namespace StreamFormat::FMT::Detail { return std::unexpected(FMTResult::ArgsInterface_Unavaible); } - template - [[nodiscard]] inline std::expected GetIndexOfCurrentNamedArg(FormatterExecutor&, std::int32_t) + template + [[nodiscard]] inline std::expected GetIndexOfCurrentNamedArg(BufferInfoView& format, std::int32_t) { return std::unexpected(FMTResult::ArgsInterface_Unavaible); } @@ -36,7 +36,7 @@ namespace StreamFormat::FMT::Detail return std::unexpected(FMTResult::ArgsInterface_Unavaible); } template - [[nodiscard]] inline std::expected GetConvertedTypeAt(T*, std::int32_t) + [[nodiscard]] inline std::expected GetConvertedTypeAt(std::int32_t) { return std::unexpected(FMTResult::ArgsInterface_Unavaible); } @@ -77,16 +77,15 @@ namespace StreamFormat::FMT::Detail { if constexpr (Detail::IsANamedArgs>::value) { - std::expected currentNamedArg = Detail::FMTBufferParamsManip(format).NextIsNamedArgs(m_Value.GetName()); - if (not currentNamedArg) - { return std::unexpected(FMTResult::BufferManipError); } - return beginSearchIndex; + bool currentIsANamedArg = SF_TRY(Detail::FMTBufferParamsManip(format).NextIsNamedArgs(m_Value.GetName())); + if (currentIsANamedArg) + return beginSearchIndex; } - return FormatterArgs::GetIndexOfCurrentNamedArg(format, beginSearchIndex + 1); + return ParserArgs::GetIndexOfCurrentNamedArg(format, beginSearchIndex + 1); } public: - inline PointerID GetPointerIDAt(std::int32_t idx) + [[nodiscard]] inline std::expected GetPointerIDAt(std::int32_t idx) { if (idx == 0) return PointerID{.TypeInfo = typeid(TypeWithoutRef), .Ptr = static_cast(&m_Value)}; return ParserArgs::GetPointerIDAt(idx - 1); @@ -103,7 +102,7 @@ namespace StreamFormat::FMT::Detail else { return std::unexpected(FMTResult::ArgsInterface_InvalidConversion); } } - return ParserArgs::template GetConvertedTypeAt(value, idx - 1); + return ParserArgs::template GetConvertedTypeAt(idx - 1); } }; @@ -137,7 +136,7 @@ namespace StreamFormat::FMT::Detail { return ArgsInterface.GetIndexOfCurrentNamedArg(format, std::int32_t{0}); } - PointerID GetPointerIDAt(std::int32_t idx) override + [[nodiscard]] inline std::expected GetPointerIDAt(std::int32_t idx) override { return ArgsInterface.GetPointerIDAt(idx); } diff --git a/src/StreamFormat/FMT/Context/ParserExecutor/ParserTextPropertiesExecutor/ParserANSITextPropertiesExecutor.h b/src/StreamFormat/FMT/Context/ParserExecutor/ParserTextPropertiesExecutor/ParserANSITextPropertiesExecutor.h index cea69085..3f22e8f9 100644 --- a/src/StreamFormat/FMT/Context/ParserExecutor/ParserTextPropertiesExecutor/ParserANSITextPropertiesExecutor.h +++ b/src/StreamFormat/FMT/Context/ParserExecutor/ParserTextPropertiesExecutor/ParserANSITextPropertiesExecutor.h @@ -14,128 +14,128 @@ namespace StreamFormat::FMT::Detail using IParserTextPropertiesExecutor::Buffer; public: - std::expected AllPropertiesReset() override + [[nodiscard]] std::expected AllPropertiesReset() override { return std::unexpected(FMTResult::FunctionNotImpl); /*BufferReadManip(Buffer).BasicReadType('\033', '[', 0, 'm');*/ } public: - std::expected ResetColor() override + [[nodiscard]] std::expected ResetColor() override { return std::unexpected(FMTResult::FunctionNotImpl); /*BufferReadManip(Buffer).BasicReadType('\033', '[', 39, ';', 49, 'm');*/ } - std::expected ExecuteColor(const Detail::TextProperties::TextColor::BasicColorFG&) override + [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::BasicColorFG&) override { return std::unexpected(FMTResult::FunctionNotImpl); /*BufferReadManip(Buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ } - std::expected ExecuteColor(const Detail::TextProperties::TextColor::BasicColorBG&) override + [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::BasicColorBG&) override { return std::unexpected(FMTResult::FunctionNotImpl); /*BufferReadManip(Buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ } - std::expected ExecuteColor(const Detail::TextProperties::TextColor::BasicColor&) override + [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::BasicColor&) override { return std::unexpected(FMTResult::FunctionNotImpl); /*BufferReadManip(Buffer).BasicReadType('\033', '[', static_cast(t.Fg) , ';', static_cast(t.Bg), 'm');*/ } - std::expected ExecuteColor(const Detail::TextProperties::TextColor::Color24bFG&) override + [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::Color24bFG&) override { return std::unexpected(FMTResult::FunctionNotImpl); /*BufferReadManip(Buffer).BasicReadType("\033[38;2;", t.R, ';', t.G, ';', t.B, 'm');*/ } - std::expected ExecuteColor(const Detail::TextProperties::TextColor::Color24bBG&) override + [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::Color24bBG&) override { return std::unexpected(FMTResult::FunctionNotImpl); /*BufferReadManip(Buffer).BasicReadType("\033[48;2;", t.R, ';', t.G, ';', t.B, 'm');*/ } - std::expected ExecuteColor(const Detail::TextProperties::TextColor::Color24b&) override + [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::Color24b&) override { return std::unexpected(FMTResult::FunctionNotImpl); /*BufferReadManip(Buffer).BasicReadType("\033[38;2;", t.Fg.R, ';', t.Fg.G, ';', t.Fg.B, "; 48; 2;", t.Bg.R, ';', t.Bg.G, ';', t.Bg.B, 'm');*/ } - std::expected ExecuteColor(const Detail::TextProperties::TextColor::ColorCubeFG&) override + [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::ColorCubeFG&) override { return std::unexpected(FMTResult::FunctionNotImpl); /*BufferReadManip(Buffer).BasicReadType("\033[38;5;", t.GetColorRef(), 'm');*/ } - std::expected ExecuteColor(const Detail::TextProperties::TextColor::ColorCubeBG&) override + [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::ColorCubeBG&) override { return std::unexpected(FMTResult::FunctionNotImpl); /*BufferReadManip(Buffer).BasicReadType("\033[48;5;", t.GetColorRef(), 'm');*/ } - std::expected ExecuteColor(const Detail::TextProperties::TextColor::ColorCube&) override + [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::ColorCube&) override { return std::unexpected(FMTResult::FunctionNotImpl); /*BufferReadManip(Buffer).BasicReadType("\033[48;5;", t.Fg.GetColorRef(), ";48;5;", t.Bg.GetColorRef(), 'm');*/ } public: - std::expected ResetFront() override + [[nodiscard]] std::expected ResetFront() override { return std::unexpected(FMTResult::FunctionNotImpl); /*BufferReadManip(Buffer).BasicReadType('\033', '[', Detail::TextProperties::TextFront::FrontID::DefaultFrontID, 'm');*/ } - std::expected ExecuteFront(const Detail::TextProperties::TextFront::FrontID&) override + [[nodiscard]] std::expected ExecuteFront(const Detail::TextProperties::TextFront::FrontID&) override { return std::unexpected(FMTResult::FunctionNotImpl); /*BufferReadManip(Buffer).BasicReadType('\033', '[', t.ID, 'm');*/ } public: - std::expected ResetStyle() override + [[nodiscard]] std::expected ResetStyle() override { return std::unexpected(FMTResult::FunctionNotImpl); /*BufferReadManip(Buffer).BasicReadType('\033', '[', 0, 'm');*/ } - std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Intensity&) override + [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Intensity&) override { return std::unexpected(FMTResult::FunctionNotImpl); /*BufferReadManip(Buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ } - std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Italic&) override + [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Italic&) override { return std::unexpected(FMTResult::FunctionNotImpl); /*BufferReadManip(Buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ } - std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Underline&) override + [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Underline&) override { return std::unexpected(FMTResult::FunctionNotImpl); /*BufferReadManip(Buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ } - std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::UnderlineColor::Color&) override + [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::UnderlineColor::Color&) override { return std::unexpected(FMTResult::FunctionNotImpl); /*BufferReadManip(Buffer).BasicReadType("\033[59m");*/ } - std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::UnderlineColor::ColorCube&) override + [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::UnderlineColor::ColorCube&) override { return std::unexpected(FMTResult::FunctionNotImpl); /*BufferReadManip(Buffer).BasicReadType("\033[58;5;", t.GetColorRef(), 'm');*/ } - std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::UnderlineColor::Color24b&) override + [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::UnderlineColor::Color24b&) override { return std::unexpected(FMTResult::FunctionNotImpl); /*BufferReadManip(Buffer).BasicReadType("\033[58;2;", t.R, ';', t.G, ';', t.B, 'm');*/ } - std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Blink&) override + [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Blink&) override { return std::unexpected(FMTResult::FunctionNotImpl); /*BufferReadManip(Buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ } - std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Inverted&) override + [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Inverted&) override { return std::unexpected(FMTResult::FunctionNotImpl); /*BufferReadManip(Buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ } - std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Ideogram&) override + [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Ideogram&) override { return std::unexpected(FMTResult::FunctionNotImpl); /*BufferReadManip(Buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ } - std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Script&) override + [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Script&) override { return std::unexpected(FMTResult::FunctionNotImpl); /*BufferReadManip(Buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ diff --git a/src/StreamFormat/FMT/Context/ParserExecutor/ParserTextPropertiesExecutor/ParserTextPropertiesExecutor.h b/src/StreamFormat/FMT/Context/ParserExecutor/ParserTextPropertiesExecutor/ParserTextPropertiesExecutor.h index abdccd9c..6f8e60b6 100644 --- a/src/StreamFormat/FMT/Context/ParserExecutor/ParserTextPropertiesExecutor/ParserTextPropertiesExecutor.h +++ b/src/StreamFormat/FMT/Context/ParserExecutor/ParserTextPropertiesExecutor/ParserTextPropertiesExecutor.h @@ -35,35 +35,35 @@ namespace StreamFormat::FMT::Detail using IParserTextPropertiesExecutor::Buffer; public: - std::expected AllPropertiesReset() override { return {}; } + [[nodiscard]] std::expected AllPropertiesReset() override { return {}; } public: - std::expected ResetColor() override {} - std::expected ExecuteColor(const Detail::TextProperties::TextColor::BasicColorFG&) override { return {}; } - std::expected ExecuteColor(const Detail::TextProperties::TextColor::BasicColorBG&) override { return {}; } - std::expected ExecuteColor(const Detail::TextProperties::TextColor::BasicColor&) override { return {}; } - std::expected ExecuteColor(const Detail::TextProperties::TextColor::Color24bFG&) override { return {}; } - std::expected ExecuteColor(const Detail::TextProperties::TextColor::Color24bBG&) override { return {}; } - std::expected ExecuteColor(const Detail::TextProperties::TextColor::Color24b&) override { return {}; } - std::expected ExecuteColor(const Detail::TextProperties::TextColor::ColorCubeFG&) override { return {}; } - std::expected ExecuteColor(const Detail::TextProperties::TextColor::ColorCubeBG&) override { return {}; } - std::expected ExecuteColor(const Detail::TextProperties::TextColor::ColorCube&) override { return {}; } + [[nodiscard]] std::expected ResetColor() override {} + [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::BasicColorFG&) override { return {}; } + [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::BasicColorBG&) override { return {}; } + [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::BasicColor&) override { return {}; } + [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::Color24bFG&) override { return {}; } + [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::Color24bBG&) override { return {}; } + [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::Color24b&) override { return {}; } + [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::ColorCubeFG&) override { return {}; } + [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::ColorCubeBG&) override { return {}; } + [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::ColorCube&) override { return {}; } public: - std::expected ResetFront() override { return {}; } - std::expected ExecuteFront(const Detail::TextProperties::TextFront::FrontID&) override { return {}; } + [[nodiscard]] std::expected ResetFront() override { return {}; } + [[nodiscard]] std::expected ExecuteFront(const Detail::TextProperties::TextFront::FrontID&) override { return {}; } public: - std::expected ResetStyle() override { return {}; } - std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Intensity&) override { return {}; } - std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Italic&) override { return {}; } - std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Underline&) override { return {}; } - std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::UnderlineColor::Color&) override { return {}; } - std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::UnderlineColor::ColorCube&) override { return {}; } - std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::UnderlineColor::Color24b&) override { return {}; } - std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Blink&) override { return {}; } - std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Inverted&) override { return {}; } - std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Ideogram&) override { return {}; } - std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Script&) override { return {}; } + [[nodiscard]] std::expected ResetStyle() override { return {}; } + [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Intensity&) override { return {}; } + [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Italic&) override { return {}; } + [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Underline&) override { return {}; } + [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::UnderlineColor::Color&) override { return {}; } + [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::UnderlineColor::ColorCube&) override { return {}; } + [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::UnderlineColor::Color24b&) override { return {}; } + [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Blink&) override { return {}; } + [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Inverted&) override { return {}; } + [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Ideogram&) override { return {}; } + [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Script&) override { return {}; } }; } diff --git a/src/StreamFormat/FMT/Detail/FMTResult.h b/src/StreamFormat/FMT/Detail/FMTResult.h index 9e9ba96a..db1106b1 100644 --- a/src/StreamFormat/FMT/Detail/FMTResult.h +++ b/src/StreamFormat/FMT/Detail/FMTResult.h @@ -21,6 +21,9 @@ namespace StreamFormat::FMT Context_ParsingFormat, Context_ArgumentIndexResolution, + Context_ArgumentIndexExpected, Context_CannotApplyType, + + GivenArgs_UnableToDeduceSize, }; } diff --git a/src/StreamFormat/FMT/Detail/Specifiers.h b/src/StreamFormat/FMT/Detail/Specifiers.h index d934e2ee..8a170cbc 100644 --- a/src/StreamFormat/FMT/Detail/Specifiers.h +++ b/src/StreamFormat/FMT/Detail/Specifiers.h @@ -183,7 +183,7 @@ namespace StreamFormat::FMT::Detail public: [[nodiscard]] std::expected Pushback(const FormatSpecifier& specifier) { - if (SpecifierCount => SIZE) + if (SpecifierCount >= SIZE) return std::unexpected(FMTResult::Specifers_Full); Specifier[SpecifierCount++] = specifier; return {}; @@ -193,7 +193,7 @@ namespace StreamFormat::FMT::Detail { FormatSpecifier* local = Get(specifier.Name); if (local == nullptr) - return SF_TRY(Pushback(specifier)); + return Pushback(specifier); if (specifier.HasText) { local->HasText = true; local->AsText = specifier.AsText; } diff --git a/src/StreamFormat/FMT/Serializers/FormatChrono.h b/src/StreamFormat/FMT/Serializers/FormatChrono.h index a5a8d566..2f741ecc 100644 --- a/src/StreamFormat/FMT/Serializers/FormatChrono.h +++ b/src/StreamFormat/FMT/Serializers/FormatChrono.h @@ -78,38 +78,37 @@ namespace StreamFormat::FMT::Detail SF_TRY(FMTBufferWriteManip(buffer).WriteInteger(static_cast(min) % 1000, shift)); } - return true; + return {}; } template [[nodiscard]] std::expected WriteTime(const std::chrono::time_point& value, BufferInfoView pattern, FMTBufferOutInfo& buffer) { - BufferWriteManip(buffer).FastWriteString( - BufferTestManip(pattern).ViewExec( - [&]{FMTBufferParamsManip(pattern).ParamGoTo('%', '#', '/'); } - ) - ); + auto view = SF_TRY(BufferTestManip(pattern).ViewExec( + [&] -> std::expected { FMTBufferParamsManip(pattern).ParamGoTo('%', '#', '/'); return {}; } + )); + SF_TRY(BufferWriteManip(buffer).FastWriteString(view)); while (!BufferAccess(pattern).IsEndOfString()) { TimePrintMode mode; - if (BufferTestManip(pattern).IsEqualToForward('%')) + if (BufferTestAccess(pattern).IsEqualTo('%')) mode = TimePrintMode::Mod; - else if (BufferTestManip(pattern).IsEqualToForward('#')) + else if (BufferTestAccess(pattern).IsEqualTo('#')) mode = TimePrintMode::FullTime; - else if (BufferTestManip(pattern).IsEqualToForward('/')) + else if (BufferTestAccess(pattern).IsEqualTo('/')) mode = TimePrintMode::Sub; - WriteSubTime_(value, pattern, buffer, mode); + SF_TRY(BufferManip(pattern).Forward()); + SF_TRY(WriteSubTime_(value, pattern, buffer, mode)); - BufferWriteManip(buffer).FastWriteString( - BufferTestManip(pattern).ViewExec( - [&]{FMTBufferParamsManip(pattern).ParamGoTo('%', '#', '/'); } - ) - ); + auto view = SF_TRY(BufferTestManip(pattern).ViewExec( + [&] -> std::expected { FMTBufferParamsManip(pattern).ParamGoTo('%', '#', '/'); return {}; } + )); + SF_TRY(BufferWriteManip(buffer).FastWriteString(view)); } - return true; + return {}; } } @@ -131,12 +130,11 @@ namespace StreamFormat::FMT { if (executor.Data.Specifiers.Has("pattern")) { - Detail::WriteTime( + return Detail::WriteTime( std::chrono::time_point>(t), Detail::BufferInfoView(executor.Data.Specifiers.GetAsText("pattern", "%h:%m:%s.%ms")), executor.BufferOut ); - return; } Detail::BufferWriteManip(executor.BufferOut).FastWriteInteger(t.count()); diff --git a/src/StreamFormat/Json/JsonFormatter.h b/src/StreamFormat/Json/JsonFormatter.h index 1005520a..3e86ea28 100644 --- a/src/StreamFormat/Json/JsonFormatter.h +++ b/src/StreamFormat/Json/JsonFormatter.h @@ -44,15 +44,15 @@ namespace StreamFormat::JSON::Detail if (Settings.OneLine) return; if (Settings.IndentWithSpaces) - FMT::Detail::BufferOutManip(BufferOut).Pushback(' ', m_Indent * Settings.IndentSize); + FMT::Detail::BufferOutManip(BufferOut).Pushback(' ', m_Indent * Settings.IndentSize).value(); else - FMT::Detail::BufferOutManip(BufferOut).Pushback('\t', m_Indent * Settings.IndentSize); + FMT::Detail::BufferOutManip(BufferOut).Pushback('\t', m_Indent * Settings.IndentSize).value(); } void NewLine() { if (Settings.OneLine) return; - FMT::Detail::BufferOutManip(BufferOut).Pushback('\n'); + FMT::Detail::BufferOutManip(BufferOut).Pushback('\n').value(); Indent(); } void BeginNewObject() { ++m_Indent; } diff --git a/src/StreamFormat/Json/JsonObjects.h b/src/StreamFormat/Json/JsonObjects.h index 142addf6..d1877297 100644 --- a/src/StreamFormat/Json/JsonObjects.h +++ b/src/StreamFormat/Json/JsonObjects.h @@ -83,7 +83,7 @@ namespace StreamFormat::JSON JsonObjectSerializer::WriteObject(t, *this); } - std::string ToString() { return FMT::FormatString(*this); } + std::string ToString() { return FMT::FormatString(*this).value(); } public: virtual void ParserExecute(Detail::JsonParser& parser) = 0; diff --git a/src/StreamFormat/Json/JsonParser.cpp b/src/StreamFormat/Json/JsonParser.cpp index ff4977bb..4566ff71 100644 --- a/src/StreamFormat/Json/JsonParser.cpp +++ b/src/StreamFormat/Json/JsonParser.cpp @@ -18,13 +18,14 @@ namespace StreamFormat::JSON::Detail if (parser.IsJsonStringBegin()) { - manip.SkipOneOf('"'); + manip.SkipOneOf('"').value(); while (true) { manip.GoTo('"'); - if (FMT::Detail::BufferTestAccess(parser.BufferIn).PrevIsNotEqualTo('\\')) break; + if (FMT::Detail::BufferTestAccess(parser.BufferIn).PrevIsNotEqualTo('\\')) + break; } - manip.SkipOneOf('"'); + manip.SkipOneOf('"').value(); } else if (parser.IsJsonNumberBegin()) { diff --git a/src/StreamFormat/Json/JsonSerializer.h b/src/StreamFormat/Json/JsonSerializer.h index 8d9bbcb5..e12c771b 100644 --- a/src/StreamFormat/Json/JsonSerializer.h +++ b/src/StreamFormat/Json/JsonSerializer.h @@ -35,11 +35,11 @@ namespace StreamFormat::JSON static inline void Format(const T&, Detail::JsonFormatter& formatter) { - FMT::Detail::BufferWriteManip(formatter.BufferOut).FastWriteString(std::string_view("Unknown JsonFormatter for type : ")); - FMT::Detail::BufferWriteManip(formatter.BufferOut).FastWriteString(std::string_view(typeid(T).name())); + FMT::Detail::BufferWriteManip(formatter.BufferOut).FastWriteString(std::string_view("Unknown JsonFormatter for type : ")).value(); + FMT::Detail::BufferWriteManip(formatter.BufferOut).FastWriteString(std::string_view(typeid(T).name())).value(); #ifdef UNKOWN_TYPE_MESSAGE - FMT::FilePrint(std::cerr, "{C:red}JsonSerializer::Format<{}> not impl", typeid(T).name()); + FMT::FilePrint(std::cerr, "{C:red}JsonSerializer::Format<{}> not impl", typeid(T).name()).value(); #endif #ifdef UNKOWN_TYPE_THROW throw Detail::JsonTypeSerializerNotImpl{}; @@ -98,7 +98,7 @@ namespace StreamFormat::JSON { FMT::Detail::DynamicBufferOutManager bufferData; FMT::Detail::BufferOutInfo buffer(bufferData); - FMT::Detail::BufferUtils::ParseEscapedQuotedString(parser.BufferIn, buffer); + FMT::Detail::BufferUtils::ParseEscapedQuotedString(parser.BufferIn, buffer).value(); FMT::Detail::BufferOutManip(buffer).ComputeGeneratedSize(); t = bufferData.GetLastGeneratedString(); } @@ -106,7 +106,7 @@ namespace StreamFormat::JSON static inline void FormatSTDString(const std::string_view t, Detail::JsonFormatter& formatter) { FMT::Detail::BufferInfo buffer(t.data(), t.size()); - FMT::Detail::BufferUtils::FormatEscapedQuotedString(formatter.BufferOut, buffer); + FMT::Detail::BufferUtils::FormatEscapedQuotedString(formatter.BufferOut, buffer).value(); } }; @@ -115,7 +115,7 @@ namespace StreamFormat::JSON template static inline void ParseFloat(FloatType& t, Detail::JsonParser& parser) { - FMT::Detail::BufferReadManip(parser.BufferIn).FastReadFloat(t); + FMT::Detail::BufferReadManip(parser.BufferIn).FastReadFloat(t).value(); } template @@ -134,13 +134,13 @@ namespace StreamFormat::JSON template static inline void FormatFloat(const FloatType& t, Detail::JsonFormatter& formatter) { - FMT::Detail::BufferWriteManip(formatter.BufferOut).FastWriteFloat(t, formatter.Settings.FloatPrecision); + FMT::Detail::BufferWriteManip(formatter.BufferOut).FastWriteFloat(t, formatter.Settings.FloatPrecision).value(); } template static inline void FormatInteger(const IntType& t, Detail::JsonFormatter& formatter) { - FMT::Detail::BufferWriteManip(formatter.BufferOut).FastWriteInteger(t); + FMT::Detail::BufferWriteManip(formatter.BufferOut).FastWriteInteger(t).value(); } }; @@ -148,18 +148,18 @@ namespace StreamFormat::JSON { static inline void ParseBool(bool& t, Detail::JsonParser& parser) { - if (FMT::Detail::BufferTestManip(parser.BufferIn).IsSameForward("true", 5)) + if (FMT::Detail::BufferTestManip(parser.BufferIn).IsSameForward("true", 5).value()) t = true; - else if (FMT::Detail::BufferTestManip(parser.BufferIn).IsSameForward("false", 5)) + else if (FMT::Detail::BufferTestManip(parser.BufferIn).IsSameForward("false", 5).value()) t = false; } static inline void FormatBool(const bool& t, Detail::JsonFormatter& formatter) { if (t) - FMT::Detail::BufferWriteManip(formatter.BufferOut).FastWriteCharArray("true", 5); + FMT::Detail::BufferWriteManip(formatter.BufferOut).FastWriteCharArray("true", 5).value(); else - FMT::Detail::BufferWriteManip(formatter.BufferOut).FastWriteCharArray("false", 5); + FMT::Detail::BufferWriteManip(formatter.BufferOut).FastWriteCharArray("false", 5).value(); } }; @@ -171,7 +171,7 @@ namespace StreamFormat::JSON FMT::Detail::BufferTestAccess access(parser.BufferIn); FMT::Detail::BufferTestManip manip(parser.BufferIn); - manip.SkipOneOf('{'); + manip.SkipOneOf('{').value(); std::size_t idx = 0; while (FMT::Detail::BufferAccess(parser.BufferIn).IsEndOfString() == false) @@ -183,16 +183,16 @@ namespace StreamFormat::JSON JsonStringSerializer::ParseSTDString(name, parser); manip.SkipAllBlanks(); - manip.SkipOneOf(':'); + manip.SkipOneOf(':').value(); manip.SkipAllBlanks(); subObjectParsingFunction(t, idx++, std::move(name), parser); manip.GoTo(',', '}'); - manip.SkipOneOf(','); + manip.SkipOneOf(',').value(); } - manip.SkipOneOf('}'); + manip.SkipOneOf('}').value(); } template @@ -205,24 +205,24 @@ namespace StreamFormat::JSON }); } - static inline void FormatBegin(Detail::JsonFormatter& formatter) { FMT::Detail::BufferOutManip(formatter.BufferOut).Pushback('{'); } + static inline void FormatBegin(Detail::JsonFormatter& formatter) { FMT::Detail::BufferOutManip(formatter.BufferOut).Pushback('{').value(); } static inline void FormatEnd(Detail::JsonFormatter& formatter) { formatter.NewLine(); - FMT::Detail::BufferOutManip(formatter.BufferOut).Pushback('}'); + FMT::Detail::BufferOutManip(formatter.BufferOut).Pushback('}').value(); } template static inline void FormatObject(const std::string_view name, const SubObject& subObject, const std::size_t idx, Detail::JsonFormatter& formatter) { - if (idx != 0) FMT::Detail::BufferOutManip(formatter.BufferOut).Pushback(','); + if (idx != 0) FMT::Detail::BufferOutManip(formatter.BufferOut).Pushback(',').value(); formatter.BeginNewObject(); formatter.NewLine(); JsonStringSerializer::FormatSTDString(name, formatter); - FMT::Detail::BufferOutManip(formatter.BufferOut).Pushback(':'); - FMT::Detail::BufferOutManip(formatter.BufferOut).Pushback(' '); + FMT::Detail::BufferOutManip(formatter.BufferOut).Pushback(':').value(); + FMT::Detail::BufferOutManip(formatter.BufferOut).Pushback(' ').value(); formatter.Format(subObject); formatter.EndNewObject(); } @@ -236,7 +236,7 @@ namespace StreamFormat::JSON FMT::Detail::BufferTestAccess access(parser.BufferIn); FMT::Detail::BufferTestManip manip(parser.BufferIn); - manip.SkipOneOf('['); + manip.SkipOneOf('[').value(); std::size_t idx = 0; while (FMT::Detail::BufferAccess(parser.BufferIn).IsEndOfString() == false) @@ -248,10 +248,10 @@ namespace StreamFormat::JSON subObjectParsingFunction(t, idx++, parser); manip.GoTo(',', ']'); - manip.SkipOneOf(','); + manip.SkipOneOf(',').value(); } - manip.SkipOneOf(']'); + manip.SkipOneOf(']').value(); } template @@ -264,18 +264,18 @@ namespace StreamFormat::JSON }); } - static inline void FormatBegin(Detail::JsonFormatter& formatter) { FMT::Detail::BufferOutManip(formatter.BufferOut).Pushback('['); } + static inline void FormatBegin(Detail::JsonFormatter& formatter) { FMT::Detail::BufferOutManip(formatter.BufferOut).Pushback('[').value(); } static inline void FormatEnd(Detail::JsonFormatter& formatter) { formatter.NewLine(); - FMT::Detail::BufferOutManip(formatter.BufferOut).Pushback(']'); + FMT::Detail::BufferOutManip(formatter.BufferOut).Pushback(']').value(); } template static inline void FormatObject(const SubObject& subObject, const std::size_t idx, Detail::JsonFormatter& formatter) { - if (idx != 0) FMT::Detail::BufferOutManip(formatter.BufferOut).Pushback(','); + if (idx != 0) FMT::Detail::BufferOutManip(formatter.BufferOut).Pushback(',').value(); formatter.BeginNewObject(); formatter.NewLine(); @@ -286,9 +286,9 @@ namespace StreamFormat::JSON struct JsonNullSerializer { - static inline void ParseNull(Detail::JsonParser& parser) { FMT::Detail::BufferTestManip(parser.BufferIn).IsSameForward("null", 4); } + static inline void ParseNull(Detail::JsonParser& parser) { FMT::Detail::BufferTestManip(parser.BufferIn).IsSameForward("null", 4).value(); } - static inline void FormatNull(Detail::JsonFormatter& formatter) { FMT::Detail::BufferWriteManip(formatter.BufferOut).FastWriteCharArray("null", 4); } + static inline void FormatNull(Detail::JsonFormatter& formatter) { FMT::Detail::BufferWriteManip(formatter.BufferOut).FastWriteCharArray("null", 4).value(); } }; } diff --git a/src/StreamFormat/ProfilerManager/ProfilerFactory.cpp b/src/StreamFormat/ProfilerManager/ProfilerFactory.cpp index c5a3e13b..b4c8aabd 100644 --- a/src/StreamFormat/ProfilerManager/ProfilerFactory.cpp +++ b/src/StreamFormat/ProfilerManager/ProfilerFactory.cpp @@ -14,7 +14,7 @@ namespace StreamFormat::ProfilerManager std::ofstream file(path.string(), std::ios::out); JSON::FormatAsJson formatProfiler(profiler); - FMT::FilePrint(file, formatProfiler); + FMT::FilePrint(file, formatProfiler).value(); file.close(); } } diff --git a/src/StreamFormat/Tester/TestSuite/TestSuite.h b/src/StreamFormat/Tester/TestSuite/TestSuite.h index 959ea00a..dea63c57 100644 --- a/src/StreamFormat/Tester/TestSuite/TestSuite.h +++ b/src/StreamFormat/Tester/TestSuite/TestSuite.h @@ -217,13 +217,13 @@ namespace StreamFormat::FMT switch (status) { case StreamFormat::Tester::TestStatus::Ok: - executor.Run("[ {C:green}OK{C} ]"); + executor.Run("[ {C:green}OK{C} ]").value(); break; case StreamFormat::Tester::TestStatus::Fail: - executor.Run("[ {C:red}FAIL{C} ]"); + executor.Run("[ {C:red}FAIL{C} ]").value(); break; case StreamFormat::Tester::TestStatus::Crash: - executor.Run("[{C:magenta}Crash{C} ]"); + executor.Run("[{C:magenta}Crash{C} ]").value(); break; } } @@ -234,26 +234,26 @@ namespace StreamFormat::FMT { static void Format(const StreamFormat::Tester::Detail::TestStatusBank& statusBank, FormatterExecutor& executor) { - Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("TestsDone "); - executor.Run("{:C:white}", statusBank.TestsDone); + Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("TestsDone ").value(); + executor.Run("{:C:white}", statusBank.TestsDone).value(); - Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral(" | TestsOK "); + Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral(" | TestsOK ").value(); if (statusBank.TestsOk == statusBank.TestsDone) - executor.Run("{:C:green}", statusBank.TestsOk); + executor.Run("{:C:green}", statusBank.TestsOk).value(); else - executor.Run("{:C:yellow}", statusBank.TestsOk); + executor.Run("{:C:yellow}", statusBank.TestsOk).value(); - Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral(" | TestsFAIL "); + Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral(" | TestsFAIL ").value(); if (statusBank.TestsFail == 0) - executor.Run("{:C:green}", statusBank.TestsFail); + executor.Run("{:C:green}", statusBank.TestsFail).value(); else - executor.Run("{:C:red}", statusBank.TestsFail); + executor.Run("{:C:red}", statusBank.TestsFail).value(); - Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral(" | TestCrash "); + Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral(" | TestCrash ").value(); if (statusBank.TestsCrash == 0) - executor.Run("{:C:green}", statusBank.TestsCrash); + executor.Run("{:C:green}", statusBank.TestsCrash).value(); else - executor.Run("{:C:magenta}", statusBank.TestsCrash); + executor.Run("{:C:magenta}", statusBank.TestsCrash).value(); } }; } From ace851fc0d7bb5bb9c276b78b0801084498aef4f Mon Sep 17 00:00:00 2001 From: BELLIER Sacha Date: Mon, 25 Nov 2024 23:58:33 +0100 Subject: [PATCH 04/42] fix: add SF_TRY() for forgotten functions --- .bazelrc | 2 +- BUILD.bazel | 5 +- Examples/.bazelrc | 4 +- Examples/CompilerInfo/BUILD.bazel | 15 ---- Examples/CompilerInfo/main.cpp | 26 ------- Examples/HelloWorld/BUILD.bazel | 5 +- Examples/HelloWorld/main.cpp | 3 + Examples/MODULE.bazel | 19 +++-- MODULE.bazel | 24 +++--- src/StreamFormat/FLog/Detail/Detail.h | 15 ++-- src/StreamFormat/FLog/LoggerImpl/XLogger.h | 21 ++---- .../BufferOutManager/BasicBufferOutManager.h | 12 +-- .../DynamicBufferOutManager.h | 43 +++++++---- .../BufferOutManager/GivenBufferOutManager.h | 4 +- .../BufferOutManager/StaticBufferOutManager.h | 4 +- src/StreamFormat/FMT/Buffer/BufferOutManip.h | 46 ++++++------ src/StreamFormat/FMT/Buffer/BufferReadManip.h | 2 +- .../FMT/Buffer/BufferWriteManip.h | 20 ++--- .../FMT/Buffer/FMTBufferOutManip.h | 14 +++- .../FMT/Buffer/FMTBufferReadManip.h | 30 ++++---- .../FMT/Buffer/FMTBufferWriteManip.h | 73 +++++++++++-------- .../FMT/Buffer/Utils/BufferGlobberManip.h | 21 +++--- .../FMT/Buffer/Utils/BufferShiftManip.h | 12 +++ .../FMT/Buffer/Utils/BufferUtils.h | 2 +- .../Context/BasicContext/BasicArgsInterface.h | 5 +- .../FMT/Context/BasicContext/BasicContext.h | 12 ++- .../BasicContext/BasicContextParse-impl.h | 22 ++++-- .../BasicContext/TextPropertiesManager-impl.h | 64 ++++++++-------- .../BasicFormatterExecutor.h | 20 +++-- .../FormatterExecutor/FormatBasics-impl.h | 44 +++++++---- .../Context/FormatterExecutor/FormatterType.h | 4 +- .../Context/FormatterExecutor/STDEnumerable.h | 14 ++-- .../FormatterExecutor/UtilityFunctions.h | 48 ++++++------ .../ParserExecutor/BasicParserExecutor.h | 15 ++-- .../Context/ParserExecutor/ParseBasics-impl.h | 3 + .../Context/ParserExecutor/UtilityFunctions.h | 4 +- src/StreamFormat/FMT/Detail/FMTResult.h | 3 + .../FMT/Serializers/CompilationData.h | 12 +-- .../FMT/Serializers/FormatChrono.h | 36 +++++---- .../FMT/Serializers/FormatSTDLib.h | 24 ++++-- .../FMT/Serializers/STDContainer/FMT_array.h | 2 +- .../FMT/Serializers/STDContainer/FMT_deque.h | 3 +- .../STDContainer/FMT_forward_list.h | 2 +- .../FMT/Serializers/STDContainer/FMT_list.h | 3 +- .../FMT/Serializers/STDContainer/FMT_map.h | 7 +- .../FMT/Serializers/STDContainer/FMT_queue.h | 5 +- .../FMT/Serializers/STDContainer/FMT_set.h | 6 +- .../FMT/Serializers/STDContainer/FMT_tuple.h | 38 ++++++---- .../STDContainer/FMT_unordered_map.h | 4 +- .../STDContainer/FMT_unordered_set.h | 4 +- .../FMT/Serializers/STDContainer/FMT_vector.h | 3 +- src/StreamFormat/Json/JsonFactory.h | 3 +- src/StreamFormat/Json/JsonSerializer.h | 8 +- src/StreamFormat/ProfilerManager/Event.h | 3 +- src/StreamFormat/Tester/TestSuite/TestSuite.h | 50 +++++++------ 55 files changed, 491 insertions(+), 402 deletions(-) delete mode 100644 Examples/CompilerInfo/BUILD.bazel delete mode 100644 Examples/CompilerInfo/main.cpp diff --git a/.bazelrc b/.bazelrc index d16d3bb8..0c1b43a2 100644 --- a/.bazelrc +++ b/.bazelrc @@ -20,7 +20,7 @@ common:tidy_format_error --aspects_parameters=enable_error=True # Winlibs common:winlibs-gcc --extra_toolchains=@winlibs//:gcc-toolchain -common:winlibs-clang --extra_toolchains=@pthread-winlibs//:clang-toolchain +common:winlibs-clang --extra_toolchains=@winlibs//:clang-toolchain # BuildBuddy common:linux --workspace_status_command=$(pwd)/.buildbuddy/workspace_status.sh diff --git a/BUILD.bazel b/BUILD.bazel index 4ac952a0..61105670 100644 --- a/BUILD.bazel +++ b/BUILD.bazel @@ -8,7 +8,7 @@ cc_library( hdrs = glob([ "src/**/*.h" ]), includes = [ "src/" ], copts = select({ - "@rules_cc//cc/compiler:msvc-cl": ["/std:c++23"], + "@rules_cc//cc/compiler:msvc-cl": ["/std:latest"], "//conditions:default": ["-std=c++23"], }), strip_include_prefix = "src", @@ -21,9 +21,10 @@ cc_test( name = "StreamFormatTests", srcs = glob([ "Tests/**/*.h", "Tests/**/*.cpp" ]), copts = select({ - "@rules_cc//cc/compiler:msvc-cl": ["/std:c++23"], + "@rules_cc//cc/compiler:msvc-cl": ["/std:latest"], "//conditions:default": ["-std=c++23"], }), deps = [ ":StreamFormat" ], + linkopts = [ "-lpthread" ], visibility = ["//visibility:public"], ) diff --git a/Examples/.bazelrc b/Examples/.bazelrc index 0cd88d06..538a4b5d 100644 --- a/Examples/.bazelrc +++ b/Examples/.bazelrc @@ -6,5 +6,5 @@ common --verbose_failures test --test_output=errors # Winlibs -common:winlibs-gcc --extra_toolchains=@ex_winlibs//:gcc-toolchain -common:winlibs-clang --extra_toolchains=@pthread-ex_winlibs//:clang-toolchain +common:winlibs-gcc --extra_toolchains=@winlibs//:gcc-toolchain +common:winlibs-clang --extra_toolchains=@winlibs//:clang-toolchain diff --git a/Examples/CompilerInfo/BUILD.bazel b/Examples/CompilerInfo/BUILD.bazel deleted file mode 100644 index 13f19c6d..00000000 --- a/Examples/CompilerInfo/BUILD.bazel +++ /dev/null @@ -1,15 +0,0 @@ -"" - -load("@rules_cc//cc:defs.bzl", "cc_binary") - -cc_binary( - name = "CompilerInfo", - srcs = glob([ "*.h", "*.cpp" ]), - includes = [ "" ], - copts = select({ - "@rules_cc//cc/compiler:msvc-cl": ["/std:c++20"], - "//conditions:default": ["-std=c++20"], - }), - deps = [ "@streamformat//:StreamFormat" ], - visibility = ["//visibility:public"], -) diff --git a/Examples/CompilerInfo/main.cpp b/Examples/CompilerInfo/main.cpp deleted file mode 100644 index 5eab2cff..00000000 --- a/Examples/CompilerInfo/main.cpp +++ /dev/null @@ -1,26 +0,0 @@ -#include "StreamFormat/FLog.h" -#include "StreamFormat/FLog/DefaultLogger.h" - -#define COMPILER "Not Detected !" -#if defined(STREAMFORMAT_COMPILER_CLANG) - #undef COMPILER - #define COMPILER "clang" -#elif defined(STREAMFORMAT_COMPILER_GCC) - #undef COMPILER - #define COMPILER "gcc" -#elif defined(STREAMFORMAT_COMPILER_MSVC) - #undef COMPILER - #define COMPILER "msvc" -#endif - -#define MODE "RELEASE" -#ifdef STREAMFORMAT_DEBUG - #undef MODE - #define MODE "DEBUG" -#endif - -int main() -{ - StreamFormat::FLog::DefaultLogger::Core().Info("COMPILER : {}", COMPILER); - StreamFormat::FLog::DefaultLogger::Core().Info("MODE : {}", MODE); -} diff --git a/Examples/HelloWorld/BUILD.bazel b/Examples/HelloWorld/BUILD.bazel index a95eb0d8..694d1203 100644 --- a/Examples/HelloWorld/BUILD.bazel +++ b/Examples/HelloWorld/BUILD.bazel @@ -7,9 +7,10 @@ cc_binary( srcs = glob([ "*.h", "*.cpp" ]), includes = [ "" ], copts = select({ - "@rules_cc//cc/compiler:msvc-cl": ["/std:c++20"], - "//conditions:default": ["-std=c++20"], + "@rules_cc//cc/compiler:msvc-cl": ["/std:latest"], + "//conditions:default": ["-std=c++23"], }), + linkopts = [ "-lpthread" ], deps = [ "@streamformat//:StreamFormat" ], visibility = ["//visibility:public"], ) diff --git a/Examples/HelloWorld/main.cpp b/Examples/HelloWorld/main.cpp index e7b9c592..467a469e 100644 --- a/Examples/HelloWorld/main.cpp +++ b/Examples/HelloWorld/main.cpp @@ -1,10 +1,13 @@ #include "StreamFormat/FLog.h" #include "StreamFormat/FLog/DefaultLogger.h" +#include "StreamFormat/FMT/Context/FormatterExecutor/UtilityFunctions.h" #include int main() { + std::cout << StreamFormat::FMT::FormatString("HelloWorld !").value(); + StreamFormat::FLog::DefaultLogger::Core().Info("HelloWorld !"); using namespace std::chrono_literals; diff --git a/Examples/MODULE.bazel b/Examples/MODULE.bazel index 53473ca6..57961fed 100644 --- a/Examples/MODULE.bazel +++ b/Examples/MODULE.bazel @@ -6,21 +6,20 @@ module( version = "0.1", ) +bazel_dep(name = "rules_cc", version = "0.0.10") +bazel_dep(name = "platforms", version = "0.0.10") git_override(module_name="bazel_utilities", remote="https://github.com/0-Sacha/bazel_utilities.git", commit="7f6c3585c41278918428ed48d45b12413c197fc0") git_override(module_name="bazel_buildbuddy", remote="https://github.com/0-Sacha/bazel_buildbuddy.git", commit="b60314cac7826edb87efe285b032b877ad725f84") git_override(module_name="bazel_winlibs", remote="https://github.com/0-Sacha/bazel_winlibs.git", commit="e2cc97b61cb9115fbc2b7169dc9d1cb36b351935") -local_path_override(module_name = "streamformat", path = "../") +bazel_dep(name = "bazel_utilities", version = "0.0.1", dev_dependency = True) +bazel_dep(name = "bazel_winlibs", version = "0.0.1", dev_dependency = True) +bazel_dep(name = "bazel_buildbuddy", version = "0.0.1", dev_dependency = True) -bazel_dep(name = "rules_cc", version = "0.0.10") -bazel_dep(name = "platforms", version = "0.0.10") -bazel_dep(name = "bazel_utilities", version = "0.0.1") -bazel_dep(name = "bazel_winlibs", version = "0.0.1") +local_path_override(module_name = "streamformat", path = "../") bazel_dep(name = "streamformat") -winlibs_toolchain_extension = use_extension("@bazel_winlibs//:rules.bzl", "winlibs_toolchain_extension") +winlibs_toolchain_extension = use_extension("@bazel_winlibs//:rules.bzl", "winlibs_toolchain_extension", dev_dependency = True) inject_repo(winlibs_toolchain_extension, "platforms", "bazel_utilities") -winlibs_toolchain_extension.winlibs_toolchain(name = "ex_winlibs") -winlibs_toolchain_extension.winlibs_toolchain(name = "pthread-ex_winlibs", linklibs = [ "pthread" ]) -use_repo(winlibs_toolchain_extension, "ex_winlibs") -use_repo(winlibs_toolchain_extension, "pthread-ex_winlibs") \ No newline at end of file +winlibs_toolchain_extension.winlibs_toolchain(name = "winlibs") +use_repo(winlibs_toolchain_extension, "winlibs") \ No newline at end of file diff --git a/MODULE.bazel b/MODULE.bazel index be47f62a..398f5829 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -6,33 +6,27 @@ module( version = "0.1", ) +bazel_dep(name = "rules_cc", version = "0.0.10") +bazel_dep(name = "platforms", version = "0.0.10") + git_override(module_name="bazel_utilities", remote="https://github.com/0-Sacha/bazel_utilities.git", commit="aa399bb2599e2cd64a35a2275ce0f73a539524a5") git_override(module_name="bazel_buildbuddy", remote="https://github.com/0-Sacha/bazel_buildbuddy.git", commit="b96ebe6a8dbe7a6c82bd91d6e0cb79e53f11fa8f") git_override(module_name="bazel_winlibs", remote="https://github.com/0-Sacha/bazel_winlibs.git", commit="0f9fcc1b821b48e0bfa216f876a1df2a27b0522f") +bazel_dep(name = "bazel_utilities", version = "0.0.1", dev_dependency = True) +bazel_dep(name = "bazel_buildbuddy", version = "0.0.1", dev_dependency = True) +bazel_dep(name = "bazel_winlibs", version = "0.0.1", dev_dependency = True) -bazel_dep(name = "rules_cc", version = "0.0.10") -bazel_dep(name = "platforms", version = "0.0.10") -bazel_dep(name = "bazel_utilities", version = "0.0.1") -bazel_dep(name = "bazel_buildbuddy", version = "0.0.1") -bazel_dep(name = "bazel_winlibs", version = "0.0.1") - +git_override(module_name = "hedron_compile_commands", remote = "https://github.com/hedronvision/bazel-compile-commands-extractor.git", commit = "1e08f8e0507b6b6b1f4416a9a22cf5c28beaba93",) bazel_dep(name = "hedron_compile_commands", dev_dependency = True) -git_override( - module_name = "hedron_compile_commands", - remote = "https://github.com/hedronvision/bazel-compile-commands-extractor.git", - commit = "1e08f8e0507b6b6b1f4416a9a22cf5c28beaba93", -) -winlibs_toolchain_extension = use_extension("@bazel_winlibs//:rules.bzl", "winlibs_toolchain_extension") +winlibs_toolchain_extension = use_extension("@bazel_winlibs//:rules.bzl", "winlibs_toolchain_extension", dev_dependency = True) inject_repo(winlibs_toolchain_extension, "platforms", "bazel_utilities") winlibs_toolchain_extension.winlibs_toolchain(name = "winlibs") -winlibs_toolchain_extension.winlibs_toolchain(name = "pthread-winlibs", linklibs = [ "pthread" ]) use_repo(winlibs_toolchain_extension, "winlibs") -use_repo(winlibs_toolchain_extension, "pthread-winlibs") # register_toolchains("@winlibs//:gcc-toolchain") # register_toolchains("@winlibs//:clang-toolchain") -buildbuddy_toolchain_extension = use_extension("@bazel_buildbuddy//:rules.bzl", "buildbuddy_toolchain_extension") +buildbuddy_toolchain_extension = use_extension("@bazel_buildbuddy//:rules.bzl", "buildbuddy_toolchain_extension", dev_dependency = True) inject_repo(buildbuddy_toolchain_extension, "platforms", "bazel_utilities") buildbuddy_toolchain_extension.buildbuddy_toolchain(name = "buildbuddy") use_repo(buildbuddy_toolchain_extension, "buildbuddy") diff --git a/src/StreamFormat/FLog/Detail/Detail.h b/src/StreamFormat/FLog/Detail/Detail.h index 5c3e3231..041d05df 100644 --- a/src/StreamFormat/FLog/Detail/Detail.h +++ b/src/StreamFormat/FLog/Detail/Detail.h @@ -42,25 +42,28 @@ namespace StreamFormat::FMT template struct FormatterType, FormatterExecutor> { - static void Format(const StreamFormat::FLog::AddIndentInFormat& format, FormatterExecutor& executor) + [[nodiscard]] static std::expected Format(const StreamFormat::FLog::AddIndentInFormat& format, FormatterExecutor& executor) { - Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("{K:indent}"); - executor.WriteType(format.Format); + SF_TRY(Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("{K:indent}")); + return executor.WriteType(format.Format); } }; template struct FormatterType, FormatterExecutor> { - static void Format(const StreamFormat::FLog::ConcateNameAndSinkName& names, FormatterExecutor& executor) + [[nodiscard]] static std::expected Format(const StreamFormat::FLog::ConcateNameAndSinkName& names, FormatterExecutor& executor) { - executor.Run(names.LoggerName, FORMAT_SV("sink", names.SinkName)); + return executor.Run(names.LoggerName, FORMAT_SV("sink", names.SinkName)); } }; template struct FormatterType, FormatterExecutor> { - static void Format(const StreamFormat::FLog::FuturConcateNameAndSinkName& names, FormatterExecutor& executor) { executor.Run(names.LoggerName, "sink"); } + [[nodiscard]] static std::expected Format(const StreamFormat::FLog::FuturConcateNameAndSinkName& names, FormatterExecutor& executor) + { + return executor.Run(names.LoggerName, "sink"); + } }; } diff --git a/src/StreamFormat/FLog/LoggerImpl/XLogger.h b/src/StreamFormat/FLog/LoggerImpl/XLogger.h index c930f8f6..2b19ec6e 100644 --- a/src/StreamFormat/FLog/LoggerImpl/XLogger.h +++ b/src/StreamFormat/FLog/LoggerImpl/XLogger.h @@ -155,30 +155,25 @@ namespace StreamFormat::FMT template struct FormatterType { - static void Format(const StreamFormat::FLog::LogSeverity::Value t, FormatterExecutor& executor) + [[nodiscard]] static std::expected Format(const StreamFormat::FLog::LogSeverity::Value t, FormatterExecutor& executor) { executor.Data.KeepNewStyle = true; switch (t) { case StreamFormat::FLog::LogSeverity::Trace: - FormatterType::Format(Detail::TextProperties::TextColor::BasicColorFG::BrightBlack, executor); - break; + return FormatterType::Format(Detail::TextProperties::TextColor::BasicColorFG::BrightBlack, executor); case StreamFormat::FLog::LogSeverity::Debug: - FormatterType::Format(Detail::TextProperties::TextColor::BasicColorFG::Blue, executor); - break; + return FormatterType::Format(Detail::TextProperties::TextColor::BasicColorFG::Blue, executor); case StreamFormat::FLog::LogSeverity::Info: - FormatterType::Format(Detail::TextProperties::TextColor::BasicColorFG::Green, executor); - break; + return FormatterType::Format(Detail::TextProperties::TextColor::BasicColorFG::Green, executor); case StreamFormat::FLog::LogSeverity::Warn: - FormatterType::Format(Detail::TextProperties::TextColor::BasicColorFG::Yellow, executor); - break; + return FormatterType::Format(Detail::TextProperties::TextColor::BasicColorFG::Yellow, executor); case StreamFormat::FLog::LogSeverity::Error: - FormatterType::Format(Detail::TextProperties::TextColor::BasicColorFG::Red, executor); - break; + return FormatterType::Format(Detail::TextProperties::TextColor::BasicColorFG::Red, executor); case StreamFormat::FLog::LogSeverity::Fatal: - FormatterType::Format(Detail::TextProperties::TextColor::BasicColorFG::BrightMagenta, executor); - break; + return FormatterType::Format(Detail::TextProperties::TextColor::BasicColorFG::BrightMagenta, executor); } + return {}; } }; } diff --git a/src/StreamFormat/FMT/Buffer/BufferOutManager/BasicBufferOutManager.h b/src/StreamFormat/FMT/Buffer/BufferOutManager/BasicBufferOutManager.h index ee0de785..7cf9d3b1 100644 --- a/src/StreamFormat/FMT/Buffer/BufferOutManager/BasicBufferOutManager.h +++ b/src/StreamFormat/FMT/Buffer/BufferOutManager/BasicBufferOutManager.h @@ -5,12 +5,6 @@ namespace StreamFormat::FMT::Detail { - enum class BufferManagerError - { - StaticMemoryManager, - AllocationFailed, - }; - template class BasicBufferOutManager { @@ -21,11 +15,11 @@ namespace StreamFormat::FMT::Detail BasicBufferOutManager& operator=(BasicBufferOutManager&) = delete; protected: - virtual void BeginContextImpl() {} + [[nodiscard]] virtual std::expected BeginContextImpl() {} virtual void ComputeGeneratedSizeImpl(const std::size_t /* totalGeneratedLength */) {} public: - void BeginContext() { BeginContextImpl(); } + [[nodiscard]] std::expected BeginContext() { return BeginContextImpl(); } void ComputeGeneratedSize(std::size_t totalGeneratedLength) { ComputeGeneratedSizeImpl(totalGeneratedLength); @@ -38,7 +32,7 @@ namespace StreamFormat::FMT::Detail virtual std::size_t GetBufferSize() const = 0; public: - [[nodiscard]] virtual std::expected AddSize(const std::size_t count) = 0; + [[nodiscard]] virtual std::expected AddSize(const std::size_t count) = 0; public: BufferInfoView GetLastGeneratedBufferInfoView() const { return BufferInfoView(GetBuffer(), m_LastGeneratedDataSize); } diff --git a/src/StreamFormat/FMT/Buffer/BufferOutManager/DynamicBufferOutManager.h b/src/StreamFormat/FMT/Buffer/BufferOutManager/DynamicBufferOutManager.h index 7a2f2051..85fc8482 100644 --- a/src/StreamFormat/FMT/Buffer/BufferOutManager/DynamicBufferOutManager.h +++ b/src/StreamFormat/FMT/Buffer/BufferOutManager/DynamicBufferOutManager.h @@ -13,10 +13,9 @@ namespace StreamFormat::FMT::Detail { public: DynamicBufferOutManager(std::size_t beginSize = DEFAULT_BEGIN_SIZE) - { - m_Buffer.reset(new CharType[beginSize]); - m_BufferSize = beginSize; - } + : m_BufferSize(beginSize) + {} + ~DynamicBufferOutManager() override = default; DynamicBufferOutManager(DynamicBufferOutManager&) = delete; DynamicBufferOutManager& operator=(DynamicBufferOutManager&) = delete; @@ -29,15 +28,27 @@ namespace StreamFormat::FMT::Detail public: CharType* GetBuffer() override { return m_Buffer.get(); } const CharType* GetBuffer() const override { return m_Buffer.get(); } - std::size_t GetBufferSize() const override { return m_BufferSize; } + std::size_t GetBufferSize() const override { if (m_Buffer == nullptr) return 0; return m_BufferSize; } public: - [[nodiscard]] std::expected AddSize(const std::size_t count) override { return Resize(count + m_BufferSize); } - [[nodiscard]] std::expected Resize(const std::size_t targetBufferSize); + [[nodiscard]] std::expected BeginContextImpl() final + { + if (m_Buffer != nullptr) + return {}; + + CharType* alloc = new CharType[m_BufferSize]; + if (alloc == nullptr) + return std::unexpected(FMTResult::Manager_AllocationFailed); + m_Buffer.reset(alloc); + return {}; + } + + [[nodiscard]] std::expected AddSize(const std::size_t count) override { return Resize(count + m_BufferSize); } + [[nodiscard]] std::expected Resize(const std::size_t targetBufferSize); protected: - std::unique_ptr m_Buffer; - std::size_t m_BufferSize; + std::unique_ptr m_Buffer = nullptr; + std::size_t m_BufferSize = 0; }; template @@ -71,24 +82,26 @@ namespace StreamFormat::FMT::Detail ShrinkDynamicBufferOutManager& operator=(ShrinkDynamicBufferOutManager&) = delete; protected: - void BeginContextImpl() override { ShrinkIfNeeded(); } void ComputeGeneratedSizeImpl(std::size_t totalGeneratedLength) override { + // WTF m_MeanGeneratedSize = (m_MeanGeneratedSize * MEAN_CALCFACT_OLD + totalGeneratedLength * MEAN_CALCFACT_LAST) / (MEAN_CALCFACT_OLD + MEAN_CALCFACT_LAST); } public: - void ShrinkIfNeeded() + [[nodiscard]] std::expected ShrinkIfNeeded() { - if (m_BufferSize > static_cast(m_MeanGeneratedSize * MEAN_SIZE_OVERFLOW)) Resize(static_cast(m_MeanGeneratedSize * MEAN_SIZE_RESIZE)); + if (m_BufferSize > static_cast(m_MeanGeneratedSize * MEAN_SIZE_OVERFLOW)) + return Resize(static_cast(m_MeanGeneratedSize * MEAN_SIZE_RESIZE)); + return {}; } private: - std::size_t m_MeanGeneratedSize; + std::size_t m_MeanGeneratedSize = 0; }; template - [[nodiscard]] std::expected DynamicBufferOutManager::Resize(const std::size_t targetBufferSize) + [[nodiscard]] std::expected DynamicBufferOutManager::Resize(const std::size_t targetBufferSize) { std::size_t newBufferSize = targetBufferSize; @@ -101,7 +114,7 @@ namespace StreamFormat::FMT::Detail CharType* newBuffer = new CharType[newBufferSize]; if (newBuffer == nullptr) - return std::unexpected(BufferManagerError::AllocationFailed); + return std::unexpected(FMTResult::Manager_AllocationFailed); std::memcpy(newBuffer, m_Buffer.get(), std::min(newBufferSize, m_BufferSize)); diff --git a/src/StreamFormat/FMT/Buffer/BufferOutManager/GivenBufferOutManager.h b/src/StreamFormat/FMT/Buffer/BufferOutManager/GivenBufferOutManager.h index a264da80..614f528e 100644 --- a/src/StreamFormat/FMT/Buffer/BufferOutManager/GivenBufferOutManager.h +++ b/src/StreamFormat/FMT/Buffer/BufferOutManager/GivenBufferOutManager.h @@ -30,9 +30,9 @@ namespace StreamFormat::FMT::Detail std::size_t GetBufferSize() const override { return m_BufferSize; } public: - [[nodiscard]] std::expected AddSize(const std::size_t /* count */) override + [[nodiscard]] std::expected AddSize(const std::size_t /* count */) override { - return std::unexpected(BufferManagerError::StaticMemoryManager); + return std::unexpected(FMTResult::Manager_StaticMemory); } private: diff --git a/src/StreamFormat/FMT/Buffer/BufferOutManager/StaticBufferOutManager.h b/src/StreamFormat/FMT/Buffer/BufferOutManager/StaticBufferOutManager.h index b9372a43..078aab71 100644 --- a/src/StreamFormat/FMT/Buffer/BufferOutManager/StaticBufferOutManager.h +++ b/src/StreamFormat/FMT/Buffer/BufferOutManager/StaticBufferOutManager.h @@ -18,9 +18,9 @@ namespace StreamFormat::FMT::Detail std::size_t GetBufferSize() const override { return Count; } public: - [[nodiscard]] std::expected AddSize(const std::size_t) override + [[nodiscard]] std::expected AddSize(const std::size_t) override { - return std::unexpected(BufferManagerError::StaticMemoryManager); + return std::unexpected(FMTResult::Manager_StaticMemory); } private: diff --git a/src/StreamFormat/FMT/Buffer/BufferOutManip.h b/src/StreamFormat/FMT/Buffer/BufferOutManip.h index c7046ba7..e62b9851 100644 --- a/src/StreamFormat/FMT/Buffer/BufferOutManip.h +++ b/src/StreamFormat/FMT/Buffer/BufferOutManip.h @@ -20,23 +20,30 @@ namespace StreamFormat::FMT::Detail using BufferInfo::Get; using BufferInfo::Manip; - public: + protected: BufferOutInfo(BasicBufferOutManager& bufferOutManager) noexcept : BufferInfo() + , Manager(bufferOutManager) + {} + + protected: + [[nodiscard]] static std::expected Init(BufferOutInfo& in) { - SetManager(bufferOutManager); + SF_TRY(in.Manager.BeginContext()); + BufferManip(in).Set(in.Manager.GetBuffer(), in.Manager.GetBufferSize()); + return {}; } public: - BasicBufferOutManager* Manager; - - public: - [[nodiscard]] std::expected SetManager(BasicBufferOutManager& bufferOutManager) + [[nodiscard]] static std::expected, FMTResult> Create(BasicBufferOutManager& bufferOutManager) { - Manager = &bufferOutManager; - Manager->BeginContext(); - BufferManip(*this).Set(Manager->GetBuffer(), Manager->GetBufferSize()); + BufferOutInfo res(bufferOutManager); + SF_TRY(Init(res)); + return res; } + + public: + BasicBufferOutManager& Manager; }; template @@ -54,23 +61,15 @@ namespace StreamFormat::FMT::Detail BufferOutInfo& Buffer; public: - [[nodiscard]] void SetManager(BasicBufferOutManager& bufferOutManager) noexcept - { - return Buffer.SetManager(bufferOutManager); - } - - void ComputeGeneratedSize() noexcept { Buffer.Manager->ComputeGeneratedSize(BufferAccess(Buffer).GetBufferCurrentSize()); } + void ComputeGeneratedSize() noexcept { Buffer.Manager.ComputeGeneratedSize(BufferAccess(Buffer).GetBufferCurrentSize()); } public: [[nodiscard]] std::expected AddSize(const std::size_t count) noexcept { - if (Buffer.Manager == nullptr) - return std::unexpected(FMTResult::Buffer_NonValid); std::size_t currentSize = BufferAccess(Buffer).GetBufferCurrentSize(); - if (not Buffer.Manager->AddSize(count)) - return std::unexpected(FMTResult::Buffer_UnableToReserveMemory); - BufferManip(Buffer).Set(Buffer.Manager->GetBuffer(), Buffer.Manager->GetBufferSize()); - Buffer.CurrentPos = Buffer.Manager->GetBuffer() + currentSize; + SF_TRY(Buffer.Manager.AddSize(count)) + BufferManip(Buffer).Set(Buffer.Manager.GetBuffer(), Buffer.Manager.GetBufferSize()); + Buffer.CurrentPos = Buffer.Manager.GetBuffer() + currentSize; return {}; } @@ -115,7 +114,10 @@ namespace StreamFormat::FMT::Detail } public: - [[nodiscard]] inline std::expected AddSpaces(const auto count) noexcept { return Pushback(' ', count); } + [[nodiscard]] inline std::expected AddSpaces(const auto count) noexcept + { + return Pushback(' ', count); + } private: template diff --git a/src/StreamFormat/FMT/Buffer/BufferReadManip.h b/src/StreamFormat/FMT/Buffer/BufferReadManip.h index 76558a48..02198e8b 100644 --- a/src/StreamFormat/FMT/Buffer/BufferReadManip.h +++ b/src/StreamFormat/FMT/Buffer/BufferReadManip.h @@ -89,8 +89,8 @@ namespace StreamFormat::FMT::Detail } // TODO : Opti with bigger types - { *str++ = BufferManip(Buffer).GetAndForward(); } while (sizeToCopy-- != 0) + { *str++ = SF_TRY(BufferManip(Buffer).GetAndForward()); } if (isZeroEnded) { *str = 0; } return {}; diff --git a/src/StreamFormat/FMT/Buffer/BufferWriteManip.h b/src/StreamFormat/FMT/Buffer/BufferWriteManip.h index 16ec2508..d312176a 100644 --- a/src/StreamFormat/FMT/Buffer/BufferWriteManip.h +++ b/src/StreamFormat/FMT/Buffer/BufferWriteManip.h @@ -61,11 +61,11 @@ namespace StreamFormat::FMT::Detail { BufferOutManip manip(Buffer); - if (i == 0) { manip.Pushback('0'); return {}; } + if (i == 0) { SF_TRY(manip.Pushback('0')); return {}; } if constexpr (std::is_signed_v) { - if (i < 0) { manip.Pushback('-'); i = -i; } + if (i < 0) { SF_TRY(manip.Pushback('-')); i = -i; } } std::int32_t nbDigit = BufferWriteUtils::GetNumberOfDigitDec(i); @@ -95,7 +95,7 @@ namespace StreamFormat::FMT::Detail T k = std::trunc(i); i = i - k; std::int32_t nbDigit = BufferWriteUtils::GetNumberOfDigitDec(k); - manip.Forward(nbDigit); + SF_TRY(manip.Forward(nbDigit)); std::int32_t nbDigit_ = nbDigit; while (nbDigit_ > 0) { @@ -103,13 +103,13 @@ namespace StreamFormat::FMT::Detail k /= 10; nbDigit_--; } - manip.Forward(nbDigit); - manip.Pushback('.'); + SF_TRY(manip.Forward(nbDigit)); + SF_TRY(manip.Pushback('.')); while (floatPrecision-- >= 0) { TChar intPart = static_cast(std::trunc(i *= 10)); - manip.Pushback(intPart + '0'); + SF_TRY(manip.Pushback(intPart + '0')); i -= intPart; } } @@ -141,7 +141,8 @@ namespace StreamFormat::FMT::Detail [[nodiscard]] inline std::expected FastWriteStringLitteral(CharInput (&str)[SIZE]) { std::size_t size = SIZE; - while (str[size - 1] == 0) --size; + while (str[size - 1] == 0) + { --size; } return FastWriteCharArray(str, size); } @@ -158,9 +159,10 @@ namespace StreamFormat::FMT::Detail template [[nodiscard]] inline std::expected BasicWriteType(Type&& type, Rest&&... rest) { - BasicWriteType(type); + SF_TRY(BasicWriteType(type)); if constexpr (sizeof...(rest) > 0) - BasicWriteType(std::forward(rest)...); + SF_TRY(BasicWriteType(std::forward(rest)...)); + return {}; } }; } diff --git a/src/StreamFormat/FMT/Buffer/FMTBufferOutManip.h b/src/StreamFormat/FMT/Buffer/FMTBufferOutManip.h index f94661e7..6f1ae1ed 100644 --- a/src/StreamFormat/FMT/Buffer/FMTBufferOutManip.h +++ b/src/StreamFormat/FMT/Buffer/FMTBufferOutManip.h @@ -21,11 +21,19 @@ namespace StreamFormat::FMT::Detail using BufferOutInfo::Manager; - public: + protected: FMTBufferOutInfo(BasicBufferOutManager& bufferOutManager) noexcept : BufferOutInfo(bufferOutManager) {} + public: + [[nodiscard]] static std::expected, FMTResult> Create(BasicBufferOutManager& bufferOutManager) + { + FMTBufferOutInfo res(bufferOutManager); + SF_TRY(BufferOutInfo::Init(res)); + return res; + } + public: std::size_t NoStride = 0; std::size_t Indent = 0; @@ -56,7 +64,9 @@ namespace StreamFormat::FMT::Detail [[nodiscard]] constexpr inline std::expected PushbackCheckIndent(const TChar c) { SF_TRY(BufferOutManip(Buffer).Pushback(c)); - if (c == '\n') return BufferOutManip(Buffer).Pushback(' ', Buffer.Indent); + if (c == '\n') + { return BufferOutManip(Buffer).Pushback(' ', Buffer.Indent); } + return {}; } }; diff --git a/src/StreamFormat/FMT/Buffer/FMTBufferReadManip.h b/src/StreamFormat/FMT/Buffer/FMTBufferReadManip.h index 288edb51..55d3de89 100644 --- a/src/StreamFormat/FMT/Buffer/FMTBufferReadManip.h +++ b/src/StreamFormat/FMT/Buffer/FMTBufferReadManip.h @@ -23,9 +23,8 @@ namespace StreamFormat::FMT::Detail BufferShiftReadManip shiftManip(Buffer); Detail::BufferTestAccess access(Buffer); Detail::BufferTestManip manip(Buffer); - T res = 0; - shiftManip.SkipShiftBeginSpace(shift); + SF_TRY(shiftManip.SkipShiftBeginSpace(shift)); bool sign = false; if constexpr (std::is_signed_v) @@ -36,6 +35,7 @@ namespace StreamFormat::FMT::Detail access.IsADigit(); + T res = (T)0; while (access.IsADigit()) { char c = SF_TRY(BufferManip(Buffer).GetAndForward()); @@ -43,9 +43,10 @@ namespace StreamFormat::FMT::Detail --shift.Size; } - shiftManip.SkipShiftEnd(shift); + SF_TRY(shiftManip.SkipShiftEnd(shift)); i = sign ? -res : res; + return {}; } public: template @@ -55,9 +56,9 @@ namespace StreamFormat::FMT::Detail Detail::BufferTestAccess access(Buffer); Detail::BufferTestManip manip(Buffer); - shiftManip.SkipShiftBeginSpace(shift); + SF_TRY(shiftManip.SkipShiftBeginSpace(shift)); - bool sign = manip.IsEqualToForward('-'); + bool sign = SF_TRY(manip.IsEqualToForward('-')); if (sign) --shift.Size; T intpart = static_cast(0); @@ -99,7 +100,7 @@ namespace StreamFormat::FMT::Detail dec /= 10; } - shiftManip.SkipShiftEnd(shift); + SF_TRY(shiftManip.SkipShiftEnd(shift)); t = sign ? - intpart - dec : intpart + dec; return {}; @@ -116,13 +117,15 @@ namespace StreamFormat::FMT::Detail shift.Size -= sizeof(T) * 8; if (base_prefix != '\0') shift.Size -= 2; - shiftManip.SkipShiftBeginSpace(shift); + SF_TRY(shiftManip.SkipShiftBeginSpace(shift)); if (base_prefix != '\0') - { manip.SkipOneOf('0'); manip.SkipOneOf(base_prefix); } - - T res = 0; + { + SF_TRY(manip.SkipOneOf('0')); + SF_TRY(manip.SkipOneOf(base_prefix)); + } + T res = (T)0; while (digitLUT(Buffer.Get()) != std::numeric_limits::max()) { res = res << digitSize; @@ -130,9 +133,10 @@ namespace StreamFormat::FMT::Detail BufferManip(Buffer).ForceForward(); } - shiftManip.SkipShiftEnd(shift); + SF_TRY(shiftManip.SkipShiftEnd(shift)); i = res; + return {}; } protected: @@ -223,12 +227,12 @@ namespace StreamFormat::FMT::Detail template [[nodiscard]] inline std::expected ReadCharArray(const CharStr (&str)[SIZE], ShiftInfo shift = ShiftInfo{}) { - ReadCharPtr(str, SIZE, 0, shift); + return ReadCharPtr(str, SIZE, 0, shift); } template [[nodiscard]] inline std::expected ReadCharBound(const CharStr* begin, const CharStr* end, ShiftInfo shift = ShiftInfo{}) { - ReadCharPtr(begin, end - begin, 0, shift); + return ReadCharPtr(begin, end - begin, 0, shift); } }; } diff --git a/src/StreamFormat/FMT/Buffer/FMTBufferWriteManip.h b/src/StreamFormat/FMT/Buffer/FMTBufferWriteManip.h index a91f53b7..67bfef53 100644 --- a/src/StreamFormat/FMT/Buffer/FMTBufferWriteManip.h +++ b/src/StreamFormat/FMT/Buffer/FMTBufferWriteManip.h @@ -31,21 +31,24 @@ namespace StreamFormat::FMT::Detail shift.Size -= nbDigit; if (i < 0) --shift.Size; - if (shift.Size <= 0) return BufferWriteManip(Buffer).FastWriteInteger(i); + if (shift.Size <= 0) + { return BufferWriteManip(Buffer).FastWriteInteger(i); } - if (!shift.Print.BeforeIsADigit()) BufferShiftWriteManip(Buffer).WriteShiftBegin(shift); + if (!shift.Print.BeforeIsADigit()) + { SF_TRY(BufferShiftWriteManip(Buffer).WriteShiftBegin(shift)); } if (i < 0) { - BufferOutManip(Buffer).Pushback('-'); + SF_TRY(BufferOutManip(Buffer).Pushback('-')); i = -i; } - if (shift.Print.BeforeIsADigit()) BufferShiftWriteManip(Buffer).WriteShiftRightAll(shift); + if (shift.Print.BeforeIsADigit()) + { SF_TRY(BufferShiftWriteManip(Buffer).WriteShiftRightAll(shift)); } if (i == 0) - BufferOutManip(Buffer).Pushback('0'); + { SF_TRY(BufferOutManip(Buffer).Pushback('0')); } else { - BufferOutManip(Buffer).Forward(nbDigit); + SF_TRY(BufferOutManip(Buffer).Forward(nbDigit)); std::int32_t nbDigit_ = nbDigit; while (nbDigit_ > 0) { @@ -53,12 +56,13 @@ namespace StreamFormat::FMT::Detail i /= 10; nbDigit_--; } - BufferOutManip(Buffer).Forward(nbDigit); + SF_TRY(BufferOutManip(Buffer).Forward(nbDigit)); } - BufferShiftWriteManip(Buffer).WriteShiftEnd(shift); + SF_TRY(BufferShiftWriteManip(Buffer).WriteShiftEnd(shift)); shift.Print.Before = oldBefore; + return {}; } public: @@ -74,22 +78,25 @@ namespace StreamFormat::FMT::Detail shift.Size -= nbDigit + floatPrecision + 1; if (i < 0) --shift.Size; - if (shift.Size <= 0) return BufferWriteManip(Buffer).FastWriteFloat(i, floatPrecision); + if (shift.Size <= 0) + { return BufferWriteManip(Buffer).FastWriteFloat(i, floatPrecision); } - if (!shift.Print.BeforeIsADigit()) BufferShiftWriteManip(Buffer).WriteShiftBegin(shift); + if (!shift.Print.BeforeIsADigit()) + { SF_TRY(BufferShiftWriteManip(Buffer).WriteShiftBegin(shift)); } if (i < 0) { - BufferOutManip(Buffer).Pushback('-'); + SF_TRY(BufferOutManip(Buffer).Pushback('-')); i = -i; } - if (shift.Print.BeforeIsADigit()) BufferShiftWriteManip(Buffer).WriteShiftRightAll(shift); + if (shift.Print.BeforeIsADigit()) + { SF_TRY(BufferShiftWriteManip(Buffer).WriteShiftRightAll(shift)); } T k = std::trunc(i); if (k == 0) - BufferOutManip(Buffer).Pushback('0'); + { SF_TRY(BufferOutManip(Buffer).Pushback('0')); } else { - BufferOutManip(Buffer).Forward(nbDigit); + SF_TRY(BufferOutManip(Buffer).Forward(nbDigit)); std::int32_t nbDigit_ = nbDigit; while (nbDigit_ > 0) { @@ -97,21 +104,22 @@ namespace StreamFormat::FMT::Detail k /= 10; nbDigit_--; } - BufferOutManip(Buffer).Forward(nbDigit); + SF_TRY(BufferOutManip(Buffer).Forward(nbDigit)); } - BufferOutManip(Buffer).Pushback('.'); + SF_TRY(BufferOutManip(Buffer).Pushback('.')); i -= k; while (floatPrecision-- != 0) { T decimal = std::trunc(i *= 10); - BufferOutManip(Buffer).Pushback((char)decimal + '0'); + SF_TRY(BufferOutManip(Buffer).Pushback((char)decimal + '0')); i -= decimal; } - BufferShiftWriteManip(Buffer).WriteShiftEnd(shift); + SF_TRY(BufferShiftWriteManip(Buffer).WriteShiftEnd(shift)); shift.Print.Before = oldBefore; + return {}; } public: @@ -136,18 +144,19 @@ namespace StreamFormat::FMT::Detail if (base_prefix != '\0') { - BufferOutManip(Buffer).Pushback('0'); - BufferOutManip(Buffer).Pushback(base_prefix); + SF_TRY(BufferOutManip(Buffer).Pushback('0')); + SF_TRY(BufferOutManip(Buffer).Pushback(base_prefix)); } - manip.Forward(digitCount); + SF_TRY(manip.Forward(digitCount)); std::int32_t k = digitCount + 1; while (--k != 0) { manip.ForceSetInverse(lut[i & (0b1 << digitSize)]); i = i >> digitSize; } - manip.Forward(digitCount); + SF_TRY(manip.Forward(digitCount)); + return {}; } public: @@ -203,25 +212,26 @@ namespace StreamFormat::FMT::Detail } const CharStr* const end = str; - BufferWriteManip(Buffer).FastWriteCharArray(begin, end - begin); + SF_TRY(BufferWriteManip(Buffer).FastWriteCharArray(begin, end - begin)); if (size > 0 && *str == '\n') { - FMTBufferOutManip(Buffer).NewLineIndent(); + SF_TRY(FMTBufferOutManip(Buffer).NewLineIndent()); ++str; --size; } } + return {}; } template [[nodiscard]] inline std::expected WriteIndentCharBound(const CharStr* begin, const CharStr* end) { - WriteIndentCharPtr(begin, end - begin); + return WriteIndentCharPtr(begin, end - begin); } template [[nodiscard]] inline std::expected WriteIndentString(std::basic_string_view str) { - WriteIndentCharPtr(str.data(), str.size()); + return WriteIndentCharPtr(str.data(), str.size()); } template @@ -230,22 +240,23 @@ namespace StreamFormat::FMT::Detail if (shift.Size <= 0) return BufferWriteManip(Buffer).FastWriteCharArray(str, size); - BufferOutManip(Buffer).Reserve(std::max(static_cast(shift.Size), size)); + SF_TRY(BufferOutManip(Buffer).Reserve(std::max(static_cast(shift.Size), size))); if (static_cast(shift.Size) > size) { shift.Size -= static_cast(size); - BufferShiftWriteManip(Buffer).WriteShiftBegin(shift); + SF_TRY(BufferShiftWriteManip(Buffer).WriteShiftBegin(shift)); - BufferWriteManip(Buffer).FastWriteCharArray(str, size); + SF_TRY(BufferWriteManip(Buffer).FastWriteCharArray(str, size)); - BufferShiftWriteManip(Buffer).WriteShiftEnd(shift); + SF_TRY(BufferShiftWriteManip(Buffer).WriteShiftEnd(shift)); } else { - BufferWriteManip(Buffer).FastWriteCharArray(str, size); + SF_TRY(BufferWriteManip(Buffer).FastWriteCharArray(str, size)); } + return {}; } template [[nodiscard]] inline std::expected WriteCharBound(const CharStr* begin, const CharStr* end, ShiftInfo& shift) diff --git a/src/StreamFormat/FMT/Buffer/Utils/BufferGlobberManip.h b/src/StreamFormat/FMT/Buffer/Utils/BufferGlobberManip.h index 5c249bc3..4c1cc671 100644 --- a/src/StreamFormat/FMT/Buffer/Utils/BufferGlobberManip.h +++ b/src/StreamFormat/FMT/Buffer/Utils/BufferGlobberManip.h @@ -18,23 +18,23 @@ namespace StreamFormat::FMT::Detail private: [[nodiscard]] static std::expected BufferInExecGlob_(BufferInfo& bufferIn, BufferInfo& glob) { - if (BufferAccess(glob).IsEndOfString()) return bufferIn.CurrentPos; + if (BufferAccess(glob).IsEndOfString()) { return bufferIn.CurrentPos; } - if (BufferAccess(bufferIn).IsEndOfString()) return nullptr; + if (BufferAccess(bufferIn).IsEndOfString()) { return nullptr; } if (BufferTestAccess(glob).IsEqualTo('?')) { - BufferManip(glob).Forward(); - BufferManip(bufferIn).Forward(); + SF_TRY(BufferManip(glob).Forward()); + SF_TRY(BufferManip(bufferIn).Forward()); return BufferInExecGlob_(bufferIn, glob); } else if (BufferTestAccess(glob).IsEqualTo('*')) { - BufferManip(glob).Forward(); + SF_TRY(BufferManip(glob).Forward()); const TChar* further = SF_TRY(BufferInExecGlob_(bufferIn, glob)); while (BufferAccess(bufferIn).CanMoveForward()) { - BufferManip(bufferIn).Forward(); + SF_TRY(BufferManip(bufferIn).Forward()); const TChar* last = SF_TRY(BufferInExecGlob_(bufferIn, glob)); if (last > further || further == nullptr) further = last; } @@ -42,9 +42,9 @@ namespace StreamFormat::FMT::Detail } else if (BufferTestAccess(glob).IsEqualTo('[')) { - BufferManip(bufferIn).Forward(); + SF_TRY(BufferManip(bufferIn).Forward()); const TChar* begin = glob.CurrentPos; - BufferTestManip(glob).GoToForward(']'); + SF_TRY(BufferTestManip(glob).GoToForward(']')); const TChar* end = glob.CurrentPos; BufferInfoView charSet(begin, end - begin); @@ -84,8 +84,8 @@ namespace StreamFormat::FMT::Detail if (bufferIn.Get() == glob.Get()) { - BufferManip(glob).Forward(); - BufferManip(bufferIn).Forward(); + SF_TRY(BufferManip(glob).Forward()); + SF_TRY(BufferManip(bufferIn).Forward()); return BufferInExecGlob_(bufferIn, glob); } return nullptr; @@ -97,6 +97,7 @@ namespace StreamFormat::FMT::Detail const TChar* furtherPointMatched = SF_TRY(BufferInExecGlob_(bufferIn, glob)); if (furtherPointMatched != nullptr) bufferIn.CurrentPos = furtherPointMatched; + return {}; } }; diff --git a/src/StreamFormat/FMT/Buffer/Utils/BufferShiftManip.h b/src/StreamFormat/FMT/Buffer/Utils/BufferShiftManip.h index 49e29903..349ced5f 100644 --- a/src/StreamFormat/FMT/Buffer/Utils/BufferShiftManip.h +++ b/src/StreamFormat/FMT/Buffer/Utils/BufferShiftManip.h @@ -23,24 +23,29 @@ namespace StreamFormat::FMT::Detail SF_TRY(BufferOutManip(Buffer).Pushback(shift.Print.Before, shift.Size - shift_)); shift.Size = shift_; } + + return {}; } [[nodiscard]] inline std::expected WriteShiftCenterEnd(Detail::ShiftInfo& shift) { if (shift.Type == Detail::ShiftInfo::ShiftType::CenterRight || shift.Type == Detail::ShiftInfo::ShiftType::CenterLeft) return BufferOutManip(Buffer).Pushback(shift.Print.After, shift.Size); + return {}; } [[nodiscard]] inline std::expected WriteShiftRightAll(Detail::ShiftInfo& shift) { if (shift.Type == Detail::ShiftInfo::ShiftType::Right) return BufferOutManip(Buffer).Pushback(shift.Print.Before, shift.Size); + return {}; } [[nodiscard]] inline std::expected WriteShiftLeftAll(Detail::ShiftInfo& shift) { if (shift.Type == Detail::ShiftInfo::ShiftType::Left) return BufferOutManip(Buffer).Pushback(shift.Print.After, shift.Size); + return {}; } [[nodiscard]] inline std::expected WriteShiftBegin(Detail::ShiftInfo& shift) @@ -70,21 +75,28 @@ namespace StreamFormat::FMT::Detail if (shift.Print.BeforeIsADigit() == false) return {}; if (shift.Type == Detail::ShiftInfo::ShiftType::Right || shift.Type == Detail::ShiftInfo::ShiftType::CenterLeft || shift.Type == Detail::ShiftInfo::ShiftType::CenterRight) + { + while (Buffer.Get() == ' ') { SF_TRY(BufferManip(Buffer).Forward()); --shift.Size; } + } + return {}; } [[nodiscard]] std::expected SkipShiftEnd(Detail::ShiftInfo& shift) { if (shift.Type == Detail::ShiftInfo::ShiftType::Left || shift.Type == Detail::ShiftInfo::ShiftType::CenterLeft || shift.Type == Detail::ShiftInfo::ShiftType::CenterRight) + { while (Buffer.Get() == ' ' && shift.Size > 0) { SF_TRY(BufferManip(Buffer).Forward()); --shift.Size; } + } + return {}; } }; } diff --git a/src/StreamFormat/FMT/Buffer/Utils/BufferUtils.h b/src/StreamFormat/FMT/Buffer/Utils/BufferUtils.h index 8b8da918..f582253e 100644 --- a/src/StreamFormat/FMT/Buffer/Utils/BufferUtils.h +++ b/src/StreamFormat/FMT/Buffer/Utils/BufferUtils.h @@ -65,7 +65,7 @@ namespace StreamFormat::FMT::Detail if (Detail::BufferTestAccess(buffer).IsEqualTo('"')) break; - Detail::BufferTestManip(buffer).SkipOneOf('\\'); + SF_TRY(Detail::BufferTestManip(buffer).SkipOneOf('\\')); switch (buffer.Get()) { // TODO : Do all others escape char diff --git a/src/StreamFormat/FMT/Context/BasicContext/BasicArgsInterface.h b/src/StreamFormat/FMT/Context/BasicContext/BasicArgsInterface.h index 01b0cf74..9171052f 100644 --- a/src/StreamFormat/FMT/Context/BasicContext/BasicArgsInterface.h +++ b/src/StreamFormat/FMT/Context/BasicContext/BasicArgsInterface.h @@ -53,10 +53,11 @@ namespace StreamFormat::FMT::Detail } template - [[nodiscard]] std::expected RunFuncFromTypeAtIndex(std::int32_t idx, std::function func) + [[nodiscard]] std::expected RunFuncFromTypeAtIndex(std::int32_t idx, std::function(const T&)> func) { const T* value = SF_TRY(GetTypeAt(idx)); - func(*value); + SF_TRY(func(*value)); + return {}; } }; diff --git a/src/StreamFormat/FMT/Context/BasicContext/BasicContext.h b/src/StreamFormat/FMT/Context/BasicContext/BasicContext.h index 452a9aa7..0371e5eb 100644 --- a/src/StreamFormat/FMT/Context/BasicContext/BasicContext.h +++ b/src/StreamFormat/FMT/Context/BasicContext/BasicContext.h @@ -116,17 +116,21 @@ namespace StreamFormat::FMT::Context while (!Detail::BufferAccess(Format).IsEndOfString()) { const TChar* beginContinousString = Format.CurrentPos; - std::size_t sizeContinousString = 0; + std::size_t sizeContinousString = 0; while (Detail::BufferAccess(Format).IsEndOfString() == false && Detail::BufferTestAccess(Format).IsEqualTo('{') == false) { ++sizeContinousString; - Detail::BufferManip(Format).Forward(); + SF_TRY(Detail::BufferManip(Format).Forward()); } SF_TRY(Executor.ExecRawString(std::basic_string_view(beginContinousString, sizeContinousString))); if (Detail::BufferAccess(Format).IsEndOfString() == false && Detail::BufferTestAccess(Format).IsEqualTo('{')) - { Parse(); } + { + SF_TRY(Parse()); + } } + + return {}; } template @@ -159,6 +163,8 @@ namespace StreamFormat::FMT::Context return ArgsInterface.GetIntAt(formatIdx); else if constexpr (std::is_convertible_v>) return ArgsInterface.GetStringAt(formatIdx); + + return std::unexpected(FMTResult::Context_ArgumentIndexExpected); } } diff --git a/src/StreamFormat/FMT/Context/BasicContext/BasicContextParse-impl.h b/src/StreamFormat/FMT/Context/BasicContext/BasicContextParse-impl.h index d380e9b1..8b5e53ef 100644 --- a/src/StreamFormat/FMT/Context/BasicContext/BasicContextParse-impl.h +++ b/src/StreamFormat/FMT/Context/BasicContext/BasicContextParse-impl.h @@ -59,6 +59,8 @@ namespace StreamFormat::FMT::Context else if (manip.IsEqualToForward('N')) { Executor.Data.NextOverride = SF_TRY(ParseNextOverrideFormatData()); } + + return {}; } template @@ -76,6 +78,7 @@ namespace StreamFormat::FMT::Context Executor.Data.Shift.Print.After = SF_TRY(Detail::BufferManip(Format).GetAndForward()); } } + return {}; } template @@ -202,15 +205,16 @@ namespace StreamFormat::FMT::Context manip.SkipAllSpaces(); if (access.IsUpperCase()) - ParseFormatDataBase(); + { SF_TRY(ParseFormatDataBase()); } else if (!access.IsLowerCase()) - ParseFormatDataSpecial(); + { SF_TRY(ParseFormatDataSpecial()); } else - ParseFormatDataCustom(); + { SF_TRY(ParseFormatDataCustom()); } Detail::FMTBufferParamsManip(Format).ParamGoTo(','); - Detail::BufferTestManip(Format).IsEqualToForward(','); + SF_TRY(Detail::BufferTestManip(Format).IsEqualToForward(',')); } + return {}; } template @@ -276,16 +280,18 @@ namespace StreamFormat::FMT::Context if (Detail::BufferTestAccess(Format).IsEqualTo(':', '{')) { - Detail::BufferManip(Format).Forward(); - ParseFormatData(); + SF_TRY(Detail::BufferManip(Format).Forward()); + SF_TRY(ParseFormatData()); } - ArgsInterface.RunTypeAtIndex(formatIdx); + SF_TRY(ArgsInterface.RunTypeAtIndex(formatIdx)); if (Executor.Data.KeepNewStyle == false) - Executor.TextManager.Reload(saveTextProperties); + { SF_TRY(Executor.TextManager.Reload(saveTextProperties)); } Executor.Data = saveFormatData; + + return {}; } template diff --git a/src/StreamFormat/FMT/Context/BasicContext/TextPropertiesManager-impl.h b/src/StreamFormat/FMT/Context/BasicContext/TextPropertiesManager-impl.h index a4f722a9..9d41255f 100644 --- a/src/StreamFormat/FMT/Context/BasicContext/TextPropertiesManager-impl.h +++ b/src/StreamFormat/FMT/Context/BasicContext/TextPropertiesManager-impl.h @@ -14,19 +14,19 @@ namespace StreamFormat::FMT::Detail [[nodiscard]] std::expected Detail::TextPropertiesManager::ApplyColorOnIndex(Context::BasicContext& context, std::int32_t index) { SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextColor::Color& data) { this->ReloadColor(data); })); + index, [this](const Detail::TextProperties::TextColor::Color& data) -> std::expected { this->ReloadColor(data); return {}; })); SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextColor::BasicColorFG& data) { this->AskApplyColor(data); })); + index, [this](const Detail::TextProperties::TextColor::BasicColorFG& data) -> std::expected { this->AskApplyColor(data); return {}; })); SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextColor::BasicColorBG& data) { this->AskApplyColor(data); })); + index, [this](const Detail::TextProperties::TextColor::BasicColorBG& data) -> std::expected { this->AskApplyColor(data); return {}; })); SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextColor::ColorCubeFG& data) { this->AskApplyColor(data); })); + index, [this](const Detail::TextProperties::TextColor::ColorCubeFG& data) -> std::expected { this->AskApplyColor(data); return {}; })); SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextColor::ColorCubeBG& data) { this->AskApplyColor(data); })); + index, [this](const Detail::TextProperties::TextColor::ColorCubeBG& data) -> std::expected { this->AskApplyColor(data); return {}; })); SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextColor::Color24bFG& data) { this->AskApplyColor(data); })); + index, [this](const Detail::TextProperties::TextColor::Color24bFG& data) -> std::expected { this->AskApplyColor(data); return {}; })); SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextColor::Color24bBG& data) { this->AskApplyColor(data); })); + index, [this](const Detail::TextProperties::TextColor::Color24bBG& data) -> std::expected { this->AskApplyColor(data); return {}; })); return {}; } @@ -34,9 +34,9 @@ namespace StreamFormat::FMT::Detail [[nodiscard]] std::expected Detail::TextPropertiesManager::ApplyFrontOnIndex(Context::BasicContext& context, std::int32_t index) { SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextFront::Front& data) { this->ReloadFront(data); })); + index, [this](const Detail::TextProperties::TextFront::Front& data) -> std::expected { this->ReloadFront(data); return {}; })); SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextFront::FrontID& data) { this->AskApplyFront(data); })); + index, [this](const Detail::TextProperties::TextFront::FrontID& data) -> std::expected { this->AskApplyFront(data); return {}; })); return {}; } @@ -44,65 +44,68 @@ namespace StreamFormat::FMT::Detail [[nodiscard]] std::expected Detail::TextPropertiesManager::ApplyStyleOnIndex(Context::BasicContext& context, std::int32_t index) { SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextStyle::Style& data) { return this->ReloadStyle(data); })); + index, [this](const Detail::TextProperties::TextStyle::Style& data) -> std::expected { return this->ReloadStyle(data); return {}; })); SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextStyle::Intensity& data) { return this->AskApplyStyle(data); })); + index, [this](const Detail::TextProperties::TextStyle::Intensity& data) -> std::expected { return this->AskApplyStyle(data); return {}; })); SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextStyle::Italic& data) { return this->AskApplyStyle(data); })); + index, [this](const Detail::TextProperties::TextStyle::Italic& data) -> std::expected { return this->AskApplyStyle(data); return {}; })); SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextStyle::Underline& data) { return this->AskApplyStyle(data); })); + index, [this](const Detail::TextProperties::TextStyle::Underline& data) -> std::expected { return this->AskApplyStyle(data); return {}; })); SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextStyle::Blink& data) { return this->AskApplyStyle(data); })); + index, [this](const Detail::TextProperties::TextStyle::Blink& data) -> std::expected { return this->AskApplyStyle(data); return {}; })); SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextStyle::Inverted& data) { return this->AskApplyStyle(data); })); + index, [this](const Detail::TextProperties::TextStyle::Inverted& data) -> std::expected { return this->AskApplyStyle(data); return {}; })); SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextStyle::Ideogram& data) { return this->AskApplyStyle(data); })); + index, [this](const Detail::TextProperties::TextStyle::Ideogram& data) -> std::expected { return this->AskApplyStyle(data); return {}; })); SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextStyle::Script& data) { return this->AskApplyStyle(data); })); + index, [this](const Detail::TextProperties::TextStyle::Script& data) -> std::expected { return this->AskApplyStyle(data); return {}; })); SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextStyle::UnderlineColor::ColorCube& data) { this->AskApplyStyle(data); })); + index, [this](const Detail::TextProperties::TextStyle::UnderlineColor::ColorCube& data) -> std::expected { this->AskApplyStyle(data); return {}; })); SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextStyle::UnderlineColor::Color24b& data) { this->AskApplyStyle(data); })); + index, [this](const Detail::TextProperties::TextStyle::UnderlineColor::Color24b& data) -> std::expected { this->AskApplyStyle(data); return {}; })); return {}; } template [[nodiscard]] std::expected Detail::TextPropertiesManager::ParseColor(Context::BasicContext& context) { - if (BufferTestManip(context.Format).IsEqualToForward(':')) + if (BufferTestAccess(context.Format).IsEqualTo(':')) { + SF_TRY(BufferManip(context.Format).Forward()); BufferTestManip(context.Format).SkipAllSpaces(); - if (BufferTestManip(context.Format).IsEqualToForward('{')) + if (BufferTestAccess(context.Format).IsEqualTo('{')) { + SF_TRY(BufferManip(context.Format).Forward()); std::int32_t idx = SF_TRY(context.GetFormatIndex()); - ApplyColorOnIndex(context, idx); - BufferTestManip(context.Format).IsEqualToForward('}'); + SF_TRY(ApplyColorOnIndex(context, idx)); + SF_TRY(BufferTestManip(context.Format).IsEqualToForward('}')); } else { auto colorFg = GetColorCode(context.Format); FMTBufferParamsManip(context.Format).ParamGoTo('-', ','); - if (BufferTestManip(context.Format).IsEqualToForward('-')) + if (BufferTestAccess(context.Format).IsEqualTo('-')) { + SF_TRY(BufferManip(context.Format).Forward()); BufferTestManip(context.Format).SkipAllSpaces(); auto colorBg = GetColorCode(context.Format); if (colorBg.has_value() && colorFg.has_value()) - return AskApplyColor(Detail::TextProperties::TextColor::BasicColor{colorFg.value(), colorBg.value()}); + { return AskApplyColor(Detail::TextProperties::TextColor::BasicColor{colorFg.value(), colorBg.value()}); } else - return ReloadDefaultColor(); + { return ReloadDefaultColor(); } } else { if (colorFg.has_value()) - return AskApplyColor(colorFg.value()); + { return AskApplyColor(colorFg.value()); } else - return ReloadDefaultColor(); + { return ReloadDefaultColor(); } } } } else - return ReloadDefaultColor(); + { return ReloadDefaultColor(); } return {}; } @@ -118,8 +121,9 @@ namespace StreamFormat::FMT::Detail while (l) { BufferTestManip(context.Format).SkipAllSpaces(); - if (BufferTestManip(context.Format).IsEqualToForward('{')) + if (BufferTestAccess(context.Format).IsEqualTo('{')) { + SF_TRY(BufferManip(context.Format).Forward()); std::int32_t idx = SF_TRY(context.GetFormatIndex()); ApplyStyleOnIndex(context, idx); BufferTestManip(context.Format).IsEqualToForward('}'); diff --git a/src/StreamFormat/FMT/Context/FormatterExecutor/BasicFormatterExecutor.h b/src/StreamFormat/FMT/Context/FormatterExecutor/BasicFormatterExecutor.h index 3835e65c..eb6010ef 100644 --- a/src/StreamFormat/FMT/Context/FormatterExecutor/BasicFormatterExecutor.h +++ b/src/StreamFormat/FMT/Context/FormatterExecutor/BasicFormatterExecutor.h @@ -51,9 +51,11 @@ namespace StreamFormat::FMT::Context template [[nodiscard]] inline std::expected WriteType(Type&& type, Rest&&... rest) { - FormatterType>::Type, M_Type>::Format(std::forward(type), *this); + auto&& formatErr = FormatterType>::Type, M_Type>::Format(std::forward(type), *this); + SF_TRY(formatErr); if constexpr (sizeof...(rest) > 0) - WriteType(std::forward(rest)...); + { SF_TRY(WriteType(std::forward(rest)...)); } + return {}; } }; } @@ -72,10 +74,11 @@ namespace StreamFormat::FMT::Context [[nodiscard]] std::expected BasicFormatterExecutor::Terminate() { Detail::BufferOutManip(BufferOut).ComputeGeneratedSize(); - + // End char not included in buffer manager context to deduce size correctly - if (Detail::BufferOutManip(BufferOut).Reserve(1)) - Detail::BufferOutManip(BufferOut).Pushback('\0'); + SF_TRY(Detail::BufferOutManip(BufferOut).Pushback('\0')); + + return {}; } template @@ -85,6 +88,7 @@ namespace StreamFormat::FMT::Context auto indent = Data.Specifiers.Get("indent"); if (indent != nullptr) BufferOut.Indent = indent->AsNumber; + return {}; } template @@ -95,15 +99,15 @@ namespace StreamFormat::FMT::Context Detail::TextProperties::Properties saveTextProperties = TextManager.Save(); Context::BasicContext context(*this, format, argsInterface); - context.Run(); - TextManager.Reload(saveTextProperties); + SF_TRY(context.Run()); + return TextManager.Reload(saveTextProperties); } template template [[nodiscard]] std::expected BasicFormatterExecutor::Run(Format&& formatInput, Args&&... args) { - Run_(Detail::BufferInfoView{formatInput}, std::forward(args)...); + return Run_(Detail::BufferInfoView{formatInput}, std::forward(args)...); } } diff --git a/src/StreamFormat/FMT/Context/FormatterExecutor/FormatBasics-impl.h b/src/StreamFormat/FMT/Context/FormatterExecutor/FormatBasics-impl.h index 2a379fd6..0e9b606c 100644 --- a/src/StreamFormat/FMT/Context/FormatterExecutor/FormatBasics-impl.h +++ b/src/StreamFormat/FMT/Context/FormatterExecutor/FormatBasics-impl.h @@ -16,9 +16,10 @@ namespace StreamFormat::FMT [[nodiscard]] static std::expected Format(const typename FormatterExecutor::Detail::template FormatSpecifier& specifier, FormatterExecutor& executor) { if (specifier.ValueIsText) - executor.Run("{ '{}', '{}' }", specifier.Name, specifier.AsText); + { SF_TRY(executor.Run("{ '{}', '{}' }", specifier.Name, specifier.AsText)); } else - executor.Run("{ '{}', '{}' }", specifier.Name, specifier.AsNumber); + { SF_TRY(executor.Run("{ '{}', '{}' }", specifier.Name, specifier.AsNumber)); } + return {}; } }; @@ -40,7 +41,7 @@ namespace StreamFormat::FMT if (size == std::numeric_limits::max()) { return std::unexpected(FMTResult::GivenArgs_UnableToDeduceSize); } - Detail::BufferWriteManip(executor.BufferOut).FastWriteString(executor.Data.Specifiers.GetAsText("begin", STDEnumerableUtility::DefaultBegin)); + SF_TRY(Detail::BufferWriteManip(executor.BufferOut).FastWriteString(executor.Data.Specifiers.GetAsText("begin", STDEnumerableUtility::DefaultBegin))); std::basic_string_view join = executor.Data.Specifiers.GetAsText("join", STDEnumerableUtility::DefaultJoin); @@ -51,13 +52,13 @@ namespace StreamFormat::FMT while (itbegin < itend) { if (first) - first = false; + { first = false; } else - Detail::FMTBufferWriteManip(executor.BufferOut).WriteIndentString(join); - executor.WriteType(*itbegin++); + { SF_TRY(Detail::FMTBufferWriteManip(executor.BufferOut).WriteIndentString(join)); } + SF_TRY(executor.WriteType(*itbegin++)); } - Detail::BufferWriteManip(executor.BufferOut).FastWriteString(executor.Data.Specifiers.GetAsText("end", STDEnumerableUtility::DefaultEnd)); + SF_TRY(Detail::BufferWriteManip(executor.BufferOut).FastWriteString(executor.Data.Specifiers.GetAsText("end", STDEnumerableUtility::DefaultEnd))); } template @@ -67,7 +68,8 @@ namespace StreamFormat::FMT size = executor.Data.Specifiers.GetAsNumber("size", size); if (size == std::numeric_limits::max()) size = std::basic_string_view(buffer).size(); - if (executor.Data.Specifiers.Has("array")) return FormatObjectArray(buffer, size, executor); + if (executor.Data.Specifiers.Has("array")) + return FormatObjectArray(buffer, size, executor); if (beginIdx > size) return {}; const T* begin = buffer + beginIdx; @@ -76,14 +78,18 @@ namespace StreamFormat::FMT if (executor.Data.Specifiers.Has("indent")) return Detail::FMTBufferWriteManip(executor.BufferOut).WriteIndentCharPtr(begin, size); - if (executor.Data.PrefixSuffix) Detail::BufferOutManip(executor.BufferOut).Pushback('\"'); + if (executor.Data.PrefixSuffix) + { SF_TRY(Detail::BufferOutManip(executor.BufferOut).Pushback('\"')); } if (executor.Data.HasSpec == false) - Detail::BufferWriteManip(executor.BufferOut).FastWriteCharArray(begin, size); + { SF_TRY(Detail::BufferWriteManip(executor.BufferOut).FastWriteCharArray(begin, size)); } else - Detail::FMTBufferWriteManip(executor.BufferOut).WriteCharPtr(begin, size, executor.Data.Shift); + { SF_TRY(Detail::FMTBufferWriteManip(executor.BufferOut).WriteCharPtr(begin, size, executor.Data.Shift)); } - if (executor.Data.PrefixSuffix) Detail::BufferOutManip(executor.BufferOut).Pushback('\"'); + if (executor.Data.PrefixSuffix) + { SF_TRY(Detail::BufferOutManip(executor.BufferOut).Pushback('\"')); } + + return {}; } } @@ -100,17 +106,19 @@ namespace StreamFormat::FMT if (executor.Data.PrefixSuffix) { if (t == true) - Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("True"); + return Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("True"); else - Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("False"); + return Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("False"); } else { if (t == true) - Detail::BufferManip(executor.BufferOut).Pushback('1'); + return Detail::BufferManip(executor.BufferOut).Pushback('1'); else - Detail::BufferManip(executor.BufferOut).Pushback('0'); + return Detail::BufferManip(executor.BufferOut).Pushback('0'); } + + return {}; } }; @@ -165,6 +173,8 @@ namespace StreamFormat::FMT { return Detail::Forwarders::FormatString(t, std::numeric_limits::max(), executor); } else { Detail::Forwarders::FormatObjectArray(t, std::numeric_limits::max(), executor); } + + return {}; } }; @@ -183,6 +193,8 @@ namespace StreamFormat::FMT { return Detail::Forwarders::FormatObjectArray(t, SIZE, executor); } + + return {}; } }; } diff --git a/src/StreamFormat/FMT/Context/FormatterExecutor/FormatterType.h b/src/StreamFormat/FMT/Context/FormatterExecutor/FormatterType.h index 201d6b30..179becb9 100644 --- a/src/StreamFormat/FMT/Context/FormatterExecutor/FormatterType.h +++ b/src/StreamFormat/FMT/Context/FormatterExecutor/FormatterType.h @@ -27,12 +27,12 @@ namespace StreamFormat::FMT template \ struct StreamFormat::FMT::FormatterType \ { \ - [[nodiscard]] static std::expected Format(const Type& value, FormatterExecutor& executor) { executor.Run(fmt, __VA_ARGS__); } \ + [[nodiscard]] static std::expected Format(const Type& value, FormatterExecutor& executor) { return executor.Run(fmt, __VA_ARGS__); } \ }; #define STREAMFORMAT_AUTO_FORMATTER_T(Type, fmt, ...) \ template \ struct StreamFormat::FMT::FormatterType \ { \ - [[nodiscard]] static std::expected Format(const Type&, FormatterExecutor& executor) { executor.Run(fmt, __VA_ARGS__); } \ + [[nodiscard]] static std::expected Format(const Type&, FormatterExecutor& executor) { return executor.Run(fmt, __VA_ARGS__); } \ }; diff --git a/src/StreamFormat/FMT/Context/FormatterExecutor/STDEnumerable.h b/src/StreamFormat/FMT/Context/FormatterExecutor/STDEnumerable.h index 490dc135..d6abeea6 100644 --- a/src/StreamFormat/FMT/Context/FormatterExecutor/STDEnumerable.h +++ b/src/StreamFormat/FMT/Context/FormatterExecutor/STDEnumerable.h @@ -55,10 +55,10 @@ namespace StreamFormat::FMT template struct FormatterType, FormatterExecutor> { - static void Format(const STDEnumerable& enumerable, FormatterExecutor& executor) + [[nodiscard]] static std::expected Format(const STDEnumerable& enumerable, FormatterExecutor& executor) { - executor.BufferOut.WriteIndentStringView(enumerable.GetStrBegin()); - executor.BufferOut.AddIndent(enumerable.GetStrBegin().size()); + SF_TRY(executor.BufferOut.WriteIndentStringView(enumerable.GetStrBegin())); + SF_TRY(executor.BufferOut.AddIndent(enumerable.GetStrBegin().size())); { // TODO: Why ? ... @@ -67,16 +67,16 @@ namespace StreamFormat::FMT bool first = true; std::for_each_n(enumerable.GetValue().cbegin() + enumerable.GetBeginIdx(), enumerable.GetSize(), [&](const auto& element) { if (first) - first = false; + { first = false; } else - executor.BufferOut.WriteIndentStringView(enumerable.GetStrJoin()); + { SF_TRY(executor.BufferOut.WriteIndentStringView(enumerable.GetStrJoin())); } - executor.WriteType(element); + SF_TRY(executor.WriteType(element)); }); } executor.BufferOut.RemoveIndent(enumerable.GetStrBegin().size()); - executor.BufferOut.WriteIndentStringView(enumerable.GetStrEnd()); + SF_TRY(executor.BufferOut.WriteIndentStringView(enumerable.GetStrEnd())); } }; diff --git a/src/StreamFormat/FMT/Context/FormatterExecutor/UtilityFunctions.h b/src/StreamFormat/FMT/Context/FormatterExecutor/UtilityFunctions.h index 52c843be..c259b86a 100644 --- a/src/StreamFormat/FMT/Context/FormatterExecutor/UtilityFunctions.h +++ b/src/StreamFormat/FMT/Context/FormatterExecutor/UtilityFunctions.h @@ -27,11 +27,11 @@ namespace StreamFormat::FMT using TCharResolved = std::remove_const_t; Detail::FormatterANSITextPropertiesExecutor textPropertiesExecutor; - Detail::FMTBufferOutInfo bufferOut{bufferOutManager}; + Detail::FMTBufferOutInfo bufferOut = SF_TRY(Detail::FMTBufferOutInfo::Create(bufferOutManager)); Context::BasicFormatterExecutor executor(bufferOut, textPropertiesExecutor); - executor.Run(format, std::forward(args)...).value(); - if (newline) BufferOutManip(bufferOut).Pushback('\n').value(); - executor.Terminate().value(); + SF_TRY(executor.Run(format, std::forward(args)...)); + if (newline) SF_TRY(BufferOutManip(bufferOut).Pushback('\n')); + return executor.Terminate(); } template @@ -41,11 +41,11 @@ namespace StreamFormat::FMT using TCharResolved = std::remove_const_t; Detail::FormatterANSITextPropertiesExecutor textPropertiesExecutor; - Detail::FMTBufferOutInfo bufferOut{bufferOutManager}; + Detail::FMTBufferOutInfo bufferOut = SF_TRY(Detail::FMTBufferOutInfo::Create(bufferOutManager)); Context::BasicFormatterExecutor executor(bufferOut, textPropertiesExecutor); - executor.WriteType(std::forward(t)).value(); - if (newline) BufferOutManip(bufferOut).Pushback('\n').value(); - executor.Terminate().value(); + SF_TRY(executor.WriteType(std::forward(t))); + if (newline) SF_TRY(BufferOutManip(bufferOut).Pushback('\n')); + return executor.Terminate(); } } @@ -54,7 +54,7 @@ namespace StreamFormat::FMT [[nodiscard]] std::expected FormatInChar(TChar (&buffer)[BUFFER_SIZE], Format&& formatInput, Args&&... args) { Detail::GivenBufferOutManager bufferOutManager(buffer); - Detail::FormatInManager(bufferOutManager, false, Detail::BufferInfoView{formatInput}, std::forward(args)...).value(); + return Detail::FormatInManager(bufferOutManager, false, Detail::BufferInfoView{formatInput}, std::forward(args)...); } template @@ -62,7 +62,7 @@ namespace StreamFormat::FMT [[nodiscard]] std::expected FormatInChar(TChar* const buffer, const std::size_t bufferSize, Format&& formatInput, Args&&... args) { Detail::GivenBufferOutManager bufferOutManager(buffer, bufferSize); - Detail::FormatInManager(bufferOutManager, false, Detail::BufferInfoView{formatInput}, std::forward(args)...).value(); + return Detail::FormatInManager(bufferOutManager, false, Detail::BufferInfoView{formatInput}, std::forward(args)...); } template @@ -70,7 +70,7 @@ namespace StreamFormat::FMT [[nodiscard]] std::expected CFilePrint(FILE* stream, Format&& formatInput, Args&&... args) { Detail::DynamicBufferOutManager bufferOutManager(256); - Detail::FormatInManager(bufferOutManager, false, Detail::BufferInfoView{formatInput}, std::forward(args)...).value(); + SF_TRY(Detail::FormatInManager(bufferOutManager, false, Detail::BufferInfoView{formatInput}, std::forward(args)...)); std::fwrite(bufferOutManager.GetBuffer(), bufferOutManager.GetLastGeneratedDataSize(), 1, stream); std::fflush(stream); @@ -81,7 +81,7 @@ namespace StreamFormat::FMT [[nodiscard]] std::expected CFilePrintLn(FILE* stream, Format&& formatInput, Args&&... args) { Detail::DynamicBufferOutManager bufferOutManager(256); - Detail::FormatInManager(bufferOutManager, true, Detail::BufferInfoView{formatInput}, std::forward(args)...).value(); + SF_TRY(Detail::FormatInManager(bufferOutManager, true, Detail::BufferInfoView{formatInput}, std::forward(args)...)); std::fwrite(bufferOutManager.GetBuffer(), bufferOutManager.GetLastGeneratedDataSize(), 1, stream); std::fflush(stream); @@ -92,7 +92,7 @@ namespace StreamFormat::FMT [[nodiscard]] std::expected FilePrint(std::basic_ostream& stream, Format&& formatInput, Args&&... args) { Detail::DynamicBufferOutManager bufferOutManager(256); - Detail::FormatInManager(bufferOutManager, false, Detail::BufferInfoView{formatInput}, std::forward(args)...).value(); + SF_TRY(Detail::FormatInManager(bufferOutManager, false, Detail::BufferInfoView{formatInput}, std::forward(args)...)); stream.write(bufferOutManager.GetBuffer(), bufferOutManager.GetLastGeneratedDataSize()); stream.flush(); @@ -103,7 +103,7 @@ namespace StreamFormat::FMT [[nodiscard]] std::expected FilePrintLn(std::basic_ostream& stream, Format&& formatInput, Args&&... args) { Detail::DynamicBufferOutManager bufferOutManager(256); - Detail::FormatInManager(bufferOutManager, true, Detail::BufferInfoView{formatInput}, std::forward(args)...).value(); + SF_TRY(Detail::FormatInManager(bufferOutManager, true, Detail::BufferInfoView{formatInput}, std::forward(args)...)); stream.write(bufferOutManager.GetBuffer(), bufferOutManager.GetLastGeneratedDataSize()); stream.flush(); @@ -114,7 +114,7 @@ namespace StreamFormat::FMT [[nodiscard]] std::expected FormatInString(std::basic_string& str, Format&& formatInput, Args&&... args) { Detail::DynamicBufferOutManager bufferOutManager(256); - Detail::FormatInManager(bufferOutManager, false, Detail::BufferInfoView{formatInput}, std::forward(args)...).value(); + SF_TRY(Detail::FormatInManager(bufferOutManager, false, Detail::BufferInfoView{formatInput}, std::forward(args)...)); str = bufferOutManager.GetLastGeneratedString(); } @@ -123,7 +123,7 @@ namespace StreamFormat::FMT [[nodiscard]] inline std::expected, FMTResult> FormatString(Format&& formatInput, Args&&... args) { Detail::DynamicBufferOutManager bufferOutManager(256); - Detail::FormatInManager(bufferOutManager, false, Detail::BufferInfoView{formatInput}, std::forward(args)...).value(); + SF_TRY(Detail::FormatInManager(bufferOutManager, false, Detail::BufferInfoView{formatInput}, std::forward(args)...)); return bufferOutManager.GetLastGeneratedString(); } @@ -134,7 +134,7 @@ namespace StreamFormat::FMT [[nodiscard]] std::expected FormatInChar(TChar (&buffer)[BUFFER_SIZE], T&& t) { Detail::GivenBufferOutManager bufferOutManager(buffer, BUFFER_SIZE); - Detail::FormatInManager(bufferOutManager, false, std::forward(t)); + return Detail::FormatInManager(bufferOutManager, false, std::forward(t)); } template @@ -142,7 +142,7 @@ namespace StreamFormat::FMT [[nodiscard]] std::expected FormatInChar(TChar* const buffer, const std::size_t bufferSize, T&& t) { Detail::GivenBufferOutManager bufferOutManager(buffer, bufferSize); - Detail::FormatInManager(bufferOutManager, false, std::forward(t)); + return Detail::FormatInManager(bufferOutManager, false, std::forward(t)); } template @@ -150,7 +150,7 @@ namespace StreamFormat::FMT [[nodiscard]] std::expected CFilePrint(FILE* stream, T&& t) { Detail::DynamicBufferOutManager bufferOutManager(32); - Detail::FormatInManager(bufferOutManager, false, std::forward(t)).value(); + SF_TRY(Detail::FormatInManager(bufferOutManager, false, std::forward(t))); std::fwrite(bufferOutManager.GetBuffer(), static_cast(bufferOutManager.GetLastGeneratedDataSize()), 1, stream); std::fflush(stream); @@ -161,7 +161,7 @@ namespace StreamFormat::FMT [[nodiscard]] std::expected CFilePrintLn(FILE* stream, T&& t) { Detail::DynamicBufferOutManager bufferOutManager(32); - Detail::FormatInManager(bufferOutManager, true, std::forward(t)).value(); + SF_TRY(Detail::FormatInManager(bufferOutManager, true, std::forward(t))); std::fwrite(bufferOutManager.GetBuffer(), static_cast(bufferOutManager.GetLastGeneratedDataSize()), 1, stream); std::fflush(stream); @@ -172,7 +172,7 @@ namespace StreamFormat::FMT [[nodiscard]] std::expected FilePrint(std::basic_ostream& stream, T&& t) { Detail::DynamicBufferOutManager bufferOutManager(32); - Detail::FormatInManager(bufferOutManager, false, std::forward(t)).value(); + SF_TRY(Detail::FormatInManager(bufferOutManager, false, std::forward(t))); stream.write(bufferOutManager.GetBuffer(), static_cast(bufferOutManager.GetLastGeneratedDataSize())); stream.flush(); @@ -183,7 +183,7 @@ namespace StreamFormat::FMT [[nodiscard]] std::expected FilePrintLn(std::basic_ostream& stream, T&& t) { Detail::DynamicBufferOutManager bufferOutManager(32); - Detail::FormatInManager(bufferOutManager, true, std::forward(t)).value(); + SF_TRY(Detail::FormatInManager(bufferOutManager, true, std::forward(t))); stream.write(bufferOutManager.GetBuffer(), static_cast(bufferOutManager.GetLastGeneratedDataSize())); stream.flush(); @@ -194,7 +194,7 @@ namespace StreamFormat::FMT [[nodiscard]] std::expected FormatInString(std::basic_string& str, T&& t) { Detail::DynamicBufferOutManager bufferOutManager(32); - Detail::FormatInManager(bufferOutManager, false, std::forward(t)).value(); + SF_TRY(Detail::FormatInManager(bufferOutManager, false, std::forward(t))); str = bufferOutManager.GetLastGeneratedString(); } @@ -203,7 +203,7 @@ namespace StreamFormat::FMT [[nodiscard]] inline std::expected, FMTResult> FormatString(T&& t) { Detail::DynamicBufferOutManager bufferOutManager(32); - Detail::FormatInManager(bufferOutManager, false, std::forward(t)).value(); + SF_TRY(Detail::FormatInManager(bufferOutManager, false, std::forward(t))); return bufferOutManager.GetLastGeneratedString(); } } diff --git a/src/StreamFormat/FMT/Context/ParserExecutor/BasicParserExecutor.h b/src/StreamFormat/FMT/Context/ParserExecutor/BasicParserExecutor.h index d349ef88..3113ac97 100644 --- a/src/StreamFormat/FMT/Context/ParserExecutor/BasicParserExecutor.h +++ b/src/StreamFormat/FMT/Context/ParserExecutor/BasicParserExecutor.h @@ -40,7 +40,7 @@ namespace StreamFormat::FMT::Context SF_TRY(Detail::BufferTestManip(BufferIn).IsSameForward(sv.data(), sv.size())); return {}; } - [[nodiscard]] std::expected ExecSettings() override {}; + [[nodiscard]] std::expected ExecSettings() override { return {}; }; public: template @@ -52,9 +52,11 @@ namespace StreamFormat::FMT::Context template [[nodiscard]] inline std::expected ReadType(Type& type, Rest&... rest) { - ParserType>::Type, M_Type>::Parse(type, *this); + auto&& parseErr = ParserType>::Type, M_Type>::Parse(type, *this); + SF_TRY(parseErr); if constexpr (sizeof...(rest) > 0) - ReadType(std::forward(rest)...); + SF_TRY(ReadType(std::forward(rest)...)); + return {}; } }; } @@ -72,6 +74,7 @@ namespace StreamFormat::FMT::Context template [[nodiscard]] std::expected BasicParserExecutor::Terminate() { + return {}; } template @@ -82,15 +85,15 @@ namespace StreamFormat::FMT::Context Detail::TextProperties::Properties saveTextProperties = TextManager.Save(); Context::BasicContext context(*this, format, argsInterface); - context.Run(); - TextManager.Reload(saveTextProperties); + SF_TRY(context.Run()); + return TextManager.Reload(saveTextProperties); } template template [[nodiscard]] std::expected BasicParserExecutor::Run(Format&& formatInput, Args&&... args) { - Run_(Detail::BufferInfoView{formatInput}, std::forward(args)...); + return Run_(Detail::BufferInfoView{formatInput}, std::forward(args)...); } } diff --git a/src/StreamFormat/FMT/Context/ParserExecutor/ParseBasics-impl.h b/src/StreamFormat/FMT/Context/ParserExecutor/ParseBasics-impl.h index 3b03df0e..a4792e7d 100644 --- a/src/StreamFormat/FMT/Context/ParserExecutor/ParseBasics-impl.h +++ b/src/StreamFormat/FMT/Context/ParserExecutor/ParseBasics-impl.h @@ -83,6 +83,7 @@ namespace StreamFormat::FMT { // FIXME // TODO + return std::unexpected(FMTResult::FunctionNotImpl); } }; @@ -93,6 +94,7 @@ namespace StreamFormat::FMT { // FIXME // TODO + return std::unexpected(FMTResult::FunctionNotImpl); } }; @@ -103,6 +105,7 @@ namespace StreamFormat::FMT { // FIXME // TODO + return std::unexpected(FMTResult::FunctionNotImpl); } }; } diff --git a/src/StreamFormat/FMT/Context/ParserExecutor/UtilityFunctions.h b/src/StreamFormat/FMT/Context/ParserExecutor/UtilityFunctions.h index 42028577..ccf4c6b4 100644 --- a/src/StreamFormat/FMT/Context/ParserExecutor/UtilityFunctions.h +++ b/src/StreamFormat/FMT/Context/ParserExecutor/UtilityFunctions.h @@ -18,7 +18,7 @@ namespace StreamFormat::FMT Detail::ParserANSITextPropertiesExecutor> textPropertiesExecutor; Context::BasicParserExecutor> executor(buffer, textPropertiesExecutor); - executor.Run(format, std::forward(args)...); - executor.Terminate(); + SF_TRY(executor.Run(format, std::forward(args)...)); + return executor.Terminate(); } } diff --git a/src/StreamFormat/FMT/Detail/FMTResult.h b/src/StreamFormat/FMT/Detail/FMTResult.h index db1106b1..41ffd0e5 100644 --- a/src/StreamFormat/FMT/Detail/FMTResult.h +++ b/src/StreamFormat/FMT/Detail/FMTResult.h @@ -25,5 +25,8 @@ namespace StreamFormat::FMT Context_CannotApplyType, GivenArgs_UnableToDeduceSize, + + Manager_StaticMemory, + Manager_AllocationFailed, }; } diff --git a/src/StreamFormat/FMT/Serializers/CompilationData.h b/src/StreamFormat/FMT/Serializers/CompilationData.h index 33cd5f9d..1cd53a9b 100644 --- a/src/StreamFormat/FMT/Serializers/CompilationData.h +++ b/src/StreamFormat/FMT/Serializers/CompilationData.h @@ -50,9 +50,9 @@ namespace StreamFormat::FMT { [[nodiscard]] static inline std::expected Format(const Detail::FileLocation& t, FormatterExecutor& executor) { - executor.WriteType(t.FileName); - executor.BufferOut.Pushback(':'); - executor.WriteType(t.FileLine); + SF_TRY(executor.WriteType(t.FileName)); + SF_TRY(executor.BufferOut.Pushback(':')); + return executor.WriteType(t.FileLine); } }; @@ -61,9 +61,9 @@ namespace StreamFormat::FMT { [[nodiscard]] static inline std::expected Format(const Detail::FunctionProperties& t, FormatterExecutor& executor) { - executor.WriteType(t.Location); - executor.BufferOut.WriteCharArray(" @ "); - executor.WriteType(t.FunctionName); + SF_TRY(executor.WriteType(t.Location)); + SF_TRY(executor.BufferOut.WriteCharArray(" @ ")); + return executor.WriteType(t.FunctionName); } }; } diff --git a/src/StreamFormat/FMT/Serializers/FormatChrono.h b/src/StreamFormat/FMT/Serializers/FormatChrono.h index 2f741ecc..a2d9524f 100644 --- a/src/StreamFormat/FMT/Serializers/FormatChrono.h +++ b/src/StreamFormat/FMT/Serializers/FormatChrono.h @@ -29,15 +29,17 @@ namespace StreamFormat::FMT::Detail if (mode == TimePrintMode::Mod && shift.Size < 0) shift.Size = 3; - if (BufferTestManip(pattern).IsSameForward("ns", 2)) + if (BufferTestAccess(pattern).IsSame("ns", 2)) { + SF_TRY(BufferManip(pattern).Forward()); std::uint32_t ns = static_cast(std::chrono::time_point_cast(value).time_since_epoch().count()); if (mode == TimePrintMode::Mod) ns = ns % 1000; SF_TRY(FMTBufferWriteManip(buffer).WriteInteger(static_cast(ns) % 1000, shift)); } - else if (BufferTestManip(pattern).IsSameForward("us", 2)) + else if (BufferTestAccess(pattern).IsSame("us", 2)) { + SF_TRY(BufferManip(pattern).Forward()); std::uint32_t us = static_cast(std::chrono::time_point_cast(value).time_since_epoch().count()); if (mode == TimePrintMode::Mod) us = us % 1000; @@ -45,8 +47,9 @@ namespace StreamFormat::FMT::Detail us = us / 1000; SF_TRY(FMTBufferWriteManip(buffer).WriteInteger(static_cast(us) % 1000, shift)); } - else if (BufferTestManip(pattern).IsSameForward("ms", 2)) + else if (BufferTestAccess(pattern).IsSame("ms", 2)) { + SF_TRY(BufferManip(pattern).Forward()); std::uint32_t ms = static_cast(std::chrono::time_point_cast(value).time_since_epoch().count()); if (mode == TimePrintMode::Mod) ms = ms % 1000; @@ -54,8 +57,9 @@ namespace StreamFormat::FMT::Detail ms = ms / 1000000; SF_TRY(FMTBufferWriteManip(buffer).WriteInteger(static_cast(ms) % 1000, shift)); } - else if (BufferTestManip(pattern).IsEqualToForward('s')) + else if (BufferTestAccess(pattern).IsEqualTo('s')) { + SF_TRY(BufferManip(pattern).Forward()); std::uint32_t sec = static_cast(std::chrono::time_point_cast(value).time_since_epoch().count()); if (mode == TimePrintMode::Mod) sec = sec % 60; @@ -63,15 +67,17 @@ namespace StreamFormat::FMT::Detail sec = sec / 1000000000; SF_TRY(FMTBufferWriteManip(buffer).WriteInteger(static_cast(sec) % 1000, shift)); } - else if (BufferTestManip(pattern).IsEqualToForward('m')) + else if (BufferTestAccess(pattern).IsEqualTo('m')) { + SF_TRY(BufferManip(pattern).Forward()); std::uint32_t min = static_cast(std::chrono::time_point_cast(value).time_since_epoch().count()); if (mode == TimePrintMode::Mod) min = min % 60; SF_TRY(FMTBufferWriteManip(buffer).WriteInteger(static_cast(min) % 1000, shift)); } - else if (BufferTestManip(pattern).IsEqualToForward('h')) + else if (BufferTestAccess(pattern).IsEqualTo('h')) { + SF_TRY(BufferManip(pattern).Forward()); std::uint32_t min = static_cast(std::chrono::time_point_cast(value).time_since_epoch().count()); if (mode == TimePrintMode::Mod) min = min % 24; @@ -119,7 +125,7 @@ namespace StreamFormat::FMT { [[nodiscard]] static inline std::expected Format(const std::chrono::time_point& t, FormatterExecutor& executor) { - Detail::WriteTime(t, Detail::BufferInfoView(executor.Data.Specifiers.GetAsText("pattern", "%h:%m:%s.%ms")), executor.BufferOut); + return Detail::WriteTime(t, Detail::BufferInfoView(executor.Data.Specifiers.GetAsText("pattern", "%h:%m:%s.%ms")), executor.BufferOut); } }; @@ -136,20 +142,22 @@ namespace StreamFormat::FMT executor.BufferOut ); } - Detail::BufferWriteManip(executor.BufferOut).FastWriteInteger(t.count()); + SF_TRY(Detail::BufferWriteManip(executor.BufferOut).FastWriteInteger(t.count())); if constexpr (std::is_same_v, std::chrono::seconds>) - Detail::BufferOutManip(executor.BufferOut).Pushback('s'); + { SF_TRY(Detail::BufferOutManip(executor.BufferOut).Pushback('s')); } else if constexpr (std::is_same_v, std::chrono::minutes>) - Detail::BufferOutManip(executor.BufferOut).Pushback('m'); + { SF_TRY(Detail::BufferOutManip(executor.BufferOut).Pushback('m')); } else if constexpr (std::is_same_v, std::chrono::hours>) - Detail::BufferOutManip(executor.BufferOut).Pushback('h'); + { SF_TRY(Detail::BufferOutManip(executor.BufferOut).Pushback('h')); } else if constexpr (std::is_same_v, std::chrono::milliseconds>) - Detail::BufferOutManip(executor.BufferOut).Pushback('m', 's'); + { SF_TRY(Detail::BufferOutManip(executor.BufferOut).Pushback('m', 's')); } else if constexpr (std::is_same_v, std::chrono::microseconds>) - Detail::BufferOutManip(executor.BufferOut).Pushback('u', 's'); + { SF_TRY(Detail::BufferOutManip(executor.BufferOut).Pushback('u', 's')); } else if constexpr (std::is_same_v, std::chrono::nanoseconds>) - Detail::BufferOutManip(executor.BufferOut).Pushback('n', 's'); + { SF_TRY(Detail::BufferOutManip(executor.BufferOut).Pushback('n', 's')); } + + return {}; } }; } diff --git a/src/StreamFormat/FMT/Serializers/FormatSTDLib.h b/src/StreamFormat/FMT/Serializers/FormatSTDLib.h index c31722fb..ce7abfe9 100644 --- a/src/StreamFormat/FMT/Serializers/FormatSTDLib.h +++ b/src/StreamFormat/FMT/Serializers/FormatSTDLib.h @@ -16,19 +16,22 @@ namespace StreamFormat::FMT template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static inline std::expected Format(const std::basic_string& t, FormatterExecutor& executor) { Detail::BufferWriteManip(executor.BufferOut).FastWriteString(t); } + [[nodiscard]] static inline std::expected Format(const std::basic_string& t, FormatterExecutor& executor) + { return Detail::BufferWriteManip(executor.BufferOut).FastWriteString(t); } }; template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static inline std::expected Format(std::basic_string_view t, FormatterExecutor& executor) { Detail::BufferWriteManip(executor.BufferOut).FastWriteString(t); } + [[nodiscard]] static inline std::expected Format(std::basic_string_view t, FormatterExecutor& executor) + { return Detail::BufferWriteManip(executor.BufferOut).FastWriteString(t); } }; template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static inline std::expected Format(const std::basic_stringstream& t, FormatterExecutor& executor) { Detail::BufferWriteManip(executor.BufferOut).FastWriteCharArray(t.str(), t.size()); } + [[nodiscard]] static inline std::expected Format(const std::basic_stringstream& t, FormatterExecutor& executor) + { return Detail::BufferWriteManip(executor.BufferOut).FastWriteCharArray(t.str(), t.size()); } }; //------------------------------------------// @@ -42,9 +45,11 @@ namespace StreamFormat::FMT [[nodiscard]] static inline std::expected Format(const std::unique_ptr& t, FormatterExecutor& executor) { if (executor.Data.TrueValue) - FormatterType::Format(t.get(), executor); + return FormatterType::Format(t.get(), executor); else - FormatterType::Format(*t, executor); + return FormatterType::Format(*t, executor); + + return {}; } }; @@ -55,9 +60,11 @@ namespace StreamFormat::FMT [[nodiscard]] static inline std::expected Format(const std::shared_ptr& t, FormatterExecutor& executor) { if (executor.Data.TrueValue) - FormatterType::Format(t.get(), executor); + return FormatterType::Format(t.get(), executor); else - FormatterType::Format(*t, executor); + return FormatterType::Format(*t, executor); + + return {}; } }; @@ -65,6 +72,7 @@ namespace StreamFormat::FMT template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static inline std::expected Format(const std::weak_ptr& t, FormatterExecutor& executor) { FormatterType, FormatterExecutor>::Format(t.lock(), executor); } + [[nodiscard]] static inline std::expected Format(const std::weak_ptr& t, FormatterExecutor& executor) + { return FormatterType, FormatterExecutor>::Format(t.lock(), executor); } }; } diff --git a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_array.h b/src/StreamFormat/FMT/Serializers/STDContainer/FMT_array.h index 9fbc4b52..f7466c74 100644 --- a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_array.h +++ b/src/StreamFormat/FMT/Serializers/STDContainer/FMT_array.h @@ -10,7 +10,7 @@ namespace StreamFormat::FMT { [[nodiscard]] static inline std::expected Format(const std::array& t, FormatterExecutor& executor) { - FormatterType>, FormatterExecutor>::Format(t, executor); + return FormatterType>, FormatterExecutor>::Format(t, executor); } }; } diff --git a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_deque.h b/src/StreamFormat/FMT/Serializers/STDContainer/FMT_deque.h index b6835db7..715d7f1f 100644 --- a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_deque.h +++ b/src/StreamFormat/FMT/Serializers/STDContainer/FMT_deque.h @@ -8,6 +8,7 @@ namespace StreamFormat::FMT template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static inline std::expected Format(const std::deque& t, FormatterExecutor& executor) { FormatterType>, FormatterExecutor>::Format(t, executor); } + [[nodiscard]] static inline std::expected Format(const std::deque& t, FormatterExecutor& executor) + { return FormatterType>, FormatterExecutor>::Format(t, executor); } }; } diff --git a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_forward_list.h b/src/StreamFormat/FMT/Serializers/STDContainer/FMT_forward_list.h index d84e5ca2..6214bc06 100644 --- a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_forward_list.h +++ b/src/StreamFormat/FMT/Serializers/STDContainer/FMT_forward_list.h @@ -10,7 +10,7 @@ namespace StreamFormat::FMT { [[nodiscard]] static inline std::expected Format(const std::forward_list& t, FormatterExecutor& executor) { - FormatterType>, FormatterExecutor>::Format(t, executor); + return FormatterType>, FormatterExecutor>::Format(t, executor); } }; } diff --git a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_list.h b/src/StreamFormat/FMT/Serializers/STDContainer/FMT_list.h index 8a1aab04..b4a166af 100644 --- a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_list.h +++ b/src/StreamFormat/FMT/Serializers/STDContainer/FMT_list.h @@ -8,6 +8,7 @@ namespace StreamFormat::FMT template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static inline std::expected Format(const std::list& t, FormatterExecutor& executor) { FormatterType>, FormatterExecutor>::Format(t, executor); } + [[nodiscard]] static inline std::expected Format(const std::list& t, FormatterExecutor& executor) + { return FormatterType>, FormatterExecutor>::Format(t, executor); } }; } diff --git a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_map.h b/src/StreamFormat/FMT/Serializers/STDContainer/FMT_map.h index 750130d0..98f2da40 100644 --- a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_map.h +++ b/src/StreamFormat/FMT/Serializers/STDContainer/FMT_map.h @@ -10,7 +10,10 @@ namespace StreamFormat::FMT template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static inline std::expected Format(const std::map& t, FormatterExecutor& executor) { FormatterType>, FormatterExecutor>::Format(t, executor); } + [[nodiscard]] static inline std::expected Format(const std::map& t, FormatterExecutor& executor) + { + return FormatterType>, FormatterExecutor>::Format(t, executor); + } }; template @@ -18,7 +21,7 @@ namespace StreamFormat::FMT { [[nodiscard]] static inline std::expected Format(const std::multimap& t, FormatterExecutor& executor) { - FormatterType>, FormatterExecutor>::Format(t, executor); + return ormatterType>, FormatterExecutor>::Format(t, executor); } }; } diff --git a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_queue.h b/src/StreamFormat/FMT/Serializers/STDContainer/FMT_queue.h index 4d0075c7..8bdca2ec 100644 --- a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_queue.h +++ b/src/StreamFormat/FMT/Serializers/STDContainer/FMT_queue.h @@ -8,6 +8,9 @@ namespace StreamFormat::FMT template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static inline std::expected Format(const std::queue& t, FormatterExecutor& executor) {} + [[nodiscard]] static inline std::expected Format(const std::queue& t, FormatterExecutor& executor) + { + return std::unexpected(FMTResult::FunctionNotImpl); + } }; } diff --git a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_set.h b/src/StreamFormat/FMT/Serializers/STDContainer/FMT_set.h index bc5ca78e..5724c3d5 100644 --- a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_set.h +++ b/src/StreamFormat/FMT/Serializers/STDContainer/FMT_set.h @@ -8,12 +8,14 @@ namespace StreamFormat::FMT template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static inline std::expected Format(const std::set& t, FormatterExecutor& executor) { FormatterType>, FormatterExecutor>::Format(t, executor); } + [[nodiscard]] static inline std::expected Format(const std::set& t, FormatterExecutor& executor) + { return FormatterType>, FormatterExecutor>::Format(t, executor); } }; template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static inline std::expected Format(const std::multiset& t, FormatterExecutor& executor) { FormatterType>, FormatterExecutor>::Format(t, executor); } + [[nodiscard]] static inline std::expected Format(const std::multiset& t, FormatterExecutor& executor) + { return FormatterType>, FormatterExecutor>::Format(t, executor); } }; } diff --git a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_tuple.h b/src/StreamFormat/FMT/Serializers/STDContainer/FMT_tuple.h index 2aefd205..4fcdb2bd 100644 --- a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_tuple.h +++ b/src/StreamFormat/FMT/Serializers/STDContainer/FMT_tuple.h @@ -18,21 +18,23 @@ namespace StreamFormat::FMT::TupleDetail template [[nodiscard]] static inline std::expected TupleFormatRec(FormatterExecutor& executor) - {} + { + return {}; + } template [[nodiscard]] static inline std::expected TupleFormatRec(FormatterExecutor& executor, const T& t) { - executor.WriteType(t); + return executor.WriteType(t); } template [[nodiscard]] static inline std::expected TupleFormatRec(FormatterExecutor& executor, const T& t, Args&&... args) { - executor.WriteType(t); - executor.BufferOut.Pushback(','); - executor.BufferOut.Pushback(' '); - TupleFormatRec(context, args...); + SF_TRY(executor.WriteType(t)); + SF_TRY(executor.BufferOut.Pushback(',')); + SF_TRY(executor.BufferOut.Pushback(' ')); + return TupleFormatRec(context, args...); } } @@ -43,9 +45,15 @@ namespace StreamFormat::FMT { [[nodiscard]] static inline std::expected Format(const std::tuple& t, FormatterExecutor& executor) { - executor.BufferOut.Pushback('<'); - std::apply([&context](auto&&... args) { TupleDetail::TupleFormatRec(context, args...); }, t); - executor.BufferOut.Pushback('>'); + SF_TRY(executor.BufferOut.Pushback('<')); + std::expected err = {}; + std::apply([&context, &err](auto&&... args) + { + auto&& res = TupleDetail::TupleFormatRec(context, args...); + if (not res) + { err = res.error(); } + }, t); + SF_TRY(executor.BufferOut.Pushback('>')); } }; @@ -54,11 +62,13 @@ namespace StreamFormat::FMT { [[nodiscard]] static inline std::expected Format(const std::pair& t, FormatterExecutor& executor) { - executor.BufferOut.Pushback('<'); - executor.WriteType(t.first); - executor.BufferOut.Pushback(':'); - executor.WriteType(t.second); - executor.BufferOut.Pushback('>'); + SF_TRY(executor.BufferOut.Pushback('<')); + SF_TRY(executor.WriteType(t.first)); + SF_TRY(executor.BufferOut.Pushback(':')); + SF_TRY(executor.WriteType(t.second)); + SF_TRY(executor.BufferOut.Pushback('>')); + + return {}; } }; } diff --git a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_unordered_map.h b/src/StreamFormat/FMT/Serializers/STDContainer/FMT_unordered_map.h index d554dc0d..8c5383c9 100644 --- a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_unordered_map.h +++ b/src/StreamFormat/FMT/Serializers/STDContainer/FMT_unordered_map.h @@ -12,7 +12,7 @@ namespace StreamFormat::FMT { [[nodiscard]] static inline std::expected Format(const std::unordered_map& t, FormatterExecutor& executor) { - FormatterType>, FormatterExecutor>::Format(t, executor); + return FormatterType>, FormatterExecutor>::Format(t, executor); } }; @@ -21,7 +21,7 @@ namespace StreamFormat::FMT { [[nodiscard]] static inline std::expected Format(const std::unordered_multimap& t, FormatterExecutor& executor) { - FormatterType>, FormatterExecutor>::Format(t, executor); + return FormatterType>, FormatterExecutor>::Format(t, executor); } }; } diff --git a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_unordered_set.h b/src/StreamFormat/FMT/Serializers/STDContainer/FMT_unordered_set.h index b7ea41ae..f7b37e08 100644 --- a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_unordered_set.h +++ b/src/StreamFormat/FMT/Serializers/STDContainer/FMT_unordered_set.h @@ -10,7 +10,7 @@ namespace StreamFormat::FMT { [[nodiscard]] static inline std::expected Format(const std::unordered_set& t, FormatterExecutor& executor) { - FormatterType>, FormatterExecutor>::Format(t, executor); + return FormatterType>, FormatterExecutor>::Format(t, executor); } }; @@ -19,7 +19,7 @@ namespace StreamFormat::FMT { [[nodiscard]] static inline std::expected Format(const std::unordered_multiset& t, FormatterExecutor& executor) { - FormatterType>, FormatterExecutor>::Format(t, executor); + return FormatterType>, FormatterExecutor>::Format(t, executor); } }; } diff --git a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_vector.h b/src/StreamFormat/FMT/Serializers/STDContainer/FMT_vector.h index de90d079..921fa8a3 100644 --- a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_vector.h +++ b/src/StreamFormat/FMT/Serializers/STDContainer/FMT_vector.h @@ -8,6 +8,7 @@ namespace StreamFormat::FMT template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static inline std::expected Format(const std::vector& t, FormatterExecutor& executor) { FormatterType>, FormatterExecutor>::Format(t, executor); } + [[nodiscard]] static inline std::expected Format(const std::vector& t, FormatterExecutor& executor) + { return FormatterType>, FormatterExecutor>::Format(t, executor); } }; } diff --git a/src/StreamFormat/Json/JsonFactory.h b/src/StreamFormat/Json/JsonFactory.h index 004d5156..ad8ada92 100644 --- a/src/StreamFormat/Json/JsonFactory.h +++ b/src/StreamFormat/Json/JsonFactory.h @@ -29,7 +29,8 @@ namespace StreamFormat::FMT template struct FormatterType { - static void Format(const JSON::JsonObject& object, FormatterExecutor& executor) { executor.WriteType(JSON::FormatAsJson(object)); } + [[nodiscard]] static std::expected Format(const JSON::JsonObject& object, FormatterExecutor& executor) + { return executor.WriteType(JSON::FormatAsJson(object)); } }; } diff --git a/src/StreamFormat/Json/JsonSerializer.h b/src/StreamFormat/Json/JsonSerializer.h index e12c771b..27129b86 100644 --- a/src/StreamFormat/Json/JsonSerializer.h +++ b/src/StreamFormat/Json/JsonSerializer.h @@ -97,7 +97,7 @@ namespace StreamFormat::JSON static inline void ParseSTDString(std::string& t, Detail::JsonParser& parser) { FMT::Detail::DynamicBufferOutManager bufferData; - FMT::Detail::BufferOutInfo buffer(bufferData); + FMT::Detail::BufferOutInfo buffer = FMT::Detail::BufferOutInfo::Create(bufferData).value(); FMT::Detail::BufferUtils::ParseEscapedQuotedString(parser.BufferIn, buffer).value(); FMT::Detail::BufferOutManip(buffer).ComputeGeneratedSize(); t = bufferData.GetLastGeneratedString(); @@ -329,12 +329,13 @@ namespace StreamFormat::FMT template struct FormatterType, FormatterExecutor> { - static void Format(const JSON::FormatAsJson& json, FormatterExecutor& executor) + [[nodiscard]] static std::expected Format(const JSON::FormatAsJson& json, FormatterExecutor& executor) { bool ordered_struct = executor.Data.Specifiers.Has("ordered_struct"); JSON::Detail::JsonFormatter::FormatSettings settings{.OrderedStruct = ordered_struct, .FloatPrecision = executor.Data.FloatPrecision}; JSON::Detail::JsonFormatter jsonFormatter(executor.BufferOut, settings); JSON::JsonSerializer::Format(json.Value, jsonFormatter); + return {}; } }; #endif @@ -343,13 +344,14 @@ namespace StreamFormat::FMT template struct ParserType, ParserExecutor> { - static inline void Parse(T& json, ParserExecutor& executor) + [[nodiscard]] static std::expected Parse(T& json, ParserExecutor& executor) { JSON::Detail::JsonParser jsonParser(*executor.BufferIn.Manager); jsonParser.BufferIn.CurrentPos = executor.BufferIn.CurrentPos; // TODO: // JSON::JsonSerializer::Parse(json.Value, jsonParser); executor.BufferIn.CurrentPos = jsonParser.BufferIn.CurrentPos; + return {}; } }; #endif diff --git a/src/StreamFormat/ProfilerManager/Event.h b/src/StreamFormat/ProfilerManager/Event.h index 54bfccc1..1fd6281f 100644 --- a/src/StreamFormat/ProfilerManager/Event.h +++ b/src/StreamFormat/ProfilerManager/Event.h @@ -129,6 +129,7 @@ namespace StreamFormat::FMT template struct FormatterType { - static void Format(const StreamFormat::ProfilerManager::EventType& t, FormatterExecutor& executor) { executor.BufferOut.Pushback(static_cast(t)); } + [[nodiscard]] static std::expected Format(const StreamFormat::ProfilerManager::EventType& t, FormatterExecutor& executor) + { return executor.BufferOut.Pushback(static_cast(t)); } }; } diff --git a/src/StreamFormat/Tester/TestSuite/TestSuite.h b/src/StreamFormat/Tester/TestSuite/TestSuite.h index dea63c57..a96ec946 100644 --- a/src/StreamFormat/Tester/TestSuite/TestSuite.h +++ b/src/StreamFormat/Tester/TestSuite/TestSuite.h @@ -195,65 +195,67 @@ namespace StreamFormat::FMT template struct FormatterType { - static void Format(const StreamFormat::Tester::Detail::TestSuite& t, FormatterExecutor& executor) { executor.BufferOut.FastWriteString(t.Name); } + [[nodiscard]] static std::expected Format(const StreamFormat::Tester::Detail::TestSuite& t, FormatterExecutor& executor) + { return executor.BufferOut.FastWriteString(t.Name); } }; template struct FormatterType { - static void Format(const StreamFormat::Tester::Detail::Test& t, FormatterExecutor& executor) + [[nodiscard]] static std::expected Format(const StreamFormat::Tester::Detail::Test& t, FormatterExecutor& executor) { - Detail::BufferWriteManip(executor.BufferOut).FastWriteString(t.Link.Name); - Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("::"); - Detail::BufferWriteManip(executor.BufferOut).FastWriteString(t.Name); + SF_TRY(Detail::BufferWriteManip(executor.BufferOut).FastWriteString(t.Link.Name)); + SF_TRY(Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("::")); + SF_TRY(Detail::BufferWriteManip(executor.BufferOut).FastWriteString(t.Name)); + return {}; } }; template struct FormatterType { - static void Format(const StreamFormat::Tester::TestStatus& status, FormatterExecutor& executor) + [[nodiscard]] static std::expected Format(const StreamFormat::Tester::TestStatus& status, FormatterExecutor& executor) { switch (status) { case StreamFormat::Tester::TestStatus::Ok: - executor.Run("[ {C:green}OK{C} ]").value(); - break; + return executor.Run("[ {C:green}OK{C} ]"); case StreamFormat::Tester::TestStatus::Fail: - executor.Run("[ {C:red}FAIL{C} ]").value(); - break; + return executor.Run("[ {C:red}FAIL{C} ]"); case StreamFormat::Tester::TestStatus::Crash: - executor.Run("[{C:magenta}Crash{C} ]").value(); - break; + return executor.Run("[{C:magenta}Crash{C} ]"); } + return {}; } }; template struct FormatterType { - static void Format(const StreamFormat::Tester::Detail::TestStatusBank& statusBank, FormatterExecutor& executor) + [[nodiscard]] static std::expected Format(const StreamFormat::Tester::Detail::TestStatusBank& statusBank, FormatterExecutor& executor) { - Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("TestsDone ").value(); - executor.Run("{:C:white}", statusBank.TestsDone).value(); + SF_TRY(Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("TestsDone ")); + SF_TRY(executor.Run("{:C:white}", statusBank.TestsDone)); - Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral(" | TestsOK ").value(); + SF_TRY(Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral(" | TestsOK ")); if (statusBank.TestsOk == statusBank.TestsDone) - executor.Run("{:C:green}", statusBank.TestsOk).value(); + { SF_TRY(executor.Run("{:C:green}", statusBank.TestsOk)); } else - executor.Run("{:C:yellow}", statusBank.TestsOk).value(); + { SF_TRY(executor.Run("{:C:yellow}", statusBank.TestsOk)); } - Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral(" | TestsFAIL ").value(); + SF_TRY(Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral(" | TestsFAIL ")); if (statusBank.TestsFail == 0) - executor.Run("{:C:green}", statusBank.TestsFail).value(); + { SF_TRY(executor.Run("{:C:green}", statusBank.TestsFail)); } else - executor.Run("{:C:red}", statusBank.TestsFail).value(); + { SF_TRY(executor.Run("{:C:red}", statusBank.TestsFail)); } - Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral(" | TestCrash ").value(); + SF_TRY(Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral(" | TestCrash ")); if (statusBank.TestsCrash == 0) - executor.Run("{:C:green}", statusBank.TestsCrash).value(); + { SF_TRY(executor.Run("{:C:green}", statusBank.TestsCrash)); } else - executor.Run("{:C:magenta}", statusBank.TestsCrash).value(); + { SF_TRY(executor.Run("{:C:magenta}", statusBank.TestsCrash)); } + + return {}; } }; } From 048db30aad1b6cbcff419fc6c74afd764e4cad17 Mon Sep 17 00:00:00 2001 From: BELLIER Sacha Date: Tue, 26 Nov 2024 23:03:06 +0100 Subject: [PATCH 05/42] fix: clang compile --- BUILD.bazel | 5 ++++- Examples/HelloWorld/BUILD.bazel | 5 ++++- Examples/HelloWorld/main.cpp | 4 ++++ src/StreamFormat/FLog/LoggerImpl/XLogger.h | 7 +++++-- .../FMT/Context/BasicContext/TextPropertiesManager.h | 9 ++++++++- src/StreamFormat/Json/JsonFactory.h | 2 +- src/StreamFormat/Json/JsonSerializer.h | 10 +++++----- 7 files changed, 31 insertions(+), 11 deletions(-) diff --git a/BUILD.bazel b/BUILD.bazel index 61105670..93515647 100644 --- a/BUILD.bazel +++ b/BUILD.bazel @@ -25,6 +25,9 @@ cc_test( "//conditions:default": ["-std=c++23"], }), deps = [ ":StreamFormat" ], - linkopts = [ "-lpthread" ], + linkopts = select({ + "@rules_cc//cc/compiler:msvc-cl": [""], + "//conditions:default": ["-pthread"], + }), visibility = ["//visibility:public"], ) diff --git a/Examples/HelloWorld/BUILD.bazel b/Examples/HelloWorld/BUILD.bazel index 694d1203..0c7e4769 100644 --- a/Examples/HelloWorld/BUILD.bazel +++ b/Examples/HelloWorld/BUILD.bazel @@ -10,7 +10,10 @@ cc_binary( "@rules_cc//cc/compiler:msvc-cl": ["/std:latest"], "//conditions:default": ["-std=c++23"], }), - linkopts = [ "-lpthread" ], + linkopts = select({ + "@rules_cc//cc/compiler:msvc-cl": [""], + "//conditions:default": ["-pthread"], + }), deps = [ "@streamformat//:StreamFormat" ], visibility = ["//visibility:public"], ) diff --git a/Examples/HelloWorld/main.cpp b/Examples/HelloWorld/main.cpp index 467a469e..19cc35c7 100644 --- a/Examples/HelloWorld/main.cpp +++ b/Examples/HelloWorld/main.cpp @@ -7,6 +7,10 @@ int main() { std::cout << StreamFormat::FMT::FormatString("HelloWorld !").value(); + std::cout << StreamFormat::FMT::FormatString("HelloWorld !").value(); + std::cout << StreamFormat::FMT::FormatString("HelloWorld !").value(); + std::cout << StreamFormat::FMT::FormatString("HelloWorld !").value(); + std::cout << StreamFormat::FMT::FormatString("HelloWorld !").value(); StreamFormat::FLog::DefaultLogger::Core().Info("HelloWorld !"); diff --git a/src/StreamFormat/FLog/LoggerImpl/XLogger.h b/src/StreamFormat/FLog/LoggerImpl/XLogger.h index 2b19ec6e..39d565a3 100644 --- a/src/StreamFormat/FLog/LoggerImpl/XLogger.h +++ b/src/StreamFormat/FLog/LoggerImpl/XLogger.h @@ -87,12 +87,15 @@ namespace StreamFormat::FLog::Detail public: template requires FMT::Detail::ConvertibleToBufferInfoView - void Log(Severity status, Format&& format, Args&&... args) { Master::template Log(status, format, std::forward(args)...); } + void Log(Severity status, Format&& format, Args&&... args) + { + Master::template Log(status, format, std::forward(args)...); + } template void Log(Severity status, T&& t) { - Master::template Log(status, std::forward(t)); + Master::template Log(status, std::forward(t)); } public: diff --git a/src/StreamFormat/FMT/Context/BasicContext/TextPropertiesManager.h b/src/StreamFormat/FMT/Context/BasicContext/TextPropertiesManager.h index 06b15c99..3d3b84a4 100644 --- a/src/StreamFormat/FMT/Context/BasicContext/TextPropertiesManager.h +++ b/src/StreamFormat/FMT/Context/BasicContext/TextPropertiesManager.h @@ -142,6 +142,8 @@ namespace StreamFormat::FMT::Detail } if (m_CurrentContextProperties.Color.NeedModif(modif.Fg)) return ApplyColor(modif.Bg); + + return {}; } [[nodiscard]] std::expected AskApplyColor(const Detail::TextProperties::TextColor::ColorCube& modif) @@ -154,6 +156,8 @@ namespace StreamFormat::FMT::Detail } if (m_CurrentContextProperties.Color.NeedModif(modif.Fg)) return ApplyColor(modif.Bg); + + return {}; } [[nodiscard]] std::expected AskApplyColor(const Detail::TextProperties::TextColor::Color24b& modif) @@ -164,7 +168,10 @@ namespace StreamFormat::FMT::Detail return ApplyColor(modif); return ApplyColor(modif.Fg); } - if (m_CurrentContextProperties.Color.NeedModif(modif.Fg)) return ApplyColor(modif.Bg); + if (m_CurrentContextProperties.Color.NeedModif(modif.Fg)) + return ApplyColor(modif.Bg); + + return {}; } [[nodiscard]] std::expected AskApplyColor(const Detail::TextProperties::TextColor::ColorFG& modif) { return ReloadColorFG(modif); } diff --git a/src/StreamFormat/Json/JsonFactory.h b/src/StreamFormat/Json/JsonFactory.h index ad8ada92..ab751548 100644 --- a/src/StreamFormat/Json/JsonFactory.h +++ b/src/StreamFormat/Json/JsonFactory.h @@ -71,7 +71,7 @@ namespace StreamFormat::JSON if (file.is_open() == false) throw std::runtime_error("unable to open file"); FMT::Detail::DynamicBufferOutManager BufferOutManager(256); - FMT::Detail::BufferOutInfo bufferOut{BufferOutManager}; + FMT::Detail::BufferOutInfo bufferOut = FMT::Detail::BufferOutInfo::Create(BufferOutManager).value(); Detail::JsonFormatter formatter(bufferOut, settings); JsonSerializer::Format(json, formatter); diff --git a/src/StreamFormat/Json/JsonSerializer.h b/src/StreamFormat/Json/JsonSerializer.h index 27129b86..4d607c8e 100644 --- a/src/StreamFormat/Json/JsonSerializer.h +++ b/src/StreamFormat/Json/JsonSerializer.h @@ -19,7 +19,7 @@ namespace StreamFormat::JSON static inline void Parse(T&, Detail::JsonParser&) { #ifdef UNKOWN_TYPE_MESSAGE - FMT::FilePrint(std::cerr, "{C:red}JsonSerializer::Parse<{}> not impl", typeid(T).name()); + FMT::FilePrint(std::cerr, "{C:red}JsonSerializer::Parse<{}> not impl", typeid(T).name()).value(); #endif #ifdef UNKOWN_TYPE_THROW throw Detail::JsonTypeSerializerNotImpl{}; @@ -60,7 +60,7 @@ namespace StreamFormat::JSON static inline void ReadObject(T&, const JsonObject&) { #ifdef UNKOWN_TYPE_MESSAGE - FMT::FilePrint(std::cerr, "{C:red}JsonObjectSerializer::ReadObject<{}> not impl", typeid(T).name()); + FMT::FilePrint(std::cerr, "{C:red}JsonObjectSerializer::ReadObject<{}> not impl", typeid(T).name()).value(); #endif #ifdef UNKOWN_TYPE_THROW throw Detail::JsonTypeSerializerNotImpl{}; @@ -77,7 +77,7 @@ namespace StreamFormat::JSON static inline void WriteObject(const T&, JsonObject&) { #ifdef UNKOWN_TYPE_MESSAGE - FMT::FilePrint(std::cerr, "{C:red}JsonObjectSerializer::WriteObject<{}> not impl", typeid(T).name()); + FMT::FilePrint(std::cerr, "{C:red}JsonObjectSerializer::WriteObject<{}> not impl", typeid(T).name()).value(); #endif #ifdef UNKOWN_TYPE_THROW throw Detail::JsonTypeSerializerNotImpl{}; @@ -123,11 +123,11 @@ namespace StreamFormat::JSON { const char* begin = parser.BufferIn.CurrentPos; float tmp = 0; - FMT::Detail::BufferReadManip(parser.BufferIn).FastReadFloat(tmp); + FMT::Detail::BufferReadManip(parser.BufferIn).FastReadFloat(tmp).value(); const char* end = parser.BufferIn.CurrentPos; parser.BufferIn.CurrentPos = begin; - FMT::Detail::BufferReadManip(parser.BufferIn).FastReadInteger(t); + FMT::Detail::BufferReadManip(parser.BufferIn).FastReadInteger(t).value(); parser.BufferIn.CurrentPos = end; } From d5352e8ce587be615c80888112d727226fc062ca Mon Sep 17 00:00:00 2001 From: BELLIER Sacha Date: Wed, 27 Nov 2024 23:05:19 +0100 Subject: [PATCH 06/42] fix: now run... sort of --- Examples/HelloWorld/main.cpp | 6 -- Examples/MODULE.bazel | 8 +- MODULE.bazel | 66 ++++++------- src/StreamFormat/Core/Prelude.h | 18 ++-- src/StreamFormat/FLog/LoggerImpl/XLogger.h | 50 ++++++---- src/StreamFormat/FLog/Loggers/BasicLogger.h | 18 ++-- .../FLog/Loggers/LoggerMultiSinkFast.h | 28 ++++-- .../FLog/Loggers/LoggerMultiSinkSafe.h | 37 +++++--- src/StreamFormat/FLog/Sinks/LoggerSink.h | 21 ++-- .../BufferOutManager/BasicBufferOutManager.h | 2 +- src/StreamFormat/FMT/Buffer/BufferTestManip.h | 6 +- .../FMT/Buffer/FMTBufferOutManip.h | 4 +- .../FMT/Context/BasicContext/BasicContext.h | 5 + .../BasicContext/BasicContextParse-impl.h | 95 ++++++++++++------- .../Context/FormatterExecutor/FormatterArgs.h | 8 +- .../FMT/Context/ParserExecutor/ParserArgs.h | 8 +- src/StreamFormat/FMT/Detail/FMTResult.h | 2 + .../FMT/Serializers/FormatChrono.h | 3 +- 18 files changed, 231 insertions(+), 154 deletions(-) diff --git a/Examples/HelloWorld/main.cpp b/Examples/HelloWorld/main.cpp index 19cc35c7..cca27e5e 100644 --- a/Examples/HelloWorld/main.cpp +++ b/Examples/HelloWorld/main.cpp @@ -6,12 +6,6 @@ int main() { - std::cout << StreamFormat::FMT::FormatString("HelloWorld !").value(); - std::cout << StreamFormat::FMT::FormatString("HelloWorld !").value(); - std::cout << StreamFormat::FMT::FormatString("HelloWorld !").value(); - std::cout << StreamFormat::FMT::FormatString("HelloWorld !").value(); - std::cout << StreamFormat::FMT::FormatString("HelloWorld !").value(); - StreamFormat::FLog::DefaultLogger::Core().Info("HelloWorld !"); using namespace std::chrono_literals; diff --git a/Examples/MODULE.bazel b/Examples/MODULE.bazel index 57961fed..bcf173e1 100644 --- a/Examples/MODULE.bazel +++ b/Examples/MODULE.bazel @@ -9,9 +9,9 @@ module( bazel_dep(name = "rules_cc", version = "0.0.10") bazel_dep(name = "platforms", version = "0.0.10") -git_override(module_name="bazel_utilities", remote="https://github.com/0-Sacha/bazel_utilities.git", commit="7f6c3585c41278918428ed48d45b12413c197fc0") -git_override(module_name="bazel_buildbuddy", remote="https://github.com/0-Sacha/bazel_buildbuddy.git", commit="b60314cac7826edb87efe285b032b877ad725f84") -git_override(module_name="bazel_winlibs", remote="https://github.com/0-Sacha/bazel_winlibs.git", commit="e2cc97b61cb9115fbc2b7169dc9d1cb36b351935") +git_override(module_name="bazel_utilities", remote="https://github.com/0-Sacha/bazel_utilities.git", commit="fbb17685ac9ba78fef914a322e6c37839dc16d4f") +git_override(module_name="bazel_buildbuddy", remote="https://github.com/0-Sacha/bazel_buildbuddy.git", commit="f3e98389266ce759fc71e1186502fa40f3ed3049") +git_override(module_name="bazel_winlibs", remote="https://github.com/0-Sacha/bazel_winlibs.git", commit="86a2725fb26fb73bfe8dc535f8f46bd1190cdae8") bazel_dep(name = "bazel_utilities", version = "0.0.1", dev_dependency = True) bazel_dep(name = "bazel_winlibs", version = "0.0.1", dev_dependency = True) bazel_dep(name = "bazel_buildbuddy", version = "0.0.1", dev_dependency = True) @@ -21,5 +21,5 @@ bazel_dep(name = "streamformat") winlibs_toolchain_extension = use_extension("@bazel_winlibs//:rules.bzl", "winlibs_toolchain_extension", dev_dependency = True) inject_repo(winlibs_toolchain_extension, "platforms", "bazel_utilities") -winlibs_toolchain_extension.winlibs_toolchain(name = "winlibs") +winlibs_toolchain_extension.winlibs_toolchain(name = "winlibs", dbg_copts = [ "-g3", "-O0" ]) use_repo(winlibs_toolchain_extension, "winlibs") \ No newline at end of file diff --git a/MODULE.bazel b/MODULE.bazel index 398f5829..65e8c940 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -1,33 +1,33 @@ -"" - -# buildifier: disable=module-docstring -module( - name = "streamformat", - version = "0.1", -) - -bazel_dep(name = "rules_cc", version = "0.0.10") -bazel_dep(name = "platforms", version = "0.0.10") - -git_override(module_name="bazel_utilities", remote="https://github.com/0-Sacha/bazel_utilities.git", commit="aa399bb2599e2cd64a35a2275ce0f73a539524a5") -git_override(module_name="bazel_buildbuddy", remote="https://github.com/0-Sacha/bazel_buildbuddy.git", commit="b96ebe6a8dbe7a6c82bd91d6e0cb79e53f11fa8f") -git_override(module_name="bazel_winlibs", remote="https://github.com/0-Sacha/bazel_winlibs.git", commit="0f9fcc1b821b48e0bfa216f876a1df2a27b0522f") -bazel_dep(name = "bazel_utilities", version = "0.0.1", dev_dependency = True) -bazel_dep(name = "bazel_buildbuddy", version = "0.0.1", dev_dependency = True) -bazel_dep(name = "bazel_winlibs", version = "0.0.1", dev_dependency = True) - -git_override(module_name = "hedron_compile_commands", remote = "https://github.com/hedronvision/bazel-compile-commands-extractor.git", commit = "1e08f8e0507b6b6b1f4416a9a22cf5c28beaba93",) -bazel_dep(name = "hedron_compile_commands", dev_dependency = True) - -winlibs_toolchain_extension = use_extension("@bazel_winlibs//:rules.bzl", "winlibs_toolchain_extension", dev_dependency = True) -inject_repo(winlibs_toolchain_extension, "platforms", "bazel_utilities") -winlibs_toolchain_extension.winlibs_toolchain(name = "winlibs") -use_repo(winlibs_toolchain_extension, "winlibs") -# register_toolchains("@winlibs//:gcc-toolchain") -# register_toolchains("@winlibs//:clang-toolchain") - -buildbuddy_toolchain_extension = use_extension("@bazel_buildbuddy//:rules.bzl", "buildbuddy_toolchain_extension", dev_dependency = True) -inject_repo(buildbuddy_toolchain_extension, "platforms", "bazel_utilities") -buildbuddy_toolchain_extension.buildbuddy_toolchain(name = "buildbuddy") -use_repo(buildbuddy_toolchain_extension, "buildbuddy") -# register_toolchains("@buildbuddy//:gcc-toolchain") +"" + +# buildifier: disable=module-docstring +module( + name = "streamformat", + version = "0.1", +) + +bazel_dep(name = "rules_cc", version = "0.0.10") +bazel_dep(name = "platforms", version = "0.0.10") + +git_override(module_name="bazel_utilities", remote="https://github.com/0-Sacha/bazel_utilities.git", commit="fbb17685ac9ba78fef914a322e6c37839dc16d4f") +git_override(module_name="bazel_buildbuddy", remote="https://github.com/0-Sacha/bazel_buildbuddy.git", commit="f3e98389266ce759fc71e1186502fa40f3ed3049") +git_override(module_name="bazel_winlibs", remote="https://github.com/0-Sacha/bazel_winlibs.git", commit="86a2725fb26fb73bfe8dc535f8f46bd1190cdae8") +bazel_dep(name = "bazel_utilities", version = "0.0.1", dev_dependency = True) +bazel_dep(name = "bazel_buildbuddy", version = "0.0.1", dev_dependency = True) +bazel_dep(name = "bazel_winlibs", version = "0.0.1", dev_dependency = True) + +git_override(module_name = "hedron_compile_commands", remote = "https://github.com/hedronvision/bazel-compile-commands-extractor.git", commit = "1e08f8e0507b6b6b1f4416a9a22cf5c28beaba93",) +bazel_dep(name = "hedron_compile_commands", dev_dependency = True) + +winlibs_toolchain_extension = use_extension("@bazel_winlibs//:rules.bzl", "winlibs_toolchain_extension", dev_dependency = True) +inject_repo(winlibs_toolchain_extension, "platforms", "bazel_utilities") +winlibs_toolchain_extension.winlibs_toolchain(name = "winlibs", dbg_copts = [ "-g3", "-O0" ]) +use_repo(winlibs_toolchain_extension, "winlibs") +# register_toolchains("@winlibs//:gcc-toolchain") +# register_toolchains("@winlibs//:clang-toolchain") + +buildbuddy_toolchain_extension = use_extension("@bazel_buildbuddy//:rules.bzl", "buildbuddy_toolchain_extension", dev_dependency = True) +inject_repo(buildbuddy_toolchain_extension, "platforms", "bazel_utilities") +buildbuddy_toolchain_extension.buildbuddy_toolchain(name = "buildbuddy") +use_repo(buildbuddy_toolchain_extension, "buildbuddy") +# register_toolchains("@buildbuddy//:gcc-toolchain") diff --git a/src/StreamFormat/Core/Prelude.h b/src/StreamFormat/Core/Prelude.h index 9704d8ce..4a38f055 100644 --- a/src/StreamFormat/Core/Prelude.h +++ b/src/StreamFormat/Core/Prelude.h @@ -35,16 +35,20 @@ #include #include +namespace StreamFormat::Detail +{ + template + T&& forward_error(T&& t) + { + return std::forward(t); + } +} + #define SF_TRY(exp) ({ \ auto __expected = exp; \ if (not __expected) [[unlikely]] \ - return std::unexpected(__expected.error()); \ + return StreamFormat::Detail::forward_error(std::unexpected(__expected.error())); \ __expected.value(); \ }); -#define SF_TRY_OR(exp, error) ({ \ - auto __expected = exp; \ - if (not __expected) [[unlikely]] \ - return std::unexpected(error); \ - __expected.value(); \ - }); \ No newline at end of file +#define SF_FORWARD(exp) SF_TRY(exp) diff --git a/src/StreamFormat/FLog/LoggerImpl/XLogger.h b/src/StreamFormat/FLog/LoggerImpl/XLogger.h index 39d565a3..41ff5e1a 100644 --- a/src/StreamFormat/FLog/LoggerImpl/XLogger.h +++ b/src/StreamFormat/FLog/LoggerImpl/XLogger.h @@ -87,66 +87,84 @@ namespace StreamFormat::FLog::Detail public: template requires FMT::Detail::ConvertibleToBufferInfoView - void Log(Severity status, Format&& format, Args&&... args) + [[nodiscard]] std::expected Log(Severity status, Format&& format, Args&&... args) { - Master::template Log(status, format, std::forward(args)...); + return Master::template Log(status, format, std::forward(args)...); } template - void Log(Severity status, T&& t) + [[nodiscard]] std::expected Log(Severity status, T&& t) { - Master::template Log(status, std::forward(t)); + return Master::template Log(status, std::forward(t)); } public: /////---------- Logger Severity with array as format ----------///// template requires FMT::Detail::ConvertibleToBufferInfoView - inline void Trace(Format&& format, Args&&... args) { return Log(LogSeverity::Trace, format, std::forward(args)...); } + inline std::expected Trace(Format&& format, Args&&... args) + { + return Log(LogSeverity::Trace, format, std::forward(args)...); + } template requires FMT::Detail::ConvertibleToBufferInfoView - inline void Debug(Format&& format, Args&&... args) { return Log(LogSeverity::Debug, format, std::forward(args)...); } + inline std::expected Debug(Format&& format, Args&&... args) + { + return Log(LogSeverity::Debug, format, std::forward(args)...); + } template requires FMT::Detail::ConvertibleToBufferInfoView - inline void Info(Format&& format, Args&&... args) { return Log(LogSeverity::Info, format, std::forward(args)...); } + inline std::expected Info(Format&& format, Args&&... args) + { + return Log(LogSeverity::Info, format, std::forward(args)...); + } template requires FMT::Detail::ConvertibleToBufferInfoView - inline void Warn(Format&& format, Args&&... args) { return Log(LogSeverity::Warn, format, std::forward(args)...); } + inline std::expected Warn(Format&& format, Args&&... args) + { + return Log(LogSeverity::Warn, format, std::forward(args)...); + } template requires FMT::Detail::ConvertibleToBufferInfoView - inline void Error(Format&& format, Args&&... args) { return Log(LogSeverity::Error, format, std::forward(args)...); } + inline std::expected Error(Format&& format, Args&&... args) + { + return Log(LogSeverity::Error, format, std::forward(args)...); + } template requires FMT::Detail::ConvertibleToBufferInfoView - inline void Fatal(Format&& format, Args&&... args) { return Log(LogSeverity::Fatal, format, std::forward(args)...); } + inline std::expected Fatal(Format&& format, Args&&... args) + { + return Log(LogSeverity::Fatal, format, std::forward(args)...); + } /////---------- NO-FORMAT Logger Severity ----------///// template - inline void Trace(T&& t) + inline std::expected Trace(T&& t) { return Log(LogSeverity::Trace, std::forward(t)); } template - inline void Debug(T&& t) + inline std::expected Debug(T&& t) { return Log(LogSeverity::Debug, std::forward(t)); } template - inline void Info(T&& t) + inline std::expected Info(T&& t) { return Log(LogSeverity::Info, std::forward(t)); } template - inline void Warn(T&& t) + inline std::expected Warn(T&& t) { return Log(LogSeverity::Warn, std::forward(t)); } template - inline void Error(T&& t) + inline std::expected Error(T&& t) { return Log(LogSeverity::Error, std::forward(t)); } template - inline void Fatal(T&& t) + inline std::expected Fatal(T&& t) { return Log(LogSeverity::Fatal, std::forward(t)); } diff --git a/src/StreamFormat/FLog/Loggers/BasicLogger.h b/src/StreamFormat/FLog/Loggers/BasicLogger.h index b025f545..db37630b 100644 --- a/src/StreamFormat/FLog/Loggers/BasicLogger.h +++ b/src/StreamFormat/FLog/Loggers/BasicLogger.h @@ -76,31 +76,35 @@ namespace StreamFormat::FLog::Detail template requires FMT::Detail::ConvertibleToBufferInfoView - void Log(const SeverityValueType& severity, Format&& format, Args&&... args) + [[nodiscard]] std::expected Log(const SeverityValueType& severity, Format&& format, Args&&... args) { if (severity < m_Severity) return; std::chrono::nanoseconds logTime = std::chrono::high_resolution_clock::now() - m_StartTime; - FMT::Detail::FormatInManager(preFormatBufferOutManager, false, FMT::Detail::BufferInfoView(m_Pattern), FORMAT_SV("time", logTime), FORMAT_SV("name", m_Name), - FORMAT_SV("data", FLog::AddIndentInFormat(format))); + SF_TRY(FMT::Detail::FormatInManager(preFormatBufferOutManager, false, FMT::Detail::BufferInfoView(m_Pattern), FORMAT_SV("time", logTime), FORMAT_SV("name", m_Name), + FORMAT_SV("data", FLog::AddIndentInFormat(format)))); - FMT::Detail::FormatInManager(fullFormatBufferOutManager, true, preFormatBufferOutManager.GetLastGeneratedBufferInfoView(), std::forward(args)..., FORMAT_SV("color", severity)); + SF_TRY(FMT::Detail::FormatInManager(fullFormatBufferOutManager, true, preFormatBufferOutManager.GetLastGeneratedBufferInfoView(), std::forward(args)..., FORMAT_SV("color", severity))); m_Stream.write(fullFormatBufferOutManager.GetBuffer(), static_cast(fullFormatBufferOutManager.GetLastGeneratedDataSize())); m_Stream.flush(); + + return {}; } template - void Log(const SeverityValueType& severity, T&& t) + [[nodiscard]] std::expected Log(const SeverityValueType& severity, T&& t) { if (severity < m_Severity) return; std::chrono::nanoseconds logTime = std::chrono::high_resolution_clock::now() - m_StartTime; - FMT::Detail::FormatInManager(fullFormatBufferOutManager, true, FMT::Detail::BufferInfoView(m_Pattern), FORMAT_SV("data", t), FORMAT_SV("color", severity), - FORMAT_SV("time", logTime), FORMAT_SV("name", m_Name)); + SF_TRY(FMT::Detail::FormatInManager(fullFormatBufferOutManager, true, FMT::Detail::BufferInfoView(m_Pattern), FORMAT_SV("data", t), FORMAT_SV("color", severity), + FORMAT_SV("time", logTime), FORMAT_SV("name", m_Name))); m_Stream.write(fullFormatBufferOutManager.GetBuffer(), static_cast(fullFormatBufferOutManager.GetLastGeneratedDataSize())); m_Stream.flush(); + + return {}; } }; } diff --git a/src/StreamFormat/FLog/Loggers/LoggerMultiSinkFast.h b/src/StreamFormat/FLog/Loggers/LoggerMultiSinkFast.h index 9ede672b..a91eaf5e 100644 --- a/src/StreamFormat/FLog/Loggers/LoggerMultiSinkFast.h +++ b/src/StreamFormat/FLog/Loggers/LoggerMultiSinkFast.h @@ -31,36 +31,44 @@ namespace StreamFormat::FLog::Detail ~BasicLoggerMultiSinkFastImpl() override = default; + public: + void Await(const SeverityValueType& severity) + { + for (auto& sink : m_Sinks) + if (sink->NeedToLog(severity)) sink->WaitUnitlFinishedToWrite(); + } + public: template requires FMT::Detail::ConvertibleToBufferInfoView - void Log(const SeverityValueType& severity, const Format& format, Args&&... args) + [[nodiscard]] std::expected Log(const SeverityValueType& severity, const Format& format, Args&&... args) { std::chrono::nanoseconds logTime = std::chrono::high_resolution_clock::now() - m_StartTime; FMT::Detail::DynamicBufferOutManager manager(256); - auto formatBuffer = FMT::Detail::FormatInManager(manager, false, format, std::forward(args)...); + auto formatBuffer = SF_TRY(FMT::Detail::FormatInManager(manager, false, format, std::forward(args)...)); for (auto& sink : m_Sinks) if (sink->NeedToLog(severity)) - sink->FormatAndWriteToSink(sink->GetPattern(severity), logTime, m_Name, static_cast>(*formatBuffer)); + { SF_TRY(sink->FormatAndWriteToSink(sink->GetPattern(severity), logTime, m_Name, static_cast>(*formatBuffer))); } - for (auto& sink : m_Sinks) - if (sink->NeedToLog(severity)) sink->WaitUnitlFinishedToWrite(); + Await(severity); + return {}; } template - void Log(const SeverityValueType& severity, T&& t) + [[nodiscard]] std::expected Log(const SeverityValueType& severity, T&& t) { std::chrono::nanoseconds logTime = std::chrono::high_resolution_clock::now() - m_StartTime; FMT::Detail::DynamicBufferOutManager manager(256); - auto formatBuffer = FMT::Detail::FormatInManager(manager, false, std::forward(t)); + auto formatBuffer = SF_TRY(FMT::Detail::FormatInManager(manager, false, std::forward(t))); for (auto& sink : m_Sinks) if (sink->NeedToLog(severity)) - sink->FormatAndWriteToSink(sink->GetPattern(severity), logTime, m_Name, static_cast>(*formatBuffer)); + { SF_TRY(sink->FormatAndWriteToSink(sink->GetPattern(severity), logTime, m_Name, static_cast>(*formatBuffer))); } - for (auto& sink : m_Sinks) - if (sink->NeedToLog(severity)) sink->WaitUnitlFinishedToWrite(); + Await(severity); + + return {}; } }; } diff --git a/src/StreamFormat/FLog/Loggers/LoggerMultiSinkSafe.h b/src/StreamFormat/FLog/Loggers/LoggerMultiSinkSafe.h index 2defd367..984bfec0 100644 --- a/src/StreamFormat/FLog/Loggers/LoggerMultiSinkSafe.h +++ b/src/StreamFormat/FLog/Loggers/LoggerMultiSinkSafe.h @@ -31,10 +31,17 @@ namespace StreamFormat::FLog::Detail ~BasicLoggerMultiSinkSafeImpl() override = default; + public: + void Await(const SeverityValueType& severity) + { + for (auto& sink : m_Sinks) + if (sink->NeedToLog(severity)) sink->WaitUnitlFinishedToWrite(); + } + public: template requires FMT::Detail::ConvertibleToBufferInfoView - void Log(const SeverityValueType& severity, const Format& format, Args&&... args) + [[nodiscard]] std::expected Log(const SeverityValueType& severity, const Format& format, Args&&... args) { std::chrono::nanoseconds logTime = std::chrono::high_resolution_clock::now() - m_StartTime; @@ -46,20 +53,20 @@ namespace StreamFormat::FLog::Detail FMT::Detail::DynamicBufferOutManager managerPattern(256); FMT::Detail::DynamicBufferOutManager managerFormat(256); auto formatPatternStr = - FMT::Detail::FormatInManager(managerPattern, false, std::string_view(sink->GetPattern(severity)), FORMAT_SV("time", logTime), - FORMAT_SV("name", FuturConcateNameAndSinkName(m_Name)), FORMAT_SV("data", FLog::AddIndentInFormat(format))); - auto formatFormatStr = FMT::Detail::FormatInManager(managerFormat, false, static_cast(*formatPatternStr), std::forward(args)..., - FORMAT_SV("sink", sink->GetName()), FORMAT_SV("color", severity)); - sink->WriteToSink(static_cast>(*formatFormatStr)); + SF_TRY(FMT::Detail::FormatInManager(managerPattern, false, std::string_view(sink->GetPattern(severity)), FORMAT_SV("time", logTime), + FORMAT_SV("name", FuturConcateNameAndSinkName(m_Name)), FORMAT_SV("data", FLog::AddIndentInFormat(format)))); + auto formatFormatStr = SF_TRY(FMT::Detail::FormatInManager(managerFormat, false, static_cast(*formatPatternStr), std::forward(args)..., + FORMAT_SV("sink", sink->GetName()), FORMAT_SV("color", severity))); + SF_TRY(sink->WriteToSink(static_cast>(*formatFormatStr))); } } - - for (auto& sink : m_Sinks) - if (sink->NeedToLog(severity)) sink->WaitUnitlFinishedToWrite(); + + Await(severity); + return {}; } template - void Log(const SeverityValueType& severity, T&& t) + [[nodiscard]] std::expected Log(const SeverityValueType& severity, T&& t) { std::chrono::nanoseconds logTime = std::chrono::high_resolution_clock::now() - m_StartTime; @@ -68,14 +75,14 @@ namespace StreamFormat::FLog::Detail if (sink->NeedToLog(severity)) { FMT::Detail::DynamicBufferOutManager manager(256); - auto formatBuffer = FMT::Detail::FormatInManager(manager, false, std::string_view(sink->GetPattern(severity)), FORMAT_SV("time", logTime), - FORMAT_SV("name", ConcateNameAndSinkName(m_Name, sink->GetName())), FORMAT_SV("data", t)); - sink->WriteToSink(static_cast>(*formatBuffer)); + auto formatBuffer = SF_TRY(FMT::Detail::FormatInManager(manager, false, std::string_view(sink->GetPattern(severity)), FORMAT_SV("time", logTime), + FORMAT_SV("name", ConcateNameAndSinkName(m_Name, sink->GetName())), FORMAT_SV("data", t))); + SF_TRY(sink->WriteToSink(static_cast>(*formatBuffer))); } } - for (auto& sink : m_Sinks) - if (sink->NeedToLog(severity)) sink->WaitUnitlFinishedToWrite(); + Await(severity); + return {}; } }; } diff --git a/src/StreamFormat/FLog/Sinks/LoggerSink.h b/src/StreamFormat/FLog/Sinks/LoggerSink.h index 1bdebd99..9442e9e7 100644 --- a/src/StreamFormat/FLog/Sinks/LoggerSink.h +++ b/src/StreamFormat/FLog/Sinks/LoggerSink.h @@ -50,7 +50,8 @@ namespace StreamFormat::FLog::Detail bool NeedToLog(const SeverityValueType& severity) { return severity >= SinkSeverity; } void WriteToSink(const SeverityValueType& severity, const BufferType& bufferToPrint) { - if (NeedToLog(severity)) WriteToSink(bufferToPrint); + if (NeedToLog(severity)) + WriteToSink(bufferToPrint); } public: @@ -85,26 +86,28 @@ namespace StreamFormat::FLog::Detail if (IsAsync == AsyncSink::Async) return m_AsyncWaiter.get(); } - void FormatAndWriteToSinkSync(PatternTransfertType pattern, const std::chrono::nanoseconds& logTime, const NameType& loggerName, const BufferType& formatBuffer) + [[nodiscard]] std::expected FormatAndWriteToSinkSync(PatternTransfertType pattern, const std::chrono::nanoseconds& logTime, const NameType& loggerName, const BufferType& formatBuffer) { FMT::Detail::DynamicBufferOutManager manager(256); - auto formatPatternStr = FMT::Detail::FormatInManager(manager, false, pattern, FORMAT_SV("time", logTime), FORMAT_SV("name", ConcateNameAndSinkName(loggerName, Name)), - FORMAT_SV("data", formatBuffer)); + auto formatPatternStr = SF_TRY(FMT::Detail::FormatInManager(manager, false, pattern, FORMAT_SV("time", logTime), FORMAT_SV("name", ConcateNameAndSinkName(loggerName, Name)), + FORMAT_SV("data", formatBuffer))); BufferType buffer(*formatPatternStr); WriteToSinkSync(buffer); + return {}; } - void FormatAndWriteToSinkAsync(PatternTransfertType pattern, const std::chrono::nanoseconds& logTime, const NameType& loggerName, const BufferType& formatBuffer) + [[nodiscard]] std::expected FormatAndWriteToSinkAsync(PatternTransfertType pattern, const std::chrono::nanoseconds& logTime, const NameType& loggerName, const BufferType& formatBuffer) { + // TODO m_AsyncWaiter = std::async(std::launch::async, &BasicLoggerSink::FormatAndWriteToSinkSync, this, pattern, logTime, loggerName, formatBuffer); + return {}; } - void FormatAndWriteToSink(PatternTransfertType pattern, const std::chrono::nanoseconds& logTime, const NameType& loggerName, const BufferType& formatBuffer) + [[nodiscard]] std::expected FormatAndWriteToSink(PatternTransfertType pattern, const std::chrono::nanoseconds& logTime, const NameType& loggerName, const BufferType& formatBuffer) { if (IsAsync == AsyncSink::Sync) - FormatAndWriteToSinkSync(pattern, logTime, loggerName, formatBuffer); - else - FormatAndWriteToSinkAsync(pattern, logTime, loggerName, formatBuffer); + return FormatAndWriteToSinkSync(pattern, logTime, loggerName, formatBuffer); + return FormatAndWriteToSinkAsync(pattern, logTime, loggerName, formatBuffer); } }; } diff --git a/src/StreamFormat/FMT/Buffer/BufferOutManager/BasicBufferOutManager.h b/src/StreamFormat/FMT/Buffer/BufferOutManager/BasicBufferOutManager.h index 7cf9d3b1..4c97d0eb 100644 --- a/src/StreamFormat/FMT/Buffer/BufferOutManager/BasicBufferOutManager.h +++ b/src/StreamFormat/FMT/Buffer/BufferOutManager/BasicBufferOutManager.h @@ -15,7 +15,7 @@ namespace StreamFormat::FMT::Detail BasicBufferOutManager& operator=(BasicBufferOutManager&) = delete; protected: - [[nodiscard]] virtual std::expected BeginContextImpl() {} + [[nodiscard]] virtual std::expected BeginContextImpl() { return {}; } virtual void ComputeGeneratedSizeImpl(const std::size_t /* totalGeneratedLength */) {} public: diff --git a/src/StreamFormat/FMT/Buffer/BufferTestManip.h b/src/StreamFormat/FMT/Buffer/BufferTestManip.h index c5c7da60..b96a8e04 100644 --- a/src/StreamFormat/FMT/Buffer/BufferTestManip.h +++ b/src/StreamFormat/FMT/Buffer/BufferTestManip.h @@ -51,7 +51,7 @@ namespace StreamFormat::FMT::Detail isSame = *bufferStr++ == *str++; --size; } - if (size != 0 && *str != 0) + if (size != 0) { return false; } return isSame; } @@ -103,7 +103,7 @@ namespace StreamFormat::FMT::Detail { if (Access().IsSame(str, size)) { - SF_TRY(BufferManip(Buffer).Forward()); + SF_TRY(BufferManip(Buffer).Forward(size)); return true; } return false; @@ -113,7 +113,7 @@ namespace StreamFormat::FMT::Detail { if (Access().IsSame(sv)) { - SF_TRY(BufferManip(Buffer).Forward()); + SF_TRY(BufferManip(Buffer).Forward(sv.size())); return true; } return false; diff --git a/src/StreamFormat/FMT/Buffer/FMTBufferOutManip.h b/src/StreamFormat/FMT/Buffer/FMTBufferOutManip.h index 6f1ae1ed..818103bf 100644 --- a/src/StreamFormat/FMT/Buffer/FMTBufferOutManip.h +++ b/src/StreamFormat/FMT/Buffer/FMTBufferOutManip.h @@ -109,7 +109,9 @@ namespace StreamFormat::FMT::Detail TChar* const oldpos = Buffer.CurrentPos; auto isSame = SF_TRY(manip.IsSameForward(sv)); if (isSame && (access.IsEqualTo(':') || access.IsEqualTo('}'))) - { return true; } + { + return true; + } Buffer.CurrentPos = oldpos; return false; } diff --git a/src/StreamFormat/FMT/Context/BasicContext/BasicContext.h b/src/StreamFormat/FMT/Context/BasicContext/BasicContext.h index 0371e5eb..a5cf7c36 100644 --- a/src/StreamFormat/FMT/Context/BasicContext/BasicContext.h +++ b/src/StreamFormat/FMT/Context/BasicContext/BasicContext.h @@ -62,6 +62,11 @@ namespace StreamFormat::FMT::Context public: [[nodiscard]] std::expected Run(); + private: + [[nodiscard]] std::expected GetFormatIndex_Number(); + [[nodiscard]] std::expected GetFormatIndex_Name(); + [[nodiscard]] std::expected GetFormatIndex_SubIndex(); + public: [[nodiscard]] std::expected GetFormatIndex(); template diff --git a/src/StreamFormat/FMT/Context/BasicContext/BasicContextParse-impl.h b/src/StreamFormat/FMT/Context/BasicContext/BasicContextParse-impl.h index 8b5e53ef..9d2a9c5f 100644 --- a/src/StreamFormat/FMT/Context/BasicContext/BasicContextParse-impl.h +++ b/src/StreamFormat/FMT/Context/BasicContext/BasicContextParse-impl.h @@ -217,56 +217,82 @@ namespace StreamFormat::FMT::Context return {}; } + template - [[nodiscard]] std::expected BasicContext::GetFormatIndex() + [[nodiscard]] std::expected BasicContext::GetFormatIndex_Number() + { + std::int32_t index = -1; + SF_TRY(Detail::BufferReadManip(Format).FastReadInteger(index)); + + if (Detail::BufferTestAccess(Format).IsEqualTo(':') || Detail::BufferTestAccess(Format).IsEqualTo('}')) + { + if (index >= 0 && index < ArgsInterface.Size()) + { return index; } + } + + return std::unexpected(FMTResult::Context_ArgumentIndexResolution); + } + template + [[nodiscard]] std::expected BasicContext::GetFormatIndex_Name() { - const TChar* mainSubFormat = Format.CurrentPos; + std::int32_t index = SF_TRY(ArgsInterface.GetIndexOfCurrentNamedArg(Format)); + if (Detail::BufferTestAccess(Format).IsEqualTo(':') || Detail::BufferTestAccess(Format).IsEqualTo('}')) + { + if (index >= 0 && index < ArgsInterface.Size()) + { return index; } + } + return std::unexpected(FMTResult::Context_ArgumentIndexResolution); + } + template + [[nodiscard]] std::expected BasicContext::GetFormatIndex_SubIndex() + { Detail::BufferTestAccess access(Format); Detail::BufferTestManip manip(Format); + SF_TRY(Detail::BufferManip(Format).Forward()); + std::int32_t recIndex = SF_TRY(GetFormatIndex()); + if (access.IsEqualTo('}') && recIndex >= 0 && recIndex < ArgsInterface.Size()) + { + SF_TRY(Detail::BufferManip(Format).Forward()); + manip.SkipAllSpaces(); + if (access.IsEqualTo(':', '}')) + { + std::int32_t finalRecIndex = (std::int32_t)SF_TRY(ArgsInterface.GetIntAt(recIndex)); + if (finalRecIndex >= 0 && finalRecIndex < ArgsInterface.Size()) + return finalRecIndex; + } + } + return std::unexpected(FMTResult::Context_ArgumentIndexResolution); + } + + template + [[nodiscard]] std::expected BasicContext::GetFormatIndex() + { + Detail::BufferTestAccess access(Format); + // I : if there is no number specified : ':' or '}' if (access.IsEqualTo(':') || access.IsEqualTo('}')) if (ValuesIndex < ArgsInterface.Size()) { return ValuesIndex++; } // II: A number(idx) - std::int32_t subIndex = -1; - if (Detail::BufferReadManip(Format).FastReadInteger(subIndex).has_value()) - if (access.IsEqualTo(':') || access.IsEqualTo('}')) - if (subIndex >= 0 && subIndex < ArgsInterface.Size()) - { return subIndex; } - Format.CurrentPos = mainSubFormat; + if (access.IsADigit()) + { + return SF_FORWARD(GetFormatIndex_Number()); + } // III : A name - auto currentNamedArg = ArgsInterface.GetIndexOfCurrentNamedArg(Format); - if (currentNamedArg.has_value()) + if (access.IsLowerCase() || access.IsUpperCase()) { - std::int32_t indexOfNamedArg = currentNamedArg.value(); - if (indexOfNamedArg >= 0 && indexOfNamedArg < ArgsInterface.Size()) - { return indexOfNamedArg; } - Format.CurrentPos = mainSubFormat; + return SF_FORWARD(GetFormatIndex_Name()); } // VI : { which is a idx to an argument if (access.IsEqualTo('{')) { - SF_TRY(Detail::BufferManip(Format).Forward()); - std::int32_t recIndex = SF_TRY(GetFormatIndex()); - if (access.IsEqualTo('}') && recIndex >= 0 && recIndex < ArgsInterface.Size()) - { - SF_TRY(Detail::BufferManip(Format).Forward()); - manip.SkipAllSpaces(); - if (access.IsEqualTo(':', '}')) - { - std::int32_t finalRecIndex = (std::int32_t)SF_TRY(ArgsInterface.GetIntAt(recIndex)); - if (finalRecIndex >= 0 && finalRecIndex < ArgsInterface.Size()) - return finalRecIndex; - return std::unexpected(FMTResult::Context_ArgumentIndexResolution); - } - } + return SF_FORWARD(GetFormatIndex_SubIndex()); } - Format.CurrentPos = mainSubFormat; return std::unexpected(FMTResult::Context_ArgumentIndexResolution); } @@ -305,11 +331,14 @@ namespace StreamFormat::FMT::Context return Detail::FMTBufferParamsManip(Format).ParamGoToForward(); // Skip } } - std::int32_t formatIdx = SF_TRY(GetFormatIndex()); - if (formatIdx >= 0 && formatIdx < ArgsInterface.Size()) + auto formatIdx = GetFormatIndex(); + if (formatIdx.has_value()) { - SF_TRY(ParseVariable(formatIdx)); - return Detail::FMTBufferParamsManip(Format).ParamGoToForward(); // Skip } + if (formatIdx.value() >= 0 && formatIdx.value() < ArgsInterface.Size()) + { + SF_TRY(ParseVariable(formatIdx.value())); + return Detail::FMTBufferParamsManip(Format).ParamGoToForward(); // Skip } + } } SF_TRY(Executor.ExecRawString("{")); diff --git a/src/StreamFormat/FMT/Context/FormatterExecutor/FormatterArgs.h b/src/StreamFormat/FMT/Context/FormatterExecutor/FormatterArgs.h index a3ebe5e8..2c9f0bad 100644 --- a/src/StreamFormat/FMT/Context/FormatterExecutor/FormatterArgs.h +++ b/src/StreamFormat/FMT/Context/FormatterExecutor/FormatterArgs.h @@ -24,21 +24,21 @@ namespace StreamFormat::FMT::Detail template [[nodiscard]] inline std::expected RunTypeAtIndex(FormatterExecutor&, std::int32_t) { - return std::unexpected(FMTResult::ArgsInterface_Unavaible); + return std::unexpected(FMTResult::ArgsInterface_IndexOutOfBounds); } template [[nodiscard]] inline std::expected GetIndexOfCurrentNamedArg(BufferInfoView&, std::int32_t) { - return std::unexpected(FMTResult::ArgsInterface_Unavaible); + return std::unexpected(FMTResult::ArgsInterface_CantMatchNamedArgs); } [[nodiscard]] inline std::expected GetPointerIDAt(std::int32_t) { - return std::unexpected(FMTResult::ArgsInterface_Unavaible); + return std::unexpected(FMTResult::ArgsInterface_IndexOutOfBounds); } template [[nodiscard]] inline std::expected GetConvertedTypeAt(std::int32_t) { - return std::unexpected(FMTResult::ArgsInterface_Unavaible); + return std::unexpected(FMTResult::ArgsInterface_IndexOutOfBounds); } }; diff --git a/src/StreamFormat/FMT/Context/ParserExecutor/ParserArgs.h b/src/StreamFormat/FMT/Context/ParserExecutor/ParserArgs.h index 6e1696ec..cf7e36ba 100644 --- a/src/StreamFormat/FMT/Context/ParserExecutor/ParserArgs.h +++ b/src/StreamFormat/FMT/Context/ParserExecutor/ParserArgs.h @@ -24,21 +24,21 @@ namespace StreamFormat::FMT::Detail template [[nodiscard]] inline std::expected RunTypeAtIndex(FormatterExecutor&, std::int32_t) { - return std::unexpected(FMTResult::ArgsInterface_Unavaible); + return std::unexpected(FMTResult::ArgsInterface_IndexOutOfBounds); } template [[nodiscard]] inline std::expected GetIndexOfCurrentNamedArg(BufferInfoView& format, std::int32_t) { - return std::unexpected(FMTResult::ArgsInterface_Unavaible); + return std::unexpected(FMTResult::ArgsInterface_CantMatchNamedArgs); } [[nodiscard]] inline std::expected GetPointerIDAt(std::int32_t) { - return std::unexpected(FMTResult::ArgsInterface_Unavaible); + return std::unexpected(FMTResult::ArgsInterface_IndexOutOfBounds); } template [[nodiscard]] inline std::expected GetConvertedTypeAt(std::int32_t) { - return std::unexpected(FMTResult::ArgsInterface_Unavaible); + return std::unexpected(FMTResult::ArgsInterface_IndexOutOfBounds); } }; diff --git a/src/StreamFormat/FMT/Detail/FMTResult.h b/src/StreamFormat/FMT/Detail/FMTResult.h index 41ffd0e5..c8504344 100644 --- a/src/StreamFormat/FMT/Detail/FMTResult.h +++ b/src/StreamFormat/FMT/Detail/FMTResult.h @@ -14,6 +14,8 @@ namespace StreamFormat::FMT ArgsInterface_Unavaible, ArgsInterface_InvalidTypeID, ArgsInterface_InvalidConversion, + ArgsInterface_CantMatchNamedArgs, + ArgsInterface_IndexOutOfBounds, Specifers_Full, Specifers_Invalid, diff --git a/src/StreamFormat/FMT/Serializers/FormatChrono.h b/src/StreamFormat/FMT/Serializers/FormatChrono.h index a2d9524f..20c028c4 100644 --- a/src/StreamFormat/FMT/Serializers/FormatChrono.h +++ b/src/StreamFormat/FMT/Serializers/FormatChrono.h @@ -24,7 +24,8 @@ namespace StreamFormat::FMT::Detail ShiftInfo shift; shift.Type = Detail::ShiftInfo::ShiftType::Right; shift.Print = Detail::ShiftInfo::ShiftPrint('0', ' '); - SF_TRY(BufferReadManip(pattern).FastReadInteger(shift.Size)); + shift.Size = 0; + (void)BufferReadManip(pattern).FastReadInteger(shift.Size); if (mode == TimePrintMode::Mod && shift.Size < 0) shift.Size = 3; From 27f6470a3737c273027fcaaaf6550f0dab1f0136 Mon Sep 17 00:00:00 2001 From: BELLIER Sacha Date: Thu, 28 Nov 2024 21:42:03 +0100 Subject: [PATCH 07/42] ... wip ... --- BUILD.bazel | 8 +- Examples/HelloWorld/main.cpp | 2 + src/StreamFormat/FLog/Loggers/BasicLogger.h | 6 +- src/StreamFormat/FMT/Buffer/BufferTestManip.h | 25 ++-- .../FMT/Buffer/BufferWriteManip.h | 2 + .../FMT/Buffer/FMTBufferReadManip.h | 12 +- .../FMT/Buffer/Utils/BufferShiftManip.h | 4 +- .../FMT/Buffer/Utils/BufferUtils.h | 8 +- .../Context/BasicContext/BasicArgsInterface.h | 2 +- .../BasicContext/BasicContextParse-impl.h | 117 +++++++++++------- .../BasicContext/TextPropertiesManager-impl.h | 24 ++-- .../BasicContext/TextPropertiesManager.h | 3 + .../FormatterExecutor/FormatBasics-impl.h | 7 +- .../Context/FormatterExecutor/FormatterType.h | 13 +- .../FormatterExecutor/UtilityFunctions.h | 10 ++ .../Context/ParserExecutor/ParseBasics-impl.h | 12 +- src/StreamFormat/FMT/Detail/FMTResult.h | 1 + src/StreamFormat/Json/JsonParser.cpp | 2 +- src/StreamFormat/Json/JsonSerializer.h | 6 +- .../Json/Serializers/JsonObjectsSerializer.h | 2 +- 20 files changed, 171 insertions(+), 95 deletions(-) diff --git a/BUILD.bazel b/BUILD.bazel index 93515647..d9fd5828 100644 --- a/BUILD.bazel +++ b/BUILD.bazel @@ -22,7 +22,13 @@ cc_test( srcs = glob([ "Tests/**/*.h", "Tests/**/*.cpp" ]), copts = select({ "@rules_cc//cc/compiler:msvc-cl": ["/std:latest"], - "//conditions:default": ["-std=c++23"], + "//conditions:default": [ + "-std=c++23", + "-Wall", "-Wextra", "-Wpedantic", + "-Wshadow", + "-Wconversion", "-Wsign-conversion", + "-Werror=return-type" + ], }), deps = [ ":StreamFormat" ], linkopts = select({ diff --git a/Examples/HelloWorld/main.cpp b/Examples/HelloWorld/main.cpp index cca27e5e..ea81f1b4 100644 --- a/Examples/HelloWorld/main.cpp +++ b/Examples/HelloWorld/main.cpp @@ -6,6 +6,8 @@ int main() { + StreamFormat::FMT::FilePrint(std::cout, "HelloWorld {} !", "ahhh"); + StreamFormat::FLog::DefaultLogger::Core().Info("HelloWorld !"); using namespace std::chrono_literals; diff --git a/src/StreamFormat/FLog/Loggers/BasicLogger.h b/src/StreamFormat/FLog/Loggers/BasicLogger.h index db37630b..0a6d6cb4 100644 --- a/src/StreamFormat/FLog/Loggers/BasicLogger.h +++ b/src/StreamFormat/FLog/Loggers/BasicLogger.h @@ -78,7 +78,8 @@ namespace StreamFormat::FLog::Detail requires FMT::Detail::ConvertibleToBufferInfoView [[nodiscard]] std::expected Log(const SeverityValueType& severity, Format&& format, Args&&... args) { - if (severity < m_Severity) return; + if (severity < m_Severity) + return {}; std::chrono::nanoseconds logTime = std::chrono::high_resolution_clock::now() - m_StartTime; @@ -95,7 +96,8 @@ namespace StreamFormat::FLog::Detail template [[nodiscard]] std::expected Log(const SeverityValueType& severity, T&& t) { - if (severity < m_Severity) return; + if (severity < m_Severity) + return {}; std::chrono::nanoseconds logTime = std::chrono::high_resolution_clock::now() - m_StartTime; diff --git a/src/StreamFormat/FMT/Buffer/BufferTestManip.h b/src/StreamFormat/FMT/Buffer/BufferTestManip.h index b96a8e04..35e83d1c 100644 --- a/src/StreamFormat/FMT/Buffer/BufferTestManip.h +++ b/src/StreamFormat/FMT/Buffer/BufferTestManip.h @@ -123,23 +123,34 @@ namespace StreamFormat::FMT::Detail template [[nodiscard]] inline std::expected SkipOneOf(const CharToTest... ele) noexcept { - SF_TRY(IsEqualToForward(ele...)); - return {}; + if (Access().IsEqualTo(ele...)) + { + SF_TRY(BufferManip(Buffer).Forward()); + return; + } + return std::unexpected(FMTResult::Parse_TokenNotExpected); + } + + template + inline void IgnoreOneOf(const CharToTest... ele) noexcept + { + if (Access().IsEqualTo(ele...) && BufferAccess(Buffer).CanMoveForward()) + { BufferManip(Buffer).ForceForward(); } } template - inline void SkipEvery(const CharToTest... ele) noexcept + inline void IgnoreEvery(const CharToTest... ele) noexcept { while (Access().IsEqualTo(ele...) && BufferAccess(Buffer).CanMoveForward()) { BufferManip(Buffer).ForceForward(); } } public: - [[nodiscard]] inline std::expected SkipSpace() noexcept { return SkipOneOf(' ', '\t'); } - [[nodiscard]] inline std::expected SkipBlank() noexcept { return SkipOneOf(' ', '\t', '\n', '\r', '\v'); } + [[nodiscard]] inline void IgnoreOneSpace() noexcept { return IgnoreOneOf(' ', '\t'); } + [[nodiscard]] inline void IgnoreOneBlank() noexcept { return IgnoreOneOf(' ', '\t', '\n', '\r', '\v'); } - inline void SkipAllSpaces() noexcept { SkipEvery(' ', '\t'); } - inline void SkipAllBlanks() noexcept { SkipEvery(' ', '\t', '\n', '\r', '\v'); } + inline void IgnoreEverySpaces() noexcept { IgnoreEvery(' ', '\t'); } + inline void IgnoreEveryBlanks() noexcept { IgnoreEvery(' ', '\t', '\n', '\r', '\v'); } public: template diff --git a/src/StreamFormat/FMT/Buffer/BufferWriteManip.h b/src/StreamFormat/FMT/Buffer/BufferWriteManip.h index d312176a..1d7d8de1 100644 --- a/src/StreamFormat/FMT/Buffer/BufferWriteManip.h +++ b/src/StreamFormat/FMT/Buffer/BufferWriteManip.h @@ -112,6 +112,8 @@ namespace StreamFormat::FMT::Detail SF_TRY(manip.Pushback(intPart + '0')); i -= intPart; } + + return {}; } public: diff --git a/src/StreamFormat/FMT/Buffer/FMTBufferReadManip.h b/src/StreamFormat/FMT/Buffer/FMTBufferReadManip.h index 55d3de89..466fc68b 100644 --- a/src/StreamFormat/FMT/Buffer/FMTBufferReadManip.h +++ b/src/StreamFormat/FMT/Buffer/FMTBufferReadManip.h @@ -24,7 +24,7 @@ namespace StreamFormat::FMT::Detail Detail::BufferTestAccess access(Buffer); Detail::BufferTestManip manip(Buffer); - SF_TRY(shiftManip.SkipShiftBeginSpace(shift)); + SF_TRY(shiftManip.IgnoreShiftBeginSpace(shift)); bool sign = false; if constexpr (std::is_signed_v) @@ -43,7 +43,7 @@ namespace StreamFormat::FMT::Detail --shift.Size; } - SF_TRY(shiftManip.SkipShiftEnd(shift)); + SF_TRY(shiftManip.IgnoreShiftEnd(shift)); i = sign ? -res : res; return {}; @@ -56,7 +56,7 @@ namespace StreamFormat::FMT::Detail Detail::BufferTestAccess access(Buffer); Detail::BufferTestManip manip(Buffer); - SF_TRY(shiftManip.SkipShiftBeginSpace(shift)); + SF_TRY(shiftManip.IgnoreShiftBeginSpace(shift)); bool sign = SF_TRY(manip.IsEqualToForward('-')); if (sign) --shift.Size; @@ -100,7 +100,7 @@ namespace StreamFormat::FMT::Detail dec /= 10; } - SF_TRY(shiftManip.SkipShiftEnd(shift)); + SF_TRY(shiftManip.IgnoreShiftEnd(shift)); t = sign ? - intpart - dec : intpart + dec; return {}; @@ -117,7 +117,7 @@ namespace StreamFormat::FMT::Detail shift.Size -= sizeof(T) * 8; if (base_prefix != '\0') shift.Size -= 2; - SF_TRY(shiftManip.SkipShiftBeginSpace(shift)); + SF_TRY(shiftManip.IgnoreShiftBeginSpace(shift)); if (base_prefix != '\0') { @@ -133,7 +133,7 @@ namespace StreamFormat::FMT::Detail BufferManip(Buffer).ForceForward(); } - SF_TRY(shiftManip.SkipShiftEnd(shift)); + SF_TRY(shiftManip.IgnoreShiftEnd(shift)); i = res; return {}; diff --git a/src/StreamFormat/FMT/Buffer/Utils/BufferShiftManip.h b/src/StreamFormat/FMT/Buffer/Utils/BufferShiftManip.h index 349ced5f..790cdb77 100644 --- a/src/StreamFormat/FMT/Buffer/Utils/BufferShiftManip.h +++ b/src/StreamFormat/FMT/Buffer/Utils/BufferShiftManip.h @@ -70,7 +70,7 @@ namespace StreamFormat::FMT::Detail BufferInfo& Buffer; public: - [[nodiscard]] std::expected SkipShiftBeginSpace(Detail::ShiftInfo& shift) + [[nodiscard]] std::expected IgnoreShiftBeginSpace(Detail::ShiftInfo& shift) { if (shift.Print.BeforeIsADigit() == false) return {}; @@ -86,7 +86,7 @@ namespace StreamFormat::FMT::Detail return {}; } - [[nodiscard]] std::expected SkipShiftEnd(Detail::ShiftInfo& shift) + [[nodiscard]] std::expected IgnoreShiftEnd(Detail::ShiftInfo& shift) { if (shift.Type == Detail::ShiftInfo::ShiftType::Left || shift.Type == Detail::ShiftInfo::ShiftType::CenterLeft || shift.Type == Detail::ShiftInfo::ShiftType::CenterRight) { diff --git a/src/StreamFormat/FMT/Buffer/Utils/BufferUtils.h b/src/StreamFormat/FMT/Buffer/Utils/BufferUtils.h index f582253e..80c394c5 100644 --- a/src/StreamFormat/FMT/Buffer/Utils/BufferUtils.h +++ b/src/StreamFormat/FMT/Buffer/Utils/BufferUtils.h @@ -63,7 +63,8 @@ namespace StreamFormat::FMT::Detail auto view = SF_TRY(Detail::BufferTestManip(buffer).ViewUntil('"', '\\')); SF_TRY(Detail::BufferWriteManip(stringOut).FastWriteString(view)); - if (Detail::BufferTestAccess(buffer).IsEqualTo('"')) break; + if (Detail::BufferTestAccess(buffer).IsEqualTo('"')) + { break; } SF_TRY(Detail::BufferTestManip(buffer).SkipOneOf('\\')); switch (buffer.Get()) @@ -86,6 +87,8 @@ namespace StreamFormat::FMT::Detail } } SF_TRY(Detail::BufferTestManip(buffer).SkipOneOf('"')); + + return {}; } template @@ -99,6 +102,7 @@ namespace StreamFormat::FMT::Detail if (Detail::BufferAccess(stringIn).IsEndOfString()) break; + // TODO SF_TRY(Detail::BufferTestManip(stringIn).SkipOneOf('\\')); switch (stringIn.Get()) { @@ -120,6 +124,8 @@ namespace StreamFormat::FMT::Detail } } SF_TRY(Detail::BufferOutManip(buffer).Pushback('"')); + + return {}; } }; } diff --git a/src/StreamFormat/FMT/Context/BasicContext/BasicArgsInterface.h b/src/StreamFormat/FMT/Context/BasicContext/BasicArgsInterface.h index 9171052f..0e865d00 100644 --- a/src/StreamFormat/FMT/Context/BasicContext/BasicArgsInterface.h +++ b/src/StreamFormat/FMT/Context/BasicContext/BasicArgsInterface.h @@ -74,7 +74,7 @@ namespace StreamFormat::FMT::Detail public: [[nodiscard]] std::expected GetPointerIDAt(std::int32_t) override { return std::unexpected(FMTResult::ArgsInterface_Unavaible); } [[nodiscard]] std::expected RunTypeAtIndex(std::int32_t) override { return std::unexpected(FMTResult::ArgsInterface_Unavaible); } - [[nodiscard]] std::expected GetIndexOfCurrentNamedArg(BufferInfoView& format) override { return std::unexpected(FMTResult::ArgsInterface_Unavaible); } + [[nodiscard]] std::expected GetIndexOfCurrentNamedArg(BufferInfoView&) override { return std::unexpected(FMTResult::ArgsInterface_Unavaible); } [[nodiscard]] std::expected, FMTResult> GetStringAt(std::int32_t) override { return std::unexpected(FMTResult::ArgsInterface_Unavaible); } [[nodiscard]] std::expected GetIntAt(std::int32_t) override { return std::unexpected(FMTResult::ArgsInterface_Unavaible); } }; diff --git a/src/StreamFormat/FMT/Context/BasicContext/BasicContextParse-impl.h b/src/StreamFormat/FMT/Context/BasicContext/BasicContextParse-impl.h index 9d2a9c5f..071b09ff 100644 --- a/src/StreamFormat/FMT/Context/BasicContext/BasicContextParse-impl.h +++ b/src/StreamFormat/FMT/Context/BasicContext/BasicContextParse-impl.h @@ -14,30 +14,40 @@ namespace StreamFormat::FMT::Context template [[nodiscard]] std::expected, FMTResult> BasicContext::ParseNextOverrideFormatData() { + // TODO: check that function Detail::BufferTestAccess access(Format); Detail::BufferTestManip manip(Format); - manip.SkipAllSpaces(); + manip.IgnoreEverySpaces(); Detail::FMTBufferParamsManip(Format).ParamGoTo('{', '=', ':'); - manip.SkipAllSpaces(); - manip.IsEqualToForward('=', ':'); - manip.SkipAllSpaces(); + manip.IgnoreEverySpaces(); + manip.IgnoreOneOf('=', ':'); + manip.IgnoreEverySpaces(); Detail::FMTBufferParamsManip(Format).ParamGoTo('{'); const TChar* begin = Format.CurrentPos; - SF_TRY(manip.IsEqualToForward('{')); + SF_TRY(manip.SkipOneOf('{')); int scopes = 0; while (Detail::FMTBufferParamsManip(Format).IsEndOfParameter() == false || scopes > 0) { manip.GoTo('\'', '}', '{'); - if (manip.IsEqualToForward('\'')) + if (access.IsEqualTo('\'')) + { + SF_TRY(Detail::BufferManip(Format).Forward()); manip.GoToForward('\''); - else if (manip.IsEqualToForward('{')) + } + else if (access.IsEqualTo('{')) + { + SF_TRY(Detail::BufferManip(Format).Forward()); scopes++; - else if (scopes > 0 && manip.IsEqualToForward('}')) + } + else if (scopes > 0 && access.IsEqualTo('}')) + { + SF_TRY(Detail::BufferManip(Format).Forward()); scopes--; + } } - SF_TRY(manip.IsEqualToForward('}')); + manip.SkipOneOf('}'); const TChar* end = Format.CurrentPos; return std::basic_string_view(begin, end - begin); } @@ -45,20 +55,35 @@ namespace StreamFormat::FMT::Context template [[nodiscard]] std::expected BasicContext::ParseFormatDataBase() { - Detail::BufferTestManip manip(Format); + Detail::BufferTestAccess access(Format); - if (manip.IsEqualToForward('C')) - { SF_TRY(Executor.TextManager.ParseColor(*this)); } - else if (manip.IsEqualToForward('S')) - { SF_TRY(Executor.TextManager.ParseStyle(*this)); } - else if (manip.IsEqualToForward('F')) - { SF_TRY(Executor.TextManager.ParseFront(*this)); } + if (access.IsEqualTo('C')) + { + SF_TRY(Detail::BufferManip(Format).Forward()); + SF_TRY(Executor.TextManager.ParseColor(*this)); + } + else if (access.IsEqualTo('S')) + { + SF_TRY(Detail::BufferManip(Format).Forward()); + SF_TRY(Executor.TextManager.ParseStyle(*this)); + } + else if (access.IsEqualTo('F')) + { + SF_TRY(Detail::BufferManip(Format).Forward()); + SF_TRY(Executor.TextManager.ParseFront(*this)); + } - else if (manip.IsEqualToForward('K')) - { Executor.Data.KeepNewStyle = true; } + else if (access.IsEqualTo('K')) + { + SF_TRY(Detail::BufferManip(Format).Forward()); + Executor.Data.KeepNewStyle = true; + } - else if (manip.IsEqualToForward('N')) - { Executor.Data.NextOverride = SF_TRY(ParseNextOverrideFormatData()); } + else if (access.IsEqualTo('N')) + { + SF_TRY(Detail::BufferManip(Format).Forward()); + Executor.Data.NextOverride = SF_TRY(ParseNextOverrideFormatData()); + } return {}; } @@ -68,8 +93,9 @@ namespace StreamFormat::FMT::Context { Executor.Data.Shift.Type = type; Executor.Data.Shift.Size = SF_TRY(FormatReadParameter(-1)); - if (Detail::BufferTestManip(Format).IsEqualToForward(':')) + if (Detail::BufferTestAccess(Format).IsEqualTo(':')) { + Detail::BufferManip(Format).Forward(); Executor.Data.Shift.Print.Before = SF_TRY(Detail::BufferManip(Format).GetAndForward()); Executor.Data.Shift.Print.After = Executor.Data.Shift.Print.Before; if (Detail::BufferTestAccess(Format).IsEqualTo('|')) @@ -90,7 +116,7 @@ namespace StreamFormat::FMT::Context if (access.IsEqualTo('{')) { SF_TRY(Detail::BufferManip(Format).Forward()); - std::int32_t formatIndex = (std::int32_t)SF_TRY(GetFormatIndex()); + std::int32_t formatIndex = SF_TRY(GetFormatIndex()); bool ableToApply = false; auto applyFormatData = SF_TRY(ArgsInterface.template GetTypeAt>(formatIndex)); @@ -103,8 +129,8 @@ namespace StreamFormat::FMT::Context ableToApply |= Executor.Data.TestApply(applyShiftInfo); if (not ableToApply) - return std::unexpected(FMTResult::Context_CannotApplyType); - SF_TRY(manip.IsEqualToForward('}')); + { return std::unexpected(FMTResult::Context_CannotApplyType); } + SF_TRY(manip.SkipOneOf('}')); } else if (access.IsEqualTo('.')) @@ -145,7 +171,7 @@ namespace StreamFormat::FMT::Context } else { - SF_TRY(manip.IsEqualToForward('>')); + SF_TRY(manip.SkipOneOf('>')); SF_TRY(ParseFormatDataSpecial_ShiftType(Detail::ShiftInfo::ShiftType::CenterRight)); } } @@ -163,11 +189,12 @@ namespace StreamFormat::FMT::Context [&] -> std::expected { Detail::FMTBufferParamsManip(Format).ParamGoTo(' ', '=', '\'', '{', ','); return {}; } )); Detail::FMTBufferParamsManip(Format).ParamGoTo('=', '\'', '{', ','); - SF_TRY(manip.IsEqualToForward('=')); - manip.SkipAllSpaces(); + manip.IgnoreOneOf('='); + manip.IgnoreEverySpaces(); - if (manip.IsEqualToForward('\'')) + if (access.IsEqualTo('\'')) { + SF_TRY(Detail::BufferManip(Format).Forward()); std::basic_string_view value = SF_TRY(Detail::BufferTestManip(Format).ViewUntil('\'')); SF_TRY(Executor.Data.Specifiers.Concat(Detail::FormatSpecifier{name, value})); } @@ -177,12 +204,13 @@ namespace StreamFormat::FMT::Context SF_TRY(Detail::BufferReadManip(Format).FastReadInteger(value)); SF_TRY(Executor.Data.Specifiers.Concat(Detail::FormatSpecifier{name, value})); } - else if (manip.IsEqualToForward('{')) + else if (access.IsEqualTo('{')) { + SF_TRY(Detail::BufferManip(Format).Forward()); std::int32_t idx = SF_TRY(GetFormatIndex()); // TODO / FIXME // Executor.Data.Specifiers.Concat(Detail::FormatSpecifier{name, GetTypeAtIndexAuto(idx)}); - SF_TRY(manip.IsEqualToForward('}')); + SF_TRY(manip.SkipOneOf('}')); } else if (access.IsEqualTo(',', '}')) { @@ -202,7 +230,7 @@ namespace StreamFormat::FMT::Context Executor.Data.HasSpec = true; while (Detail::BufferAccess(Format).IsEndOfString() == false && Detail::FMTBufferParamsManip(Format).IsEndOfParameter() == false) { - manip.SkipAllSpaces(); + manip.IgnoreEverySpaces(); if (access.IsUpperCase()) { SF_TRY(ParseFormatDataBase()); } @@ -212,7 +240,7 @@ namespace StreamFormat::FMT::Context { SF_TRY(ParseFormatDataCustom()); } Detail::FMTBufferParamsManip(Format).ParamGoTo(','); - SF_TRY(Detail::BufferTestManip(Format).IsEqualToForward(',')); + SF_TRY(Detail::BufferTestManip(Format).SkipOneOf(',')); } return {}; } @@ -250,17 +278,20 @@ namespace StreamFormat::FMT::Context Detail::BufferTestAccess access(Format); Detail::BufferTestManip manip(Format); - SF_TRY(Detail::BufferManip(Format).Forward()); - std::int32_t recIndex = SF_TRY(GetFormatIndex()); - if (access.IsEqualTo('}') && recIndex >= 0 && recIndex < ArgsInterface.Size()) + if (access.IsEqualTo('{')) { SF_TRY(Detail::BufferManip(Format).Forward()); - manip.SkipAllSpaces(); - if (access.IsEqualTo(':', '}')) + std::int32_t recIndex = SF_TRY(GetFormatIndex()); + if (access.IsEqualTo('}') && recIndex >= 0 && recIndex < ArgsInterface.Size()) { - std::int32_t finalRecIndex = (std::int32_t)SF_TRY(ArgsInterface.GetIntAt(recIndex)); - if (finalRecIndex >= 0 && finalRecIndex < ArgsInterface.Size()) - return finalRecIndex; + SF_TRY(Detail::BufferManip(Format).Forward()); + manip.IgnoreEverySpaces(); + if (access.IsEqualTo(':', '}')) + { + std::int32_t finalRecIndex = (std::int32_t)SF_TRY(ArgsInterface.GetIntAt(recIndex)); + if (finalRecIndex >= 0 && finalRecIndex < ArgsInterface.Size()) + return finalRecIndex; + } } } return std::unexpected(FMTResult::Context_ArgumentIndexResolution); @@ -323,12 +354,12 @@ namespace StreamFormat::FMT::Context template [[nodiscard]] std::expected BasicContext::Parse() { - Detail::BufferManip(Format).Forward(); // Skip { + Detail::BufferManip(Format).Forward(); // Ignore { if (Detail::BufferTestAccess(Format).IsUpperCase()) { SF_TRY(ParseFormatData()); - return Detail::FMTBufferParamsManip(Format).ParamGoToForward(); // Skip } + return Detail::FMTBufferParamsManip(Format).ParamGoToForward(); // Ignore } } auto formatIdx = GetFormatIndex(); @@ -337,7 +368,7 @@ namespace StreamFormat::FMT::Context if (formatIdx.value() >= 0 && formatIdx.value() < ArgsInterface.Size()) { SF_TRY(ParseVariable(formatIdx.value())); - return Detail::FMTBufferParamsManip(Format).ParamGoToForward(); // Skip } + return Detail::FMTBufferParamsManip(Format).ParamGoToForward(); // Ignore } } } diff --git a/src/StreamFormat/FMT/Context/BasicContext/TextPropertiesManager-impl.h b/src/StreamFormat/FMT/Context/BasicContext/TextPropertiesManager-impl.h index 9d41255f..e0175029 100644 --- a/src/StreamFormat/FMT/Context/BasicContext/TextPropertiesManager-impl.h +++ b/src/StreamFormat/FMT/Context/BasicContext/TextPropertiesManager-impl.h @@ -73,13 +73,13 @@ namespace StreamFormat::FMT::Detail if (BufferTestAccess(context.Format).IsEqualTo(':')) { SF_TRY(BufferManip(context.Format).Forward()); - BufferTestManip(context.Format).SkipAllSpaces(); + BufferTestManip(context.Format).IgnoreEverySpaces(); if (BufferTestAccess(context.Format).IsEqualTo('{')) { SF_TRY(BufferManip(context.Format).Forward()); std::int32_t idx = SF_TRY(context.GetFormatIndex()); SF_TRY(ApplyColorOnIndex(context, idx)); - SF_TRY(BufferTestManip(context.Format).IsEqualToForward('}')); + SF_TRY(BufferTestManip(context.Format).SkipOneOf('}')); } else { @@ -88,7 +88,7 @@ namespace StreamFormat::FMT::Detail if (BufferTestAccess(context.Format).IsEqualTo('-')) { SF_TRY(BufferManip(context.Format).Forward()); - BufferTestManip(context.Format).SkipAllSpaces(); + BufferTestManip(context.Format).IgnoreEverySpaces(); auto colorBg = GetColorCode(context.Format); if (colorBg.has_value() && colorFg.has_value()) { return AskApplyColor(Detail::TextProperties::TextColor::BasicColor{colorFg.value(), colorBg.value()}); } @@ -117,31 +117,31 @@ namespace StreamFormat::FMT::Detail SF_TRY(BufferManip(context.Format).Forward()); if (!BufferTestAccess(context.Format).IsEqualTo('}', ',')) { - bool l = true; - while (l) + bool loop = true; + while (loop) { - BufferTestManip(context.Format).SkipAllSpaces(); + BufferTestManip(context.Format).IgnoreEverySpaces(); if (BufferTestAccess(context.Format).IsEqualTo('{')) { SF_TRY(BufferManip(context.Format).Forward()); std::int32_t idx = SF_TRY(context.GetFormatIndex()); ApplyStyleOnIndex(context, idx); - BufferTestManip(context.Format).IsEqualToForward('}'); + BufferTestManip(context.Format).SkipOneOf('}'); } else { ParseStyleNamed(context.Format); } FMTBufferParamsManip(context.Format).ParamGoTo('|', ','); - l = SF_TRY(BufferTestManip(context.Format).IsEqualToForward('|')); - BufferTestManip(context.Format).SkipAllSpaces(); + loop = SF_TRY(BufferTestManip(context.Format).IsEqualToForward('|')); + BufferTestManip(context.Format).IgnoreEverySpaces(); } } else - return ReloadDefaultStyle(); + { return ReloadDefaultStyle(); } } else - return ReloadDefaultStyle(); + { return ReloadDefaultStyle(); } return {}; } @@ -230,7 +230,7 @@ namespace StreamFormat::FMT::Detail if (BufferTestAccess(context.Format).IsEqualTo(':')) { SF_TRY(BufferManip(context.Format).Forward()); - BufferTestManip(context.Format).SkipAllSpaces(); + BufferTestManip(context.Format).IgnoreEverySpaces(); Detail::TextProperties::TextFront::FrontID frontID = (std::uint8_t)SF_TRY(BufferUtilsManip(context.Format).GetWordFromList(frontCode)); return ApplyFront(frontID); diff --git a/src/StreamFormat/FMT/Context/BasicContext/TextPropertiesManager.h b/src/StreamFormat/FMT/Context/BasicContext/TextPropertiesManager.h index 3d3b84a4..53cbbccb 100644 --- a/src/StreamFormat/FMT/Context/BasicContext/TextPropertiesManager.h +++ b/src/StreamFormat/FMT/Context/BasicContext/TextPropertiesManager.h @@ -116,6 +116,7 @@ namespace StreamFormat::FMT::Detail { if (m_CurrentContextProperties.Color.NeedModif(modif)) return ApplyColor(modif); + return {}; } template requires Detail::TextPropertiesStyleCanApply @@ -123,6 +124,7 @@ namespace StreamFormat::FMT::Detail { if (m_CurrentContextProperties.Style.NeedModif(modif)) return ApplyStyle(modif); + return {}; } template requires Detail::TextPropertiesFrontCanApply @@ -130,6 +132,7 @@ namespace StreamFormat::FMT::Detail { if (m_CurrentContextProperties.Front.NeedModif(modif)) return ApplyFront(modif); + return {}; } [[nodiscard]] std::expected AskApplyColor(const Detail::TextProperties::TextColor::BasicColor& modif) diff --git a/src/StreamFormat/FMT/Context/FormatterExecutor/FormatBasics-impl.h b/src/StreamFormat/FMT/Context/FormatterExecutor/FormatBasics-impl.h index 0e9b606c..67541508 100644 --- a/src/StreamFormat/FMT/Context/FormatterExecutor/FormatBasics-impl.h +++ b/src/StreamFormat/FMT/Context/FormatterExecutor/FormatBasics-impl.h @@ -58,15 +58,16 @@ namespace StreamFormat::FMT SF_TRY(executor.WriteType(*itbegin++)); } - SF_TRY(Detail::BufferWriteManip(executor.BufferOut).FastWriteString(executor.Data.Specifiers.GetAsText("end", STDEnumerableUtility::DefaultEnd))); + return Detail::BufferWriteManip(executor.BufferOut).FastWriteString(executor.Data.Specifiers.GetAsText("end", STDEnumerableUtility::DefaultEnd)); } template [[nodiscard]] std::expected FormatString(const T* buffer, std::size_t size, FormatterExecutor& executor) { std::size_t beginIdx = (std::size_t)executor.Data.Specifiers.GetAsNumber("begin", 0); - size = executor.Data.Specifiers.GetAsNumber("size", size); - if (size == std::numeric_limits::max()) size = std::basic_string_view(buffer).size(); + size = executor.Data.Specifiers.GetAsNumber("size", size); + if (size == std::numeric_limits::max()) + { size = std::basic_string_view(buffer).size(); } if (executor.Data.Specifiers.Has("array")) return FormatObjectArray(buffer, size, executor); diff --git a/src/StreamFormat/FMT/Context/FormatterExecutor/FormatterType.h b/src/StreamFormat/FMT/Context/FormatterExecutor/FormatterType.h index 179becb9..e141643e 100644 --- a/src/StreamFormat/FMT/Context/FormatterExecutor/FormatterType.h +++ b/src/StreamFormat/FMT/Context/FormatterExecutor/FormatterType.h @@ -19,6 +19,7 @@ namespace StreamFormat::FMT #ifdef UNKOWN_TYPE_DEBUG STREAMFORMAT_DEBUGBREAK(); #endif + return {}; } }; } @@ -27,12 +28,12 @@ namespace StreamFormat::FMT template \ struct StreamFormat::FMT::FormatterType \ { \ - [[nodiscard]] static std::expected Format(const Type& value, FormatterExecutor& executor) { return executor.Run(fmt, __VA_ARGS__); } \ + [[nodiscard]] static std::expected Format(const Type& value, FormatterExecutor& executor) { return executor.Run(fmt, __VA_ARGS__); } \ }; -#define STREAMFORMAT_AUTO_FORMATTER_T(Type, fmt, ...) \ - template \ - struct StreamFormat::FMT::FormatterType \ - { \ - [[nodiscard]] static std::expected Format(const Type&, FormatterExecutor& executor) { return executor.Run(fmt, __VA_ARGS__); } \ +#define STREAMFORMAT_AUTO_FORMATTER_T(Type, fmt, ...) \ + template \ + struct StreamFormat::FMT::FormatterType \ + { \ + [[nodiscard]] static std::expected Format(const Type&, FormatterExecutor& executor) { return executor.Run(fmt, __VA_ARGS__); } \ }; diff --git a/src/StreamFormat/FMT/Context/FormatterExecutor/UtilityFunctions.h b/src/StreamFormat/FMT/Context/FormatterExecutor/UtilityFunctions.h index c259b86a..05bac255 100644 --- a/src/StreamFormat/FMT/Context/FormatterExecutor/UtilityFunctions.h +++ b/src/StreamFormat/FMT/Context/FormatterExecutor/UtilityFunctions.h @@ -74,6 +74,7 @@ namespace StreamFormat::FMT std::fwrite(bufferOutManager.GetBuffer(), bufferOutManager.GetLastGeneratedDataSize(), 1, stream); std::fflush(stream); + return {}; } template @@ -85,6 +86,7 @@ namespace StreamFormat::FMT std::fwrite(bufferOutManager.GetBuffer(), bufferOutManager.GetLastGeneratedDataSize(), 1, stream); std::fflush(stream); + return {}; } template @@ -96,6 +98,7 @@ namespace StreamFormat::FMT stream.write(bufferOutManager.GetBuffer(), bufferOutManager.GetLastGeneratedDataSize()); stream.flush(); + return {}; } template @@ -107,6 +110,7 @@ namespace StreamFormat::FMT stream.write(bufferOutManager.GetBuffer(), bufferOutManager.GetLastGeneratedDataSize()); stream.flush(); + return {}; } template @@ -116,6 +120,7 @@ namespace StreamFormat::FMT Detail::DynamicBufferOutManager bufferOutManager(256); SF_TRY(Detail::FormatInManager(bufferOutManager, false, Detail::BufferInfoView{formatInput}, std::forward(args)...)); str = bufferOutManager.GetLastGeneratedString(); + return {}; } template @@ -154,6 +159,7 @@ namespace StreamFormat::FMT std::fwrite(bufferOutManager.GetBuffer(), static_cast(bufferOutManager.GetLastGeneratedDataSize()), 1, stream); std::fflush(stream); + return {}; } template @@ -165,6 +171,7 @@ namespace StreamFormat::FMT std::fwrite(bufferOutManager.GetBuffer(), static_cast(bufferOutManager.GetLastGeneratedDataSize()), 1, stream); std::fflush(stream); + return {}; } template @@ -176,6 +183,7 @@ namespace StreamFormat::FMT stream.write(bufferOutManager.GetBuffer(), static_cast(bufferOutManager.GetLastGeneratedDataSize())); stream.flush(); + return {}; } template @@ -187,6 +195,7 @@ namespace StreamFormat::FMT stream.write(bufferOutManager.GetBuffer(), static_cast(bufferOutManager.GetLastGeneratedDataSize())); stream.flush(); + return {}; } template @@ -196,6 +205,7 @@ namespace StreamFormat::FMT Detail::DynamicBufferOutManager bufferOutManager(32); SF_TRY(Detail::FormatInManager(bufferOutManager, false, std::forward(t))); str = bufferOutManager.GetLastGeneratedString(); + return {}; } template diff --git a/src/StreamFormat/FMT/Context/ParserExecutor/ParseBasics-impl.h b/src/StreamFormat/FMT/Context/ParserExecutor/ParseBasics-impl.h index a4792e7d..6ce903c7 100644 --- a/src/StreamFormat/FMT/Context/ParserExecutor/ParseBasics-impl.h +++ b/src/StreamFormat/FMT/Context/ParserExecutor/ParseBasics-impl.h @@ -20,19 +20,19 @@ namespace StreamFormat::FMT { if (!executor.Data.PrefixSuffix) { - if (Detail::BufferTestManip(executor.BufferIn).IsEqualTo('t', 'T')) + if (Detail::BufferTestAccess(executor.BufferIn).IsEqualTo('t', 'T')) { SF_TRY(Detail::BufferManip(executor.BufferIn).Forward()); - if (Detail::BufferTestManip(executor.BufferIn).IsSame("rue")) + if (Detail::BufferTestAccess(executor.BufferIn).IsSame("rue")) { SF_TRY(Detail::BufferManip(executor.BufferIn).Forward()); t = true; } } - else if (Detail::BufferTestManip(executor.BufferIn).IsEqualToForward('f', 'F')) + else if (Detail::BufferTestAccess(executor.BufferIn).IsEqualTo('f', 'F')) { SF_TRY(Detail::BufferManip(executor.BufferIn).Forward()); - if (Detail::BufferTestManip(executor.BufferIn).IsSameForward("alse")) + if (Detail::BufferTestAccess(executor.BufferIn).IsSame("alse")) { SF_TRY(Detail::BufferManip(executor.BufferIn).Forward()); t = false; @@ -41,12 +41,12 @@ namespace StreamFormat::FMT } else { - if (Detail::BufferTestManip(executor.BufferIn).IsEqualTo('1')) + if (Detail::BufferTestAccess(executor.BufferIn).IsEqualTo('1')) { SF_TRY(Detail::BufferManip(executor.BufferIn).Forward()); t = true; } - else if (Detail::BufferTestManip(executor.BufferIn).IsEqualTo('0')) + else if (Detail::BufferTestAccess(executor.BufferIn).IsEqualTo('0')) { SF_TRY(Detail::BufferManip(executor.BufferIn).Forward()); t = false; diff --git a/src/StreamFormat/FMT/Detail/FMTResult.h b/src/StreamFormat/FMT/Detail/FMTResult.h index c8504344..d6b2215f 100644 --- a/src/StreamFormat/FMT/Detail/FMTResult.h +++ b/src/StreamFormat/FMT/Detail/FMTResult.h @@ -10,6 +10,7 @@ namespace StreamFormat::FMT Buffer_OutOfBoundAccess, Buffer_UnableToReserveMemory, Parse_NonValidDigit, + Parse_TokenNotExpected, ArgsInterface_Unavaible, ArgsInterface_InvalidTypeID, diff --git a/src/StreamFormat/Json/JsonParser.cpp b/src/StreamFormat/Json/JsonParser.cpp index 4566ff71..6b08bdb0 100644 --- a/src/StreamFormat/Json/JsonParser.cpp +++ b/src/StreamFormat/Json/JsonParser.cpp @@ -13,7 +13,7 @@ namespace StreamFormat::JSON::Detail FMT::Detail::BufferTestAccess access(parser.BufferIn); FMT::Detail::BufferTestManip manip(parser.BufferIn); - manip.SkipAllBlanks(); + manip.IgnoreEveryBlanks(); const char* begin = parser.BufferIn.CurrentPos; if (parser.IsJsonStringBegin()) diff --git a/src/StreamFormat/Json/JsonSerializer.h b/src/StreamFormat/Json/JsonSerializer.h index 4d607c8e..d30c465d 100644 --- a/src/StreamFormat/Json/JsonSerializer.h +++ b/src/StreamFormat/Json/JsonSerializer.h @@ -182,9 +182,9 @@ namespace StreamFormat::JSON std::string name; JsonStringSerializer::ParseSTDString(name, parser); - manip.SkipAllBlanks(); + manip.IgnoreEveryBlanks(); manip.SkipOneOf(':').value(); - manip.SkipAllBlanks(); + manip.IgnoreEveryBlanks(); subObjectParsingFunction(t, idx++, std::move(name), parser); @@ -241,7 +241,7 @@ namespace StreamFormat::JSON while (FMT::Detail::BufferAccess(parser.BufferIn).IsEndOfString() == false) { - manip.SkipAllBlanks(); + manip.IgnoreEveryBlanks(); if (access.IsEqualTo(']')) break; diff --git a/src/StreamFormat/Json/Serializers/JsonObjectsSerializer.h b/src/StreamFormat/Json/Serializers/JsonObjectsSerializer.h index 247b465c..bff42cea 100644 --- a/src/StreamFormat/Json/Serializers/JsonObjectsSerializer.h +++ b/src/StreamFormat/Json/Serializers/JsonObjectsSerializer.h @@ -15,7 +15,7 @@ namespace StreamFormat::JSON { static inline void Parse(std::unique_ptr& t, Detail::JsonParser& parser) { - FMT::Detail::BufferTestManip(parser.BufferIn).SkipAllBlanks(); + FMT::Detail::BufferTestManip(parser.BufferIn).IgnoreEveryBlanks(); if (parser.IsJsonStringBegin()) t = std::make_unique(); else if (parser.IsJsonNumberBegin()) From fb4690b2a713a25c9ca288c904c6cf812a29bd39 Mon Sep 17 00:00:00 2001 From: BELLIER Sacha Date: Sun, 1 Dec 2024 14:38:10 +0100 Subject: [PATCH 08/42] feat: finally, issues fixed ! --- Examples/HelloWorld/main.cpp | 2 - Tests/FMT/BaseFMTTests.h | 2 +- Tests/FMT/ComplexPattern.cpp | 6 +- Tests/FMT/Globber.cpp | 58 ++++----- Tests/FMT/Index.cpp | 4 +- Tests/FMT/Limits.cpp | 118 ++++++++++-------- Tests/FMT/Shift.cpp | 68 +++++----- Tests/FMT/Specifier.cpp | 6 +- Tests/FMT/TextProperties.cpp | 18 +-- src/StreamFormat/Core/Prelude.h | 4 +- src/StreamFormat/FMT/Buffer/BufferTestManip.h | 2 +- .../FMT/Buffer/FMTBufferWriteManip.h | 8 +- .../FMT/Context/BasicContext/BasicContext.h | 3 +- .../BasicContext/BasicContextParse-impl.h | 17 ++- .../BasicFormatterExecutor.h | 11 +- .../FormatterExecutor/FormatBasics-impl.h | 4 +- .../FormatterExecutor/UtilityFunctions.h | 56 +++++++++ .../Context/ParserExecutor/UtilityFunctions.h | 2 +- src/StreamFormat/FMT/Detail/FMTResult.h | 15 +++ .../ProfilerManager/ProfilerMacro.h | 12 +- src/StreamFormat/Tester/TestSuite/BasicTest.h | 75 ++++++++--- src/StreamFormat/Tester/TestSuite/TestSuite.h | 8 +- 22 files changed, 320 insertions(+), 179 deletions(-) diff --git a/Examples/HelloWorld/main.cpp b/Examples/HelloWorld/main.cpp index ea81f1b4..cca27e5e 100644 --- a/Examples/HelloWorld/main.cpp +++ b/Examples/HelloWorld/main.cpp @@ -6,8 +6,6 @@ int main() { - StreamFormat::FMT::FilePrint(std::cout, "HelloWorld {} !", "ahhh"); - StreamFormat::FLog::DefaultLogger::Core().Info("HelloWorld !"); using namespace std::chrono_literals; diff --git a/Tests/FMT/BaseFMTTests.h b/Tests/FMT/BaseFMTTests.h index bf3eb36f..daed614f 100644 --- a/Tests/FMT/BaseFMTTests.h +++ b/Tests/FMT/BaseFMTTests.h @@ -2,4 +2,4 @@ #include "StreamFormat/Tester/TestSuite/AllTestSuite.h" -inline PCT_TEST_SUITE(FMT); +inline SFT_TEST_SUITE(FMT); diff --git a/Tests/FMT/ComplexPattern.cpp b/Tests/FMT/ComplexPattern.cpp index 6a1078c0..84ccfca8 100644 --- a/Tests/FMT/ComplexPattern.cpp +++ b/Tests/FMT/ComplexPattern.cpp @@ -3,11 +3,11 @@ #include "BaseFMTTests.h" -PCT_TEST_GROUP(FMT, COMPLEX_PATTERN); +SFT_TEST_GROUP(FMT, COMPLEX_PATTERN); -#define TEST_FMT(fmt_test, expected, ...) PCT_EQ(StreamFormat::FMT::FormatString(fmt_test, __VA_ARGS__), std::string(expected)) +#define TEST_FMT(fmt_test, expected, ...) SFT_EQ(StreamFormat::FMT::FormatString(fmt_test, __VA_ARGS__).value(), std::string(expected)) -PCT_TEST_FUNC(COMPLEX_PATTERN, UNESCAPED_ESCAPE_PATTERN) +SFT_TEST_FUNC(COMPLEX_PATTERN, UNESCAPED_ESCAPE_PATTERN) { TEST_FMT("{0}", "9", 9); TEST_FMT("{{0}|", "{9|", 9); diff --git a/Tests/FMT/Globber.cpp b/Tests/FMT/Globber.cpp index 824cd53f..ab277ecd 100644 --- a/Tests/FMT/Globber.cpp +++ b/Tests/FMT/Globber.cpp @@ -4,69 +4,69 @@ #include "StreamFormat/FMT/Buffer/Utils/BufferGlobberManip.h" -PCT_TEST_GROUP(FMT, GLOBBER); +SFT_TEST_GROUP(FMT, GLOBBER); #define TEST_GLOBBER(data, glob) \ { \ StreamFormat::FMT::Detail::BufferInfoView p_buffer(data); \ StreamFormat::FMT::Detail::BufferInfoView p_glob(glob); \ StreamFormat::FMT::Detail::Globber::BufferInExecGlob(p_buffer, \ p_glob).value(); \ - PCT_ASSERT( \ + SFT_ASSERT( \ StreamFormat::FMT::Detail::BufferAccess(p_buffer).IsEndOfString()); \ } -PCT_TEST_FUNC(GLOBBER, BASIC_WILDCARD){ +SFT_TEST_FUNC(GLOBBER, BASIC_WILDCARD){ TEST_GLOBBER("qwerty", "qwerty") TEST_GLOBBER("qwerty", "q?erty") TEST_GLOBBER("qwerty", "q?????") TEST_GLOBBER("qwerty", "qwer?y") TEST_GLOBBER("qwerty", "qwert?") TEST_GLOBBER("qwerty", "??????") TEST_GLOBBER("qwerty", "*") TEST_GLOBBER("qwerty", "******") TEST_GLOBBER("qwerty", "*?**?*")} -PCT_TEST_GROUP(FMT, PARSE_GLOBBER); -PCT_TEST_FUNC(PARSE_GLOBBER, PG_BASIC_WILDCARD) { +SFT_TEST_GROUP(FMT, PARSE_GLOBBER); +SFT_TEST_FUNC(PARSE_GLOBBER, PG_BASIC_WILDCARD) { int k = 0; StreamFormat::FMT::Parse("|123|", "|{}|", k).value(); - PCT_EQ(k, 123); + SFT_EQ(k, 123); { - char test[5]; - StreamFormat::FMT::Parse("|test|", "|{}|", test).value(); - // PCT_EQ(std::string(test), std::string("test")); + // char test[5]; + // StreamFormat::FMT::Parse("|test|", "|{}|", test).value(); + // SFT_EQ(std::string(test), std::string("test")); } { - char test[4]; - StreamFormat::FMT::Parse("|test|", "|{:no-zero-end}|", test).value(); - // PCT_EQ(std::string(test, 4), std::string("test")); + // char test[4]; + // StreamFormat::FMT::Parse("|test|", "|{:no-zero-end}|", test).value(); + // SFT_EQ(std::string(test, 4), std::string("test")); } { - char test[4]; - StreamFormat::FMT::Parse("|test|", "|{}t|", test).value(); - // PCT_EQ(std::string(test), std::string("tes")); + // char test[4]; + // StreamFormat::FMT::Parse("|test|", "|{}t|", test).value(); + // SFT_EQ(std::string(test), std::string("tes")); } { - char test[11]; - StreamFormat::FMT::Parse("|test123456|", "|{}|", test).value(); - // PCT_EQ(std::string(test), std::string("test123456")); + // char test[11]; + // StreamFormat::FMT::Parse("|test123456|", "|{}|", test).value(); + // SFT_EQ(std::string(test), std::string("test123456")); } { - char test[11]; - StreamFormat::FMT::Parse("|test123456|", "|{:glob='*1'}23456|", test).value(); - // PCT_EQ(std::string(test), std::string("test1")); + // char test[11]; + // StreamFormat::FMT::Parse("|test123456|", "|{:glob='*1'}23456|", test).value(); + // SFT_EQ(std::string(test), std::string("test1")); } { - char test[11]; + // char test[11]; // just glob = '????' but compiler are anrgy about trigraph on '??' - StreamFormat::FMT::Parse("|test123456|", - "|{:glob='?" - "?" - "?" - "?'}123456|", - test).value(); - // PCT_EQ(std::string(test), std::string("test")); + // StreamFormat::FMT::Parse("|test123456|", + // "|{:glob='?" + // "?" + // "?" + // "?'}123456|", + // test).value(); + // SFT_EQ(std::string(test), std::string("test")); } } diff --git a/Tests/FMT/Index.cpp b/Tests/FMT/Index.cpp index e0a4e6bc..703df7fd 100644 --- a/Tests/FMT/Index.cpp +++ b/Tests/FMT/Index.cpp @@ -4,9 +4,9 @@ #include "BaseFMTTests.h" /* -PCT_TEST_GROUP(FMT, INDEX); +SFT_TEST_GROUP(FMT, INDEX); -PCT_TEST_FUNC(INDEX, ReIndexing) +SFT_TEST_FUNC(INDEX, ReIndexing) { } */ diff --git a/Tests/FMT/Limits.cpp b/Tests/FMT/Limits.cpp index 3af6e564..eaf1643c 100644 --- a/Tests/FMT/Limits.cpp +++ b/Tests/FMT/Limits.cpp @@ -3,102 +3,110 @@ #include "BaseFMTTests.h" -PCT_TEST_GROUP(FMT, LIMITS); +SFT_TEST_GROUP(FMT, LIMITS); -#define PCT_TEST_FUNC_LowBufferSize(k) \ - PCT_TEST_FUNC(LIMITS, LowBufferSize##k) { \ - char buffer[k] = {0}; \ - StreamFormat::FMT::FormatInChar(buffer, "0123456789").value(); \ - for (int i = 0; i < k; ++i) \ - PCT_EQ(buffer[i] - '0', i); \ +#define SFT_TEST_FUNC_LowBufferSize(k) \ + SFT_TEST_FUNC(LIMITS, LowBufferSize##k) { \ + char buffer[k] = {0}; \ + auto res = StreamFormat::FMT::FormatInChar(buffer, "0123456789"); \ + SFT_EXPECTED_VALUE(res); \ + for (int i = 0; i < k; ++i) \ + SFT_EQ(buffer[i] - '0', i); \ } -PCT_TEST_FUNC_LowBufferSize(10); -PCT_TEST_FUNC_LowBufferSize(9); -PCT_TEST_FUNC_LowBufferSize(8); -PCT_TEST_FUNC_LowBufferSize(7); -PCT_TEST_FUNC_LowBufferSize(6); -PCT_TEST_FUNC_LowBufferSize(5); -PCT_TEST_FUNC_LowBufferSize(4); -PCT_TEST_FUNC_LowBufferSize(3); -PCT_TEST_FUNC_LowBufferSize(2); -PCT_TEST_FUNC_LowBufferSize(1); +SFT_TEST_FUNC_LowBufferSize(10); +SFT_TEST_FUNC_LowBufferSize(9); +SFT_TEST_FUNC_LowBufferSize(8); +SFT_TEST_FUNC_LowBufferSize(7); +SFT_TEST_FUNC_LowBufferSize(6); +SFT_TEST_FUNC_LowBufferSize(5); +SFT_TEST_FUNC_LowBufferSize(4); +SFT_TEST_FUNC_LowBufferSize(3); +SFT_TEST_FUNC_LowBufferSize(2); +SFT_TEST_FUNC_LowBufferSize(1); -PCT_TEST_FUNC(LIMITS, PlainLowBufferSize10) { +SFT_TEST_FUNC(LIMITS, PlainLowBufferSize10) { char buffer[10] = {0}; - StreamFormat::FMT::FormatInChar(buffer, "0123456789").value(); + auto res = StreamFormat::FMT::FormatInChar(buffer, "0123456789"); + SFT_EXPECTED_VALUE(res); for (int i = 0; i < 10; ++i) - PCT_EQ(buffer[i] - '0', i); + SFT_EQ(buffer[i] - '0', i); } -PCT_TEST_FUNC(LIMITS, PlainLowBufferSize1) { +SFT_TEST_FUNC(LIMITS, PlainLowBufferSize1) { char buffer[1] = {0}; - StreamFormat::FMT::FormatInChar(buffer, "0").value(); + auto res = StreamFormat::FMT::FormatInChar(buffer, "0"); + SFT_EXPECTED_VALUE(res); for (int i = 0; i < 1; ++i) - PCT_EQ(buffer[i] - '0', i); + SFT_EQ(buffer[i] - '0', i); } -#define PCT_TEST_FUNC_LowBufferSizeArray(k) \ - PCT_TEST_FUNC(LIMITS, LowBufferSizeArray##k) { \ - char buffer[k] = {0}; \ - const char fmtBuffer[] = { \ - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; \ - StreamFormat::FMT::Detail::BufferInfoView format(fmtBuffer, k); \ - StreamFormat::FMT::Detail::GivenBufferOutManager manager(buffer, k); \ - StreamFormat::FMT::Detail::FormatInManager(manager, false, format).value(); \ - for (int i = 0; i < k; ++i) \ - PCT_EQ(buffer[i] - '0', i); \ +#define SFT_TEST_FUNC_LowBufferSizeArray(k) \ + SFT_TEST_FUNC(LIMITS, LowBufferSizeArray##k) { \ + char buffer[k] = {0}; \ + const char fmtBuffer[] = { \ + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; \ + StreamFormat::FMT::Detail::BufferInfoView format(fmtBuffer, k); \ + StreamFormat::FMT::Detail::GivenBufferOutManager manager(buffer, k); \ + auto res = StreamFormat::FMT::Detail::FormatInManager(manager, false, format); \ + SFT_EXPECTED_VALUE(res); \ + for (int i = 0; i < k; ++i) \ + SFT_EQ(buffer[i] - '0', i); \ } -PCT_TEST_FUNC_LowBufferSizeArray(10); -PCT_TEST_FUNC_LowBufferSizeArray(9); -PCT_TEST_FUNC_LowBufferSizeArray(8); -PCT_TEST_FUNC_LowBufferSizeArray(7); -PCT_TEST_FUNC_LowBufferSizeArray(6); -PCT_TEST_FUNC_LowBufferSizeArray(5); -PCT_TEST_FUNC_LowBufferSizeArray(4); -PCT_TEST_FUNC_LowBufferSizeArray(3); -PCT_TEST_FUNC_LowBufferSizeArray(2); -PCT_TEST_FUNC_LowBufferSizeArray(1); +SFT_TEST_FUNC_LowBufferSizeArray(10); +SFT_TEST_FUNC_LowBufferSizeArray(9); +SFT_TEST_FUNC_LowBufferSizeArray(8); +SFT_TEST_FUNC_LowBufferSizeArray(7); +SFT_TEST_FUNC_LowBufferSizeArray(6); +SFT_TEST_FUNC_LowBufferSizeArray(5); +SFT_TEST_FUNC_LowBufferSizeArray(4); +SFT_TEST_FUNC_LowBufferSizeArray(3); +SFT_TEST_FUNC_LowBufferSizeArray(2); +SFT_TEST_FUNC_LowBufferSizeArray(1); -PCT_TEST_FUNC(LIMITS, PlainLowBufferSizeArray10) { +SFT_TEST_FUNC(LIMITS, PlainLowBufferSizeArray10) { char buffer[10] = {0}; const char fmtBuffer[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; StreamFormat::FMT::Detail::BufferInfoView fmt(fmtBuffer, 10); StreamFormat::FMT::Detail::GivenBufferOutManager manager(buffer, 10); - StreamFormat::FMT::Detail::FormatInManager(manager, false, fmt).value(); + auto res = StreamFormat::FMT::Detail::FormatInManager(manager, false, fmt); + SFT_EXPECTED_VALUE(res); for (int i = 0; i < 10; ++i) - PCT_EQ(buffer[i] - '0', i); + SFT_EQ(buffer[i] - '0', i); } -PCT_TEST_FUNC(LIMITS, PlainLowBufferSizeArray1) { +SFT_TEST_FUNC(LIMITS, PlainLowBufferSizeArray1) { char buffer[1] = {0}; const char fmtBuffer[] = {'0'}; StreamFormat::FMT::Detail::BufferInfoView fmt(fmtBuffer, 1); StreamFormat::FMT::Detail::GivenBufferOutManager manager(buffer, 1); - StreamFormat::FMT::Detail::FormatInManager(manager, false, fmt).value(); + auto res = StreamFormat::FMT::Detail::FormatInManager(manager, false, fmt); + SFT_EXPECTED_VALUE(res); for (int i = 0; i < 1; ++i) - PCT_EQ(buffer[i] - '0', i); + SFT_EQ(buffer[i] - '0', i); } -PCT_TEST_FUNC(LIMITS, LowBufferSizeArray10FMT30) { +SFT_TEST_FUNC(LIMITS, LowBufferSizeArray10FMT30) { char buffer[10] = {0}; const char fmtBuffer[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; StreamFormat::FMT::Detail::BufferInfoView fmt(fmtBuffer, 30); StreamFormat::FMT::Detail::GivenBufferOutManager manager(buffer, 10); - StreamFormat::FMT::Detail::FormatInManager(manager, false, fmt).value(); + auto res = StreamFormat::FMT::Detail::FormatInManager(manager, false, fmt); + SFT_EXPECTED_VALUE(res); for (int k = 0; k < 10; ++k) - PCT_EQ(buffer[k] - '0', k); + SFT_EQ(buffer[k] - '0', k); } -PCT_TEST_FUNC(LIMITS, LowBufferSizeArray5Number9) { +SFT_TEST_FUNC(LIMITS, LowBufferSizeArray5Number9) { char buffer[10] = {0}; StreamFormat::FMT::Detail::BufferInfoView fmt("{}"); StreamFormat::FMT::Detail::GivenBufferOutManager manager(buffer, 10); std::uint64_t i = 9'876'543'210; - StreamFormat::FMT::Detail::FormatInManager(manager, false, fmt, i).value(); + auto res = StreamFormat::FMT::Detail::FormatInManager(manager, false, fmt, i); + SFT_EXPECTED_VALUE(res); for (int k = 0; k < 10; ++k) - PCT_EQ(buffer[k] - '0', 9 - k); + SFT_EQ(buffer[k] - '0', 9 - k); } diff --git a/Tests/FMT/Shift.cpp b/Tests/FMT/Shift.cpp index 8193347a..d30079f3 100644 --- a/Tests/FMT/Shift.cpp +++ b/Tests/FMT/Shift.cpp @@ -3,27 +3,27 @@ #include "BaseFMTTests.h" -PCT_TEST_GROUP(FMT, SHIFT); +SFT_TEST_GROUP(FMT, SHIFT); -#define TEST_FMT(fmt_test, expected, ...) PCT_EQ(StreamFormat::FMT::FormatString(fmt_test, __VA_ARGS__), expected) +#define TEST_FMT(fmt_test, expected, ...) SFT_EQ(StreamFormat::FMT::FormatString(fmt_test, __VA_ARGS__), expected) -PCT_TEST_GROUP(SHIFT, NUMBER_SHIFT); -PCT_TEST_GROUP(NUMBER_SHIFT, ONE_DIGIT); -PCT_TEST_FUNC(ONE_DIGIT, Right) +SFT_TEST_GROUP(SHIFT, NUMBER_SHIFT); +SFT_TEST_GROUP(NUMBER_SHIFT, ONE_DIGIT); +SFT_TEST_FUNC(ONE_DIGIT, Right) { TEST_FMT("|{:>9 }|", "| 7|", 7); TEST_FMT("|{:>9: }|", "| 7|", 7); TEST_FMT("|{:>9:0}|", "|000000007|", 7); TEST_FMT("|{:>9:*}|", "|********7|", 7); } -PCT_TEST_FUNC(ONE_DIGIT, Left) +SFT_TEST_FUNC(ONE_DIGIT, Left) { TEST_FMT("|{:<9 }|", "|7 |", 7); TEST_FMT("|{:<9: }|", "|7 |", 7); TEST_FMT("|{:<9:0}|", "|7 |", 7); TEST_FMT("|{:<9:*}|", "|7********|", 7); } -PCT_TEST_FUNC(ONE_DIGIT, Center) +SFT_TEST_FUNC(ONE_DIGIT, Center) { TEST_FMT("|{:^10 }|", "| 7 |", 7); TEST_FMT("|{:^10:-|-}|", "|-----7----|", 7); @@ -36,7 +36,7 @@ PCT_TEST_FUNC(ONE_DIGIT, Center) TEST_FMT("|{:^11:<|>}|", "|<<<<<7>>>>>|", 7); TEST_FMT("|{:^11:>|<}|", "|>>>>>7<<<<<|", 7); } -PCT_TEST_FUNC(ONE_DIGIT, CenterRight) +SFT_TEST_FUNC(ONE_DIGIT, CenterRight) { TEST_FMT("|{:^>10:-|-}|", "|-----7----|", 7); TEST_FMT("|{:^>10:*|*}|", "|*****7****|", 7); @@ -48,7 +48,7 @@ PCT_TEST_FUNC(ONE_DIGIT, CenterRight) TEST_FMT("|{:^>11:<|>}|", "|<<<<<7>>>>>|", 7); TEST_FMT("|{:^>11:>|<}|", "|>>>>>7<<<<<|", 7); } -PCT_TEST_FUNC(ONE_DIGIT, CenterLeft) +SFT_TEST_FUNC(ONE_DIGIT, CenterLeft) { TEST_FMT("|{:^<10:-|-}|", "|----7-----|", 7); TEST_FMT("|{:^<10:*|*}|", "|****7*****|", 7); @@ -61,22 +61,22 @@ PCT_TEST_FUNC(ONE_DIGIT, CenterLeft) TEST_FMT("|{:^<11:>|<}|", "|>>>>>7<<<<<|", 7); } -PCT_TEST_GROUP(NUMBER_SHIFT, TWO_DIGIT); -PCT_TEST_FUNC(TWO_DIGIT, Right) +SFT_TEST_GROUP(NUMBER_SHIFT, TWO_DIGIT); +SFT_TEST_FUNC(TWO_DIGIT, Right) { TEST_FMT("|{:>10 }|", "| 14|", 14); TEST_FMT("|{:>10: }|", "| 14|", 14); TEST_FMT("|{:>10:0}|", "|0000000014|", 14); TEST_FMT("|{:>10:*}|", "|********14|", 14); } -PCT_TEST_FUNC(TWO_DIGIT, Left) +SFT_TEST_FUNC(TWO_DIGIT, Left) { TEST_FMT("|{:<10 }|", "|14 |", 14); TEST_FMT("|{:<10: }|", "|14 |", 14); TEST_FMT("|{:<10:0}|", "|14 |", 14); TEST_FMT("|{:<10:*}|", "|14********|", 14); } -PCT_TEST_FUNC(TWO_DIGIT, Center) +SFT_TEST_FUNC(TWO_DIGIT, Center) { TEST_FMT("|{:^10 }|", "| 14 |", 14); TEST_FMT("|{:^10:-|-}|", "|----14----|", 14); @@ -89,7 +89,7 @@ PCT_TEST_FUNC(TWO_DIGIT, Center) TEST_FMT("|{:^11:<|>}|", "|<<<<<14>>>>|", 14); TEST_FMT("|{:^11:>|<}|", "|>>>>>14<<<<|", 14); } -PCT_TEST_FUNC(TWO_DIGIT, CenterRight) +SFT_TEST_FUNC(TWO_DIGIT, CenterRight) { TEST_FMT("|{:^>10:-|-}|", "|----14----|", 14); TEST_FMT("|{:^>10:*|*}|", "|****14****|", 14); @@ -101,7 +101,7 @@ PCT_TEST_FUNC(TWO_DIGIT, CenterRight) TEST_FMT("|{:^>11:<|>}|", "|<<<<<14>>>>|", 14); TEST_FMT("|{:^>11:>|<}|", "|>>>>>14<<<<|", 14); } -PCT_TEST_FUNC(TWO_DIGIT, CenterLeft) +SFT_TEST_FUNC(TWO_DIGIT, CenterLeft) { TEST_FMT("|{:^<10:-|-}|", "|----14----|", 14); TEST_FMT("|{:^<10:*|*}|", "|****14****|", 14); @@ -114,22 +114,22 @@ PCT_TEST_FUNC(TWO_DIGIT, CenterLeft) TEST_FMT("|{:^<11:>|<}|", "|>>>>14<<<<<|", 14); } -PCT_TEST_GROUP(NUMBER_SHIFT, THREE_DIGIT); -PCT_TEST_FUNC(THREE_DIGIT, Right) +SFT_TEST_GROUP(NUMBER_SHIFT, THREE_DIGIT); +SFT_TEST_FUNC(THREE_DIGIT, Right) { TEST_FMT("|{:>11 }|", "| 105|", 105); TEST_FMT("|{:>11: }|", "| 105|", 105); TEST_FMT("|{:>11:0}|", "|00000000105|", 105); TEST_FMT("|{:>11:*}|", "|********105|", 105); } -PCT_TEST_FUNC(THREE_DIGIT, Left) +SFT_TEST_FUNC(THREE_DIGIT, Left) { TEST_FMT("|{:<11 }|", "|105 |", 105); TEST_FMT("|{:<11: }|", "|105 |", 105); TEST_FMT("|{:<11:0}|", "|105 |", 105); TEST_FMT("|{:<11:*}|", "|105********|", 105); } -PCT_TEST_FUNC(THREE_DIGIT, Center) +SFT_TEST_FUNC(THREE_DIGIT, Center) { TEST_FMT("|{:^10 }|", "| 105 |", 105); TEST_FMT("|{:^10:-|-}|", "|----105---|", 105); @@ -142,7 +142,7 @@ PCT_TEST_FUNC(THREE_DIGIT, Center) TEST_FMT("|{:^11:<|>}|", "|<<<<105>>>>|", 105); TEST_FMT("|{:^11:>|<}|", "|>>>>105<<<<|", 105); } -PCT_TEST_FUNC(THREE_DIGIT, CenterRight) +SFT_TEST_FUNC(THREE_DIGIT, CenterRight) { TEST_FMT("|{:^>10:-|-}|", "|----105---|", 105); TEST_FMT("|{:^>10:*|*}|", "|****105***|", 105); @@ -154,7 +154,7 @@ PCT_TEST_FUNC(THREE_DIGIT, CenterRight) TEST_FMT("|{:^>11:<|>}|", "|<<<<105>>>>|", 105); TEST_FMT("|{:^>11:>|<}|", "|>>>>105<<<<|", 105); } -PCT_TEST_FUNC(THREE_DIGIT, CenterLeft) +SFT_TEST_FUNC(THREE_DIGIT, CenterLeft) { TEST_FMT("|{:^<10:-|-}|", "|---105----|", 105); TEST_FMT("|{:^<10:*|*}|", "|***105****|", 105); @@ -167,23 +167,23 @@ PCT_TEST_FUNC(THREE_DIGIT, CenterLeft) TEST_FMT("|{:^<11:>|<}|", "|>>>>105<<<<|", 105); } -PCT_TEST_GROUP(SHIFT, STRING_SHIFT); -PCT_TEST_GROUP(STRING_SHIFT, ARRAY); -PCT_TEST_FUNC(ARRAY, Right) +SFT_TEST_GROUP(SHIFT, STRING_SHIFT); +SFT_TEST_GROUP(STRING_SHIFT, ARRAY); +SFT_TEST_FUNC(ARRAY, Right) { TEST_FMT("|{:>10 }|", "| test|", "test"); TEST_FMT("|{:>10: }|", "| test|", "test"); TEST_FMT("|{:>10:0}|", "|000000test|", "test"); TEST_FMT("|{:>10:*}|", "|******test|", "test"); } -PCT_TEST_FUNC(ARRAY, Left) +SFT_TEST_FUNC(ARRAY, Left) { TEST_FMT("|{:<10 }|", "|test |", "test"); TEST_FMT("|{:<10: }|", "|test |", "test"); TEST_FMT("|{:<10:0}|", "|test000000|", "test"); TEST_FMT("|{:<10:*}|", "|test******|", "test"); } -PCT_TEST_FUNC(ARRAY, Center) +SFT_TEST_FUNC(ARRAY, Center) { TEST_FMT("|{:^10 }|", "| test |", "test"); TEST_FMT("|{:^10:-|-}|", "|---test---|", "test"); @@ -196,7 +196,7 @@ PCT_TEST_FUNC(ARRAY, Center) TEST_FMT("|{:^11:<|>}|", "|<<<>>|", "test"); TEST_FMT("|{:^11:>|<}|", "|>>>>test<<<|", "test"); } -PCT_TEST_FUNC(ARRAY, CenterRight) +SFT_TEST_FUNC(ARRAY, CenterRight) { TEST_FMT("|{:^>10:-|-}|", "|---test---|", "test"); TEST_FMT("|{:^>10:*|*}|", "|***test***|", "test"); @@ -208,7 +208,7 @@ PCT_TEST_FUNC(ARRAY, CenterRight) TEST_FMT("|{:^>11:<|>}|", "|<<<>>|", "test"); TEST_FMT("|{:^>11:>|<}|", "|>>>>test<<<|", "test"); } -PCT_TEST_FUNC(ARRAY, CenterLeft) +SFT_TEST_FUNC(ARRAY, CenterLeft) { TEST_FMT("|{:^<10:-|-}|", "|---test---|", "test"); TEST_FMT("|{:^<10:*|*}|", "|***test***|", "test"); @@ -221,8 +221,8 @@ PCT_TEST_FUNC(ARRAY, CenterLeft) TEST_FMT("|{:^<11:>|<}|", "|>>>test<<<<|", "test"); } -PCT_TEST_GROUP(STRING_SHIFT, POINTER); -PCT_TEST_FUNC(POINTER, Right) +SFT_TEST_GROUP(STRING_SHIFT, POINTER); +SFT_TEST_FUNC(POINTER, Right) { const char* test = "test"; TEST_FMT("|{:>10 }|", "| test|", test); @@ -236,7 +236,7 @@ PCT_TEST_FUNC(POINTER, Right) TEST_FMT("|{:>10:0, size=4}|", "|000000test|", test_with_size); TEST_FMT("|{:>10:*, size=4}|", "|******test|", test_with_size); } -PCT_TEST_FUNC(POINTER, Left) +SFT_TEST_FUNC(POINTER, Left) { const char* test = "test"; TEST_FMT("|{:<10 }|", "|test |", test); @@ -250,7 +250,7 @@ PCT_TEST_FUNC(POINTER, Left) TEST_FMT("|{:<10:0, size=4}|", "|test000000|", test_with_size); TEST_FMT("|{:<10:*, size=4}|", "|test******|", test_with_size); } -PCT_TEST_FUNC(POINTER, Center) +SFT_TEST_FUNC(POINTER, Center) { const char* test = "test"; TEST_FMT("|{:^10 }|", "| test |", test); @@ -276,7 +276,7 @@ PCT_TEST_FUNC(POINTER, Center) TEST_FMT("|{:^11:<|>, size=4}|", "|<<<>>|", test_with_size); TEST_FMT("|{:^11:>|<, size=4}|", "|>>>>test<<<|", test_with_size); } -PCT_TEST_FUNC(POINTER, CenterRight) +SFT_TEST_FUNC(POINTER, CenterRight) { const char* test = "test"; TEST_FMT("|{:^>10:-|-}|", "|---test---|", test); @@ -300,7 +300,7 @@ PCT_TEST_FUNC(POINTER, CenterRight) TEST_FMT("|{:^>11:<|>, size=4}|", "|<<<>>|", test_with_size); TEST_FMT("|{:^>11:>|<, size=4}|", "|>>>>test<<<|", test_with_size); } -PCT_TEST_FUNC(POINTER, CenterLeft) +SFT_TEST_FUNC(POINTER, CenterLeft) { const char* test = "test"; TEST_FMT("|{:^<10:-|-}|", "|---test---|", test); diff --git a/Tests/FMT/Specifier.cpp b/Tests/FMT/Specifier.cpp index 43f76032..2dfb5b39 100644 --- a/Tests/FMT/Specifier.cpp +++ b/Tests/FMT/Specifier.cpp @@ -3,11 +3,11 @@ #include "BaseFMTTests.h" -PCT_TEST_GROUP(FMT, SPECIFIER); +SFT_TEST_GROUP(FMT, SPECIFIER); -#define TEST_FMT_ARRAY_SPECIFIERS(fmt_test, test_data, expected) PCT_EQ(StreamFormat::FMT::FormatString(fmt_test, test_data), expected) +#define TEST_FMT_ARRAY_SPECIFIERS(fmt_test, test_data, expected) SFT_EQ(StreamFormat::FMT::FormatString(fmt_test, test_data), expected) -PCT_TEST_FUNC(SPECIFIER, BEGIN_END) +SFT_TEST_FUNC(SPECIFIER, BEGIN_END) { int data[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; TEST_FMT_ARRAY_SPECIFIERS("{}", data, "{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }"); diff --git a/Tests/FMT/TextProperties.cpp b/Tests/FMT/TextProperties.cpp index 954e347d..0a881b43 100644 --- a/Tests/FMT/TextProperties.cpp +++ b/Tests/FMT/TextProperties.cpp @@ -3,9 +3,9 @@ #include "BaseFMTTests.h" -PCT_TEST_GROUP(FMT, TEXT_PROPERTIES); +SFT_TEST_GROUP(FMT, TEXT_PROPERTIES); -#define TEST_FMT(fmt_test, expected) PCT_EQ(Escaper(StreamFormat::FMT::FormatString(fmt_test, 0).value()), Escaper(expected)) +#define TEST_FMT(fmt_test, expected) SFT_EQ(Escaper(StreamFormat::FMT::FormatString(fmt_test, 0).value()), Escaper(expected)) static std::string Escaper(const std::string& str) { @@ -24,15 +24,15 @@ static std::string Escaper(const std::string& str) return res; } -PCT_TEST_GROUP(TEXT_PROPERTIES, ESCAPER_VALIDATING); -#define TEST_ESCAPER(str, str_res) PCT_EQ(Escaper(str), str_res) -PCT_TEST_FUNC(ESCAPER_VALIDATING, BasicTest) +SFT_TEST_GROUP(TEXT_PROPERTIES, ESCAPER_VALIDATING); +#define TEST_ESCAPER(str, str_res) SFT_EQ(Escaper(str), str_res) +SFT_TEST_FUNC(ESCAPER_VALIDATING, BasicTest) { TEST_ESCAPER("\033", "\\e"); TEST_ESCAPER("\033k", "\\ek"); } -PCT_TEST_FUNC(TEXT_PROPERTIES, BasicColor) +SFT_TEST_FUNC(TEXT_PROPERTIES, BasicColor) { TEST_FMT("123", "123"); @@ -55,7 +55,7 @@ PCT_TEST_FUNC(TEXT_PROPERTIES, BasicColor) TEST_FMT("{C:+white} 123 ", "\033[97m 123 \033[39m"); } -PCT_TEST_FUNC(TEXT_PROPERTIES, DoubleBasicColor) +SFT_TEST_FUNC(TEXT_PROPERTIES, DoubleBasicColor) { TEST_FMT("123", "123"); @@ -83,9 +83,9 @@ class TEST_FMT_ContextOut }; STREAMFORMAT_AUTO_FORMATTER_T(TEST_FMT_ContextOut, "{C:red} TEST_FMT_ContextOut {} ", 0); -#define TEST_FMT_CONTEXT(fmt_test, expected) PCT_EQ(Escaper(StreamFormat::FMT::FormatString(fmt_test, TEST_FMT_ContextOut{}).value()), Escaper(expected)) +#define TEST_FMT_CONTEXT(fmt_test, expected) SFT_EQ(Escaper(StreamFormat::FMT::FormatString(fmt_test, TEST_FMT_ContextOut{}).value()), Escaper(expected)) -PCT_TEST_FUNC(TEXT_PROPERTIES, ContextOut) +SFT_TEST_FUNC(TEXT_PROPERTIES, ContextOut) { TEST_FMT_CONTEXT("{}", "\033[31m TEST_FMT_ContextOut 0 \033[39m"); diff --git a/src/StreamFormat/Core/Prelude.h b/src/StreamFormat/Core/Prelude.h index 4a38f055..23f1ac95 100644 --- a/src/StreamFormat/Core/Prelude.h +++ b/src/StreamFormat/Core/Prelude.h @@ -38,7 +38,7 @@ namespace StreamFormat::Detail { template - T&& forward_error(T&& t) + T forward_error(T t) { return std::forward(t); } @@ -47,7 +47,7 @@ namespace StreamFormat::Detail #define SF_TRY(exp) ({ \ auto __expected = exp; \ if (not __expected) [[unlikely]] \ - return StreamFormat::Detail::forward_error(std::unexpected(__expected.error())); \ + return std::unexpected(StreamFormat::Detail::forward_error(__expected.error())); \ __expected.value(); \ }); diff --git a/src/StreamFormat/FMT/Buffer/BufferTestManip.h b/src/StreamFormat/FMT/Buffer/BufferTestManip.h index 35e83d1c..b4bf47b7 100644 --- a/src/StreamFormat/FMT/Buffer/BufferTestManip.h +++ b/src/StreamFormat/FMT/Buffer/BufferTestManip.h @@ -126,7 +126,7 @@ namespace StreamFormat::FMT::Detail if (Access().IsEqualTo(ele...)) { SF_TRY(BufferManip(Buffer).Forward()); - return; + return {}; } return std::unexpected(FMTResult::Parse_TokenNotExpected); } diff --git a/src/StreamFormat/FMT/Buffer/FMTBufferWriteManip.h b/src/StreamFormat/FMT/Buffer/FMTBufferWriteManip.h index 67bfef53..6da095b9 100644 --- a/src/StreamFormat/FMT/Buffer/FMTBufferWriteManip.h +++ b/src/StreamFormat/FMT/Buffer/FMTBufferWriteManip.h @@ -22,9 +22,9 @@ namespace StreamFormat::FMT::Detail template [[nodiscard]] std::expected WriteInteger(T i, Detail::ShiftInfo shift = Detail::ShiftInfo{}) { - char oldBefore = shift.Print.Before; - if (shift.Print.Before >= '0' && shift.Print.Before <= '9') - shift.Print.Before = ' '; + char oldAfter = shift.Print.After; + if (shift.Print.After >= '0' && shift.Print.After <= '9') + shift.Print.After = ' '; std::int32_t nbDigit = BufferWriteUtils::GetNumberOfDigitDec(i); @@ -61,7 +61,7 @@ namespace StreamFormat::FMT::Detail SF_TRY(BufferShiftWriteManip(Buffer).WriteShiftEnd(shift)); - shift.Print.Before = oldBefore; + shift.Print.After = oldAfter; return {}; } diff --git a/src/StreamFormat/FMT/Context/BasicContext/BasicContext.h b/src/StreamFormat/FMT/Context/BasicContext/BasicContext.h index a5cf7c36..04389fac 100644 --- a/src/StreamFormat/FMT/Context/BasicContext/BasicContext.h +++ b/src/StreamFormat/FMT/Context/BasicContext/BasicContext.h @@ -141,7 +141,8 @@ namespace StreamFormat::FMT::Context template void BasicContext::FormatDataApplyNextOverride() { - if (Executor.Data.NextOverride.size() == 0) return; + if (Executor.Data.NextOverride.size() == 0) + { return; } Detail::BufferInfoView overridePos(Executor.Data.NextOverride); Detail::BufferInfoView formatPos = Format; diff --git a/src/StreamFormat/FMT/Context/BasicContext/BasicContextParse-impl.h b/src/StreamFormat/FMT/Context/BasicContext/BasicContextParse-impl.h index 071b09ff..6c7d8a38 100644 --- a/src/StreamFormat/FMT/Context/BasicContext/BasicContextParse-impl.h +++ b/src/StreamFormat/FMT/Context/BasicContext/BasicContextParse-impl.h @@ -95,12 +95,12 @@ namespace StreamFormat::FMT::Context Executor.Data.Shift.Size = SF_TRY(FormatReadParameter(-1)); if (Detail::BufferTestAccess(Format).IsEqualTo(':')) { - Detail::BufferManip(Format).Forward(); + SF_TRY(Detail::BufferManip(Format).Forward()); Executor.Data.Shift.Print.Before = SF_TRY(Detail::BufferManip(Format).GetAndForward()); Executor.Data.Shift.Print.After = Executor.Data.Shift.Print.Before; if (Detail::BufferTestAccess(Format).IsEqualTo('|')) { - Detail::BufferManip(Format).Forward(); + SF_TRY(Detail::BufferManip(Format).Forward()); Executor.Data.Shift.Print.After = SF_TRY(Detail::BufferManip(Format).GetAndForward()); } } @@ -171,7 +171,7 @@ namespace StreamFormat::FMT::Context } else { - SF_TRY(manip.SkipOneOf('>')); + manip.IgnoreOneOf('>'); SF_TRY(ParseFormatDataSpecial_ShiftType(Detail::ShiftInfo::ShiftType::CenterRight)); } } @@ -240,7 +240,7 @@ namespace StreamFormat::FMT::Context { SF_TRY(ParseFormatDataCustom()); } Detail::FMTBufferParamsManip(Format).ParamGoTo(','); - SF_TRY(Detail::BufferTestManip(Format).SkipOneOf(',')); + Detail::BufferTestManip(Format).IgnoreOneOf(','); } return {}; } @@ -322,7 +322,14 @@ namespace StreamFormat::FMT::Context // VI : { which is a idx to an argument if (access.IsEqualTo('{')) { - return SF_FORWARD(GetFormatIndex_SubIndex()); + const TChar* oldPos = Format.CurrentPos; + std::expected res = GetFormatIndex_SubIndex(); + if (res.has_value() == false && res.error() == FMTResult::Context_ArgumentIndexResolution) + { + Format.CurrentPos = oldPos; + return std::unexpected(FMTResult::Context_ArgumentIndexResolution); + } + return SF_FORWARD(res); } return std::unexpected(FMTResult::Context_ArgumentIndexResolution); diff --git a/src/StreamFormat/FMT/Context/FormatterExecutor/BasicFormatterExecutor.h b/src/StreamFormat/FMT/Context/FormatterExecutor/BasicFormatterExecutor.h index eb6010ef..a43f5acc 100644 --- a/src/StreamFormat/FMT/Context/FormatterExecutor/BasicFormatterExecutor.h +++ b/src/StreamFormat/FMT/Context/FormatterExecutor/BasicFormatterExecutor.h @@ -14,6 +14,12 @@ namespace StreamFormat::FMT::Context { + enum class EndOfStringCharMode + { + Forced, + Optional + }; + template class BasicFormatterExecutor : public ContextExecutor { @@ -30,6 +36,7 @@ namespace StreamFormat::FMT::Context public: Detail::FMTBufferOutInfo& BufferOut; + EndOfStringCharMode EndOfStringChar = EndOfStringCharMode::Optional; using ContextExecutor::Data; using ContextExecutor::TextManager; @@ -76,7 +83,9 @@ namespace StreamFormat::FMT::Context Detail::BufferOutManip(BufferOut).ComputeGeneratedSize(); // End char not included in buffer manager context to deduce size correctly - SF_TRY(Detail::BufferOutManip(BufferOut).Pushback('\0')); + auto res = Detail::BufferOutManip(BufferOut).Pushback('\0'); + if (EndOfStringChar == EndOfStringCharMode::Forced) + { SF_TRY(res); } return {}; } diff --git a/src/StreamFormat/FMT/Context/FormatterExecutor/FormatBasics-impl.h b/src/StreamFormat/FMT/Context/FormatterExecutor/FormatBasics-impl.h index 67541508..6183c36d 100644 --- a/src/StreamFormat/FMT/Context/FormatterExecutor/FormatBasics-impl.h +++ b/src/StreamFormat/FMT/Context/FormatterExecutor/FormatBasics-impl.h @@ -114,9 +114,9 @@ namespace StreamFormat::FMT else { if (t == true) - return Detail::BufferManip(executor.BufferOut).Pushback('1'); + return Detail::BufferOutManip(executor.BufferOut).Pushback('1'); else - return Detail::BufferManip(executor.BufferOut).Pushback('0'); + return Detail::BufferOutManip(executor.BufferOut).Pushback('0'); } return {}; diff --git a/src/StreamFormat/FMT/Context/FormatterExecutor/UtilityFunctions.h b/src/StreamFormat/FMT/Context/FormatterExecutor/UtilityFunctions.h index 05bac255..e982843e 100644 --- a/src/StreamFormat/FMT/Context/FormatterExecutor/UtilityFunctions.h +++ b/src/StreamFormat/FMT/Context/FormatterExecutor/UtilityFunctions.h @@ -217,3 +217,59 @@ namespace StreamFormat::FMT return bufferOutManager.GetLastGeneratedString(); } } + +namespace StreamFormat::FMT +{ + template + struct FormatterType + { + [[nodiscard]] static std::expected Format(FMTResult result, FormatterExecutor& executor) + { + switch(result) + { + case FMTResult::FunctionNotImpl: + return Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("FunctionNotImpl"); + case FMTResult::Buffer_NonValid: + return Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("Buffer_NonValid"); + case FMTResult::Buffer_OutOfBoundAccess: + return Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("Buffer_OutOfBoundAccess"); + case FMTResult::Buffer_UnableToReserveMemory: + return Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("Buffer_UnableToReserveMemory"); + case FMTResult::Parse_NonValidDigit: + return Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("Parse_NonValidDigit"); + case FMTResult::Parse_TokenNotExpected: + return Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("Parse_TokenNotExpected"); + case FMTResult::ArgsInterface_Unavaible: + return Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("ArgsInterface_Unavaible"); + case FMTResult::ArgsInterface_InvalidTypeID: + return Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("ArgsInterface_InvalidTypeID"); + case FMTResult::ArgsInterface_InvalidConversion: + return Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("ArgsInterface_InvalidConversion"); + case FMTResult::ArgsInterface_CantMatchNamedArgs: + return Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("ArgsInterface_CantMatchNamedArgs"); + case FMTResult::ArgsInterface_IndexOutOfBounds: + return Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("ArgsInterface_IndexOutOfBounds"); + case FMTResult::Specifers_Full: + return Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("Specifers_Full"); + case FMTResult::Specifers_Invalid: + return Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("Specifers_Invalid"); + case FMTResult::Specifers_DoesNotExist: + return Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("Specifers_DoesNotExist"); + case FMTResult::Context_ParsingFormat: + return Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("Context_ParsingFormat"); + case FMTResult::Context_ArgumentIndexResolution: + return Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("Context_ArgumentIndexResolution"); + case FMTResult::Context_ArgumentIndexExpected: + return Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("Context_ArgumentIndexExpected"); + case FMTResult::Context_CannotApplyType: + return Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("Context_CannotApplyType"); + case FMTResult::GivenArgs_UnableToDeduceSize: + return Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("GivenArgs_UnableToDeduceSize"); + case FMTResult::Manager_StaticMemory: + return Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("Manager_StaticMemory"); + case FMTResult::Manager_AllocationFailed: + return Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("Manager_AllocationFailed"); + } + } + }; +} diff --git a/src/StreamFormat/FMT/Context/ParserExecutor/UtilityFunctions.h b/src/StreamFormat/FMT/Context/ParserExecutor/UtilityFunctions.h index ccf4c6b4..0f982c7f 100644 --- a/src/StreamFormat/FMT/Context/ParserExecutor/UtilityFunctions.h +++ b/src/StreamFormat/FMT/Context/ParserExecutor/UtilityFunctions.h @@ -16,7 +16,7 @@ namespace StreamFormat::FMT Detail::BufferInfoView format{formatInput}; using TChar = typename decltype(format)::TChar; - Detail::ParserANSITextPropertiesExecutor> textPropertiesExecutor; + Detail::ParserNOTextPropertiesExecutor> textPropertiesExecutor; Context::BasicParserExecutor> executor(buffer, textPropertiesExecutor); SF_TRY(executor.Run(format, std::forward(args)...)); return executor.Terminate(); diff --git a/src/StreamFormat/FMT/Detail/FMTResult.h b/src/StreamFormat/FMT/Detail/FMTResult.h index d6b2215f..5b580c50 100644 --- a/src/StreamFormat/FMT/Detail/FMTResult.h +++ b/src/StreamFormat/FMT/Detail/FMTResult.h @@ -1,5 +1,7 @@ #pragma once +#include "StreamFormat/Core/Prelude.h" + namespace StreamFormat::FMT { enum class FMTResult @@ -33,3 +35,16 @@ namespace StreamFormat::FMT Manager_AllocationFailed, }; } + +namespace StreamFormat::Detail +{ + template<> + inline FMT::FMTResult forward_error(FMT::FMTResult t) + { + if (t == FMT::FMTResult::ArgsInterface_CantMatchNamedArgs) + return t; + if (t == FMT::FMTResult::Manager_StaticMemory) + return t; + return t; + } +} diff --git a/src/StreamFormat/ProfilerManager/ProfilerMacro.h b/src/StreamFormat/ProfilerManager/ProfilerMacro.h index 5f6059f3..ae84b803 100644 --- a/src/StreamFormat/ProfilerManager/ProfilerMacro.h +++ b/src/StreamFormat/ProfilerManager/ProfilerMacro.h @@ -2,16 +2,16 @@ #ifdef STREAMFORMAT_PROFILING_ENABLE -#define PCP_PROFILE_FUNCTION() StreamFormat::ProfilerManager::ScopeProfile profile##__LINE__(StreamFormat::ProfilerManager::Profiler::GetInstance(), __FUNCSIG__, "Function") -#define PCP_PROFILE_FUNCTION_FMT(...) \ +#define SFP_PROFILE_FUNCTION() StreamFormat::ProfilerManager::ScopeProfile profile##__LINE__(StreamFormat::ProfilerManager::Profiler::GetInstance(), __FUNCSIG__, "Function") +#define SFP_PROFILE_FUNCTION_FMT(...) \ StreamFormat::ProfilerManager::ScopeProfile profile##__LINE__(StreamFormat::ProfilerManager::Profiler::GetInstance(), \ StreamFormat::ProfilerManager::FMT::FormatString(__VA_ARGS__), "Function") -#define PCP_SAVE_DEFAULT_PROFILER() StreamFormat::ProfilerManager::ProfilerFactory::ToJson(StreamFormat::ProfilerManager::Profiler::GetInstance()) +#define SFP_SAVE_DEFAULT_PROFILER() StreamFormat::ProfilerManager::ProfilerFactory::ToJson(StreamFormat::ProfilerManager::Profiler::GetInstance()) #else // STREAMFORMAT_PROFILING_ENABLE -#define PCP_PROFILE_FUNCTION() -#define PCP_PROFILE_FUNCTION_FMT(...) -#define PCP_SAVE_DEFAULT_PROFILER() +#define SFP_PROFILE_FUNCTION() +#define SFP_PROFILE_FUNCTION_FMT(...) +#define SFP_SAVE_DEFAULT_PROFILER() #endif // STREAMFORMAT_PROFILING_ENABLE diff --git a/src/StreamFormat/Tester/TestSuite/BasicTest.h b/src/StreamFormat/Tester/TestSuite/BasicTest.h index d3bfeef6..eca962b0 100644 --- a/src/StreamFormat/Tester/TestSuite/BasicTest.h +++ b/src/StreamFormat/Tester/TestSuite/BasicTest.h @@ -2,6 +2,8 @@ #include "TestSuite.h" +#include "StreamFormat/Core/Prelude.h" + namespace StreamFormat::Tester::Detail { struct TestFunction : public Test @@ -33,6 +35,16 @@ namespace StreamFormat::Tester::Detail template void TestNotEq(T result, std::convertible_to auto notExpected, std::string_view testView, int line); + template + void TestEq(std::expected result, std::convertible_to auto expected, std::string_view testView, int line); + template + void TestNotEq(std::expected result, std::convertible_to auto notExpected, std::string_view testView, int line); + + template + void AssertExpected(std::expected result, std::string_view testView, int line); + template + void AssertOptional(std::optional result, std::string_view testView, int line); + public: FuncType Func; }; @@ -43,34 +55,67 @@ namespace StreamFormat::Tester::Detail T expected_as_T = static_cast(expected); if (result != expected_as_T) { - Link.TestLogger.Error("{C:red}{} return {} instead of {}", testView, result, expected, FORMAT_SV("test_name", Name)); + Link.TestLogger.Error("{C:red}{} return {} instead of {}", testView, result, expected, FORMAT_SV("test_name", Name)).value(); throw TestFailure{}; } - - Link.TestLogger.Trace("{C:green}{} return {}", testView, result, FORMAT_SV("test_name", Name)); + Link.TestLogger.Trace("{C:green}{} return {}", testView, result, FORMAT_SV("test_name", Name)).value(); } - template void TestFunction::TestNotEq(T result, std::convertible_to auto notExpected, std::string_view testView, [[maybe_unused]] int line) { if (result == static_cast(notExpected)) { - Link.TestLogger.Error("{C:red}{} return {} but this result was prohibited", testView, result, FORMAT_SV("test_name", Name)); + Link.TestLogger.Error("{C:red}{} return {} but that result was prohibited", testView, result, FORMAT_SV("test_name", Name)).value(); throw TestFailure{}; } - - Link.TestLogger.Trace("{C:green}{} return {}", testView, result, FORMAT_SV("test_name", Name)); + Link.TestLogger.Trace("{C:green}{} return {}", testView, result, FORMAT_SV("test_name", Name)).value(); } - inline void TestFunction::TestAssert(bool assert, std::string_view assertView, [[maybe_unused]] int line) { if (assert == false) { - Link.TestLogger.Error("{C:red}ASSERT FAILED : {}", assertView, FORMAT_SV("test_name", Name)); + Link.TestLogger.Error("{C:red}ASSERT FAILED : {}", assertView, FORMAT_SV("test_name", Name)).value(); throw TestFailure{}; } + Link.TestLogger.Trace("{C:green}ASSERT SUCCED : {}", assertView, FORMAT_SV("test_name", Name)).value(); + } - Link.TestLogger.Trace("{C:green}ASSERT SUCCED : {}", assertView, FORMAT_SV("test_name", Name)); + + template + void TestFunction::TestEq(std::expected result, std::convertible_to auto expected, std::string_view testView, [[maybe_unused]] int line) + { + if (result.has_value()) + TestEq(result.value(), expected, testView, line); + else + AssertExpected(result, testView, line); + } + template + void TestFunction::TestNotEq(std::expected result, std::convertible_to auto notExpected, std::string_view testView, [[maybe_unused]] int line) + { + if (result.has_value()) + TestEq(result.value(), notExpected, testView, line); + else + AssertExpected(result, testView, line); + } + + + template + void TestFunction::AssertExpected(std::expected result, std::string_view testView, int line) + { + if (result.has_value() == false) + { + Link.TestLogger.Error("{C:red}{} return an error: {}", testView, result.error(), FORMAT_SV("test_name", Name)).value(); + throw TestFailure{}; + } + } + template + void TestFunction::AssertOptional(std::optional result, std::string_view testView, int line) + { + if (result.has_value() == false) + { + Link.TestLogger.Error("{C:red}{} didn't return any value", testView, FORMAT_SV("test_name", Name)).value(); + throw TestFailure{}; + } } } @@ -80,11 +125,13 @@ namespace StreamFormat::Tester::Detail volatile StreamFormat::Tester::Detail::TestFunction STREAMFORMAT_TESTINTERNAL_FUNC_NAME(TestSuiteName, TestName)( \ #TestName, STREAMFORMAT_TESTINTERNAL_SUITE_NAME(TestSuiteName), STREAMFORMAT_TESTINTERNAL_FUNC_EXEC_NAME(TestSuiteName, TestName), STREAMFORMAT_FMT_FILE_LOCATION()) -#define PCT_TEST_FUNC(TestSuiteName, TestName) \ +#define SFT_TEST_FUNC(TestSuiteName, TestName) \ STREAMFORMAT_TESTINTERNAL_FUNC_DECLARE_EXEC(TestSuiteName, TestName) \ STREAMFORMAT_TESTINTERNAL_FUNC_CREATE(TestSuiteName, TestName); \ void STREAMFORMAT_TESTINTERNAL_FUNC_EXEC_NAME(TestSuiteName, TestName)(StreamFormat::Tester::Detail::TestFunction & link) -#define PCT_ASSERT(Test) link.TestAssert(Test, #Test, __LINE__) -#define PCT_EQ(Test, Expected) link.TestEq(Test, Expected, #Test, __LINE__) -#define PCT_NEQ(Test, NotExpected) link.TestNotEq(Test, NotExpected, #Test, __LINE__) +#define SFT_ASSERT(Test) link.TestAssert(Test, #Test, __LINE__) +#define SFT_EQ(Test, Expected) link.TestEq(Test, Expected, #Test, __LINE__) +#define SFT_NEQ(Test, NotExpected) link.TestNotEq(Test, NotExpected, #Test, __LINE__) + +#define SFT_EXPECTED_VALUE(Test) link.AssertExpected(Test, #Test, __LINE__) diff --git a/src/StreamFormat/Tester/TestSuite/TestSuite.h b/src/StreamFormat/Tester/TestSuite/TestSuite.h index a96ec946..16219b56 100644 --- a/src/StreamFormat/Tester/TestSuite/TestSuite.h +++ b/src/StreamFormat/Tester/TestSuite/TestSuite.h @@ -271,11 +271,11 @@ namespace StreamFormat::FMT } //-------------------- TestSuite --------------------// -#define PCT_TEST_SUITE(TestSuiteName, ...) \ +#define SFT_TEST_SUITE(TestSuiteName, ...) \ StreamFormat::Tester::Detail::TestSuite STREAMFORMAT_TESTINTERNAL_SUITE_NAME(TestSuiteName)(#TestSuiteName, STREAMFORMAT_TESTINTERNAL_SUITE_EXTRA(__VA_ARGS__)) -#define PCT_TEST_GROUP(TestSuiteName, GroupName, ...) \ +#define SFT_TEST_GROUP(TestSuiteName, GroupName, ...) \ StreamFormat::Tester::Detail::TestSuite STREAMFORMAT_TESTINTERNAL_SUITE_NAME(GroupName)(#GroupName, STREAMFORMAT_TESTINTERNAL_SUITE_EXTRA(__VA_ARGS__), \ &STREAMFORMAT_TESTINTERNAL_SUITE_NAME(TestSuiteName)) -#define PCT_TEST_SUITE_DECLARATION(TestSuiteName, ...) StreamFormat::Tester::Detail::TestSuite STREAMFORMAT_TESTINTERNAL_SUITE_NAME(TestSuiteName) -#define PCT_TEST_GROUP_DECLARATION(TestSuiteName, GroupName, ...) StreamFormat::Tester::Detail::TestSuite STREAMFORMAT_TESTINTERNAL_SUITE_NAME(GroupName) +#define SFT_TEST_SUITE_DECLARATION(TestSuiteName, ...) StreamFormat::Tester::Detail::TestSuite STREAMFORMAT_TESTINTERNAL_SUITE_NAME(TestSuiteName) +#define SFT_TEST_GROUP_DECLARATION(TestSuiteName, GroupName, ...) StreamFormat::Tester::Detail::TestSuite STREAMFORMAT_TESTINTERNAL_SUITE_NAME(GroupName) From 72b478a998933b80ba2cc79b52cd411d765a9303 Mon Sep 17 00:00:00 2001 From: BELLIER Sacha Date: Sun, 1 Dec 2024 14:40:47 +0100 Subject: [PATCH 09/42] wip: update CI; Windows MSVC does not support std::expected (C++23) --- .buildkite/linux_amd64.yml | 4 ++-- .buildkite/windows_amd64.yml | 6 ++--- .github/workflows/StreamFormat.yml | 36 +++++++++++++++--------------- 3 files changed, 23 insertions(+), 23 deletions(-) diff --git a/.buildkite/linux_amd64.yml b/.buildkite/linux_amd64.yml index d22b09cd..a38b4a4f 100644 --- a/.buildkite/linux_amd64.yml +++ b/.buildkite/linux_amd64.yml @@ -9,5 +9,5 @@ steps: - label: ":bazel: Build and Test on Clang (W asan)" commands: - - CC=clang bazelisk build --features=asan //:StreamFormatTests - - CC=clang bazelisk test --features=asan //:StreamFormatTests + - CC=clang-20 bazelisk build --features=asan //:StreamFormatTests + - CC=clang-20 bazelisk test --features=asan //:StreamFormatTests diff --git a/.buildkite/windows_amd64.yml b/.buildkite/windows_amd64.yml index 00e4841b..b446e4b9 100644 --- a/.buildkite/windows_amd64.yml +++ b/.buildkite/windows_amd64.yml @@ -2,9 +2,9 @@ agents: queue: "agent-runners-windows-amd64" steps: - - label: ":bazel: Build And Test MSVC" - commands: - - bazelisk test //:StreamFormatTests + # - label: ":bazel: Build And Test MSVC" + # commands: + # - bazelisk test //:StreamFormatTests - label: ":bazel: Build And Test Winlibs/clang" commands: diff --git a/.github/workflows/StreamFormat.yml b/.github/workflows/StreamFormat.yml index 715a01ae..064320f5 100644 --- a/.github/workflows/StreamFormat.yml +++ b/.github/workflows/StreamFormat.yml @@ -9,20 +9,20 @@ on: - '**' jobs: - windows-latest-msvc: - runs-on: windows-latest - steps: - - uses: actions/checkout@v4 - - uses: bazelbuild/setup-bazelisk@v3 - - name: Mount bazel cache - uses: actions/cache@v4 - with: - path: "~/.cache/bazel" - key: bazel - - name: Building... - run: bazelisk build //:StreamFormatTests - - name: Testing... - run: bazelisk test //:StreamFormatTests + # windows-latest-msvc: + # runs-on: windows-latest + # steps: + # - uses: actions/checkout@v4 + # - uses: bazelbuild/setup-bazelisk@v3 + # - name: Mount bazel cache + # uses: actions/cache@v4 + # with: + # path: "~/.cache/bazel" + # key: bazel + # - name: Building... + # run: bazelisk build //:StreamFormatTests + # - name: Testing... + # run: bazelisk test //:StreamFormatTests windows-latest-winlibs: runs-on: windows-latest @@ -70,10 +70,10 @@ jobs: run: | wget https://apt.llvm.org/llvm.sh chmod +x ./llvm.sh - sudo ./llvm.sh 17 + sudo ./llvm.sh 20 - name: Version - run: clang++-17 --version + run: clang++-20 --version - name: Building... - run: CC=clang++-17 bazelisk build //:StreamFormatTests + run: CC=clang++-20 bazelisk build //:StreamFormatTests - name: Testing... (W asan) - run: CC=clang++-17 bazelisk test --features=asan //:StreamFormatTests + run: CC=clang++-20 bazelisk test --features=asan //:StreamFormatTests From 9303921d749d3b535dfdd06706bce6c972b4bd37 Mon Sep 17 00:00:00 2001 From: BELLIER Sacha Date: Sun, 1 Dec 2024 14:54:25 +0100 Subject: [PATCH 10/42] wip: update to gcc 14 --- .buildkite/linux_amd64.yml | 4 ++-- .github/workflows/StreamFormat.yml | 11 +++++++---- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/.buildkite/linux_amd64.yml b/.buildkite/linux_amd64.yml index a38b4a4f..cbc49fef 100644 --- a/.buildkite/linux_amd64.yml +++ b/.buildkite/linux_amd64.yml @@ -4,8 +4,8 @@ agents: steps: - label: ":bazel: Build and Test on gcc (W asan)" commands: - - CC=gcc bazelisk build --features=asan //:StreamFormatTests - - CC=gcc bazelisk test --features=asan //:StreamFormatTests + - CC=gcc-14 bazelisk build --features=asan //:StreamFormatTests + - CC=gcc-14 bazelisk test --features=asan //:StreamFormatTests - label: ":bazel: Build and Test on Clang (W asan)" commands: diff --git a/.github/workflows/StreamFormat.yml b/.github/workflows/StreamFormat.yml index 064320f5..6fc4c289 100644 --- a/.github/workflows/StreamFormat.yml +++ b/.github/workflows/StreamFormat.yml @@ -49,12 +49,15 @@ jobs: with: path: "~/.cache/bazel" key: bazel + - name: Install Gcc 14 + run: | + sudo apt install gcc-14 - name: Version - run: gcc --version + run: gcc-14 --version - name: Building... - run: CC=gcc bazelisk build //:StreamFormatTests + run: CC=gcc-14 bazelisk build //:StreamFormatTests - name: Testing... (W asan) - run: CC=gcc bazelisk test --features=asan //:StreamFormatTests + run: CC=gcc-14 bazelisk test --features=asan //:StreamFormatTests ubuntu-latest-clang: runs-on: ubuntu-latest @@ -66,7 +69,7 @@ jobs: with: path: "~/.cache/bazel" key: bazel - - name: Install clang + - name: Install clang 20 run: | wget https://apt.llvm.org/llvm.sh chmod +x ./llvm.sh From 68b97fcfd1ba5c3d2c38dbb2db8beff35f3d8c11 Mon Sep 17 00:00:00 2001 From: BELLIER Sacha Date: Sun, 1 Dec 2024 15:06:22 +0100 Subject: [PATCH 11/42] wip: test with Gcc 13 on github --- .github/workflows/StreamFormat.yml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/StreamFormat.yml b/.github/workflows/StreamFormat.yml index 6fc4c289..1f971dca 100644 --- a/.github/workflows/StreamFormat.yml +++ b/.github/workflows/StreamFormat.yml @@ -49,15 +49,15 @@ jobs: with: path: "~/.cache/bazel" key: bazel - - name: Install Gcc 14 + - name: Install Gcc 13 run: | - sudo apt install gcc-14 + sudo apt install gcc-13 - name: Version - run: gcc-14 --version + run: gcc-13 --version - name: Building... - run: CC=gcc-14 bazelisk build //:StreamFormatTests + run: CC=gcc-13 bazelisk build //:StreamFormatTests - name: Testing... (W asan) - run: CC=gcc-14 bazelisk test --features=asan //:StreamFormatTests + run: CC=gcc-13 bazelisk test --features=asan //:StreamFormatTests ubuntu-latest-clang: runs-on: ubuntu-latest From 7d4684c4acfe0d3c889c0da15e28c1ba7f9e7c4c Mon Sep 17 00:00:00 2001 From: BELLIER Sacha Date: Sun, 1 Dec 2024 15:09:14 +0100 Subject: [PATCH 12/42] wip: use universe repo for apt --- .github/workflows/StreamFormat.yml | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/.github/workflows/StreamFormat.yml b/.github/workflows/StreamFormat.yml index 1f971dca..27f6086a 100644 --- a/.github/workflows/StreamFormat.yml +++ b/.github/workflows/StreamFormat.yml @@ -49,15 +49,17 @@ jobs: with: path: "~/.cache/bazel" key: bazel - - name: Install Gcc 13 + - name: Install Gcc 14 run: | - sudo apt install gcc-13 + sudo add-apt-repository universe + sudo apt-get update + sudo apt install gcc-14 - name: Version - run: gcc-13 --version + run: gcc-14 --version - name: Building... - run: CC=gcc-13 bazelisk build //:StreamFormatTests + run: CC=gcc-14 bazelisk build //:StreamFormatTests - name: Testing... (W asan) - run: CC=gcc-13 bazelisk test --features=asan //:StreamFormatTests + run: CC=gcc-14 bazelisk test --features=asan //:StreamFormatTests ubuntu-latest-clang: runs-on: ubuntu-latest From 761ed2c197bd89fc24376b0857d29ca2de7ef75c Mon Sep 17 00:00:00 2001 From: BELLIER Sacha Date: Sun, 1 Dec 2024 20:42:43 +0100 Subject: [PATCH 13/42] ... --- .github/workflows/StreamFormat.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/StreamFormat.yml b/.github/workflows/StreamFormat.yml index 27f6086a..f569af92 100644 --- a/.github/workflows/StreamFormat.yml +++ b/.github/workflows/StreamFormat.yml @@ -51,8 +51,10 @@ jobs: key: bazel - name: Install Gcc 14 run: | - sudo add-apt-repository universe + sudo apt install software-properties-common + sudo add-apt-repository ppa:ubuntu-toolchain-r/test sudo apt-get update + sudo apt install gcc-13 sudo apt install gcc-14 - name: Version run: gcc-14 --version From 776c925d1ac25dcd42fd721d8a728040b9782f22 Mon Sep 17 00:00:00 2001 From: BELLIER Sacha Date: Sun, 1 Dec 2024 20:44:46 +0100 Subject: [PATCH 14/42] use gcc13 --- .github/workflows/StreamFormat.yml | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/.github/workflows/StreamFormat.yml b/.github/workflows/StreamFormat.yml index f569af92..380e56bd 100644 --- a/.github/workflows/StreamFormat.yml +++ b/.github/workflows/StreamFormat.yml @@ -49,19 +49,18 @@ jobs: with: path: "~/.cache/bazel" key: bazel - - name: Install Gcc 14 + - name: Install Gcc 13 run: | sudo apt install software-properties-common sudo add-apt-repository ppa:ubuntu-toolchain-r/test sudo apt-get update sudo apt install gcc-13 - sudo apt install gcc-14 - name: Version - run: gcc-14 --version + run: gcc-13 --version - name: Building... - run: CC=gcc-14 bazelisk build //:StreamFormatTests + run: CC=gcc-13 bazelisk build //:StreamFormatTests - name: Testing... (W asan) - run: CC=gcc-14 bazelisk test --features=asan //:StreamFormatTests + run: CC=gcc-13 bazelisk test --features=asan //:StreamFormatTests ubuntu-latest-clang: runs-on: ubuntu-latest From 386720b6d1d2d79aca1ffc782874efdc3a4317b3 Mon Sep 17 00:00:00 2001 From: BELLIER Sacha Date: Sun, 1 Dec 2024 20:49:29 +0100 Subject: [PATCH 15/42] ... --- .github/workflows/StreamFormat.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/StreamFormat.yml b/.github/workflows/StreamFormat.yml index 380e56bd..ed85f641 100644 --- a/.github/workflows/StreamFormat.yml +++ b/.github/workflows/StreamFormat.yml @@ -55,6 +55,8 @@ jobs: sudo add-apt-repository ppa:ubuntu-toolchain-r/test sudo apt-get update sudo apt install gcc-13 + - name: Version + run: gcc --version - name: Version run: gcc-13 --version - name: Building... From a3f381cabec26a15a1dcaad3871c6e3e0bd24a6d Mon Sep 17 00:00:00 2001 From: Sacha Bellier Date: Sat, 22 Mar 2025 21:38:08 +0100 Subject: [PATCH 16/42] wip: using snake case file names --- .buildkite/linux_amd64.yml | 8 +- .buildkite/template.yml | 2 +- .buildkite/windows_amd64.yml | 6 +- .github/workflows/CodeChecker.yml.nop | 2 +- .github/workflows/StreamFormat.yml | 18 +- .gitignore | 14 +- BUILD.bazel | 8 +- Examples/HelloWorld/main.cpp | 15 -- Examples/README.md | 30 --- README.md | 10 +- Tests/FMT/BaseFMTTests.h | 5 - Tests/Tests.cpp | 9 - buildbuddy.yaml | 2 +- {conf => custom}/BUILD.bazel | 2 +- {Examples => examples}/.bazelrc | 0 {Examples => examples}/MODULE.bazel | 0 examples/README.md | 30 +++ .../HelloWorld => examples/hello}/BUILD.bazel | 4 +- examples/hello/main.cpp | 15 ++ src/StreamFormat/FLog.h | 11 - src/StreamFormat/FLog/LoggerFactory.h | 13 -- src/StreamFormat/FLog/LoggerImpl/XLogger.cpp | 14 -- src/StreamFormat/FLog/LoggerImpl/XLogger.h | 220 ------------------ src/StreamFormat/FMT.h | 5 - .../FMT/Buffer/Utils/BufferUtils.h | 131 ----------- .../BasicContext/ITextPropertiesExecutor.h | 48 ---- .../FormatterTextPropertiesExecutor.h | 66 ------ .../ParserANSITextPropertiesExecutor.h | 144 ------------ .../ParserTextPropertiesExecutor.h | 69 ------ .../FMT/Serializers/ParseChrono.h | 14 -- .../FMT/Serializers/ParseSTDLib.h | 12 - .../FMT/TextProperties/TextProperties.h | 20 -- src/StreamFormat/Json/JsonObjects.cpp | 59 ----- .../ProfilerManager/ProfilerJsonSerializers.h | 83 ------- .../ProfilerManager/ProfilerMacro.h | 17 -- .../Core/Prelude.h => stream/core/prelude.h} | 4 +- .../default_logger.h} | 16 +- src/stream/flog.h | 11 + .../flog/backends/basic_logger.h} | 24 +- .../flog/backends/logger_multi_sink.h} | 6 +- .../flog/backends/logger_multi_sink_fast.h} | 20 +- .../flog/backends/logger_multi_sink_safe.h} | 22 +- .../Detail.h => stream/flog/detail/detail.h} | 26 +-- src/stream/flog/frontends/xlogger.cpp | 14 ++ src/stream/flog/frontends/xlogger.h | 220 ++++++++++++++++++ src/stream/flog/logger_factory.h | 13 ++ .../flog/sinks/file_sink.h} | 14 +- .../flog/sinks/logger_sink.h} | 18 +- src/stream/fmt.h | 5 + .../fmt/buffer/buffer_info.h} | 8 +- .../fmt/buffer/buffer_manip.h} | 30 +-- .../basic_buffer_out_manager.h} | 6 +- .../dynamic_buffer_out_manager.h} | 4 +- .../given_buffer_out_manager.h} | 4 +- .../static_buffer_out_manager.h} | 4 +- .../fmt/buffer/buffer_out_manip.h} | 16 +- .../fmt/buffer/buffer_read_manip.h} | 42 ++-- .../fmt/buffer/buffer_test_manip.h} | 48 ++-- .../fmt/buffer/buffer_write_manip.h} | 20 +- .../fmt/buffer/fmt_buffer_out_manip.h} | 32 +-- .../fmt/buffer/fmt_buffer_read_manip.h} | 56 ++--- .../fmt/buffer/fmt_buffer_write_manip.h} | 84 +++---- .../fmt/buffer/utils/buffer_globber_manip.h} | 6 +- .../fmt/buffer/utils/buffer_shift_manip.h} | 48 ++-- src/stream/fmt/buffer/utils/buffer_utils.h | 131 +++++++++++ .../basic_context/basic_args_interface.h} | 10 +- .../context/basic_context/basic_context.h} | 68 +++--- .../basic_context/basic_context_parse_impl.h} | 166 ++++++------- .../basic_context/text_properties_executor.h | 48 ++++ .../text_properties_manager.cpp} | 68 +++--- .../basic_context/text_properties_manager.h} | 124 +++++----- .../text_properties_manager_impl.h} | 204 ++++++++-------- .../basic_formatter_executor.h} | 46 ++-- .../formatter_executor/format_basics_impl.h} | 78 +++---- .../format_text_properties_impl.h} | 34 +-- .../formatter_executor/formatter_args.h} | 12 +- .../formatter_text_properties_executor.h | 66 ++++++ ...formatter_text_properties_executor_ansi.h} | 52 ++--- .../formatter_executor/formatter_type.h} | 14 +- .../context/formatter_executor/index_args.h} | 6 +- .../context/formatter_executor/named_args.h} | 14 +- .../formatter_executor/std_enumerable.h} | 24 +- .../formatter_executor/utility_functions.h} | 164 ++++++------- .../parser_executor/basic_parser_executor.h} | 34 +-- .../parser_executor/parse_basics_impl.h} | 46 ++-- .../parse_text_properties_impl.h} | 32 +-- .../context/parser_executor/parser_args.h} | 10 +- .../parser_text_properties_executor.h | 69 ++++++ .../parser_text_properties_executor_ansi.h | 144 ++++++++++++ .../context/parser_executor/parser_type.h} | 10 +- .../parser_executor/utility_functions.h} | 14 +- .../fmt/context/utils/context_functions.h} | 6 +- .../fmt/detail/convert_traits.h} | 6 +- .../fmt/detail/fmt_result.h} | 12 +- .../fmt/detail/indent_handlers.h} | 8 +- .../Prelude.h => stream/fmt/detail/prelude.h} | 8 +- .../fmt/detail/specifiers.h} | 8 +- .../fmt/detail/types_traits.h} | 4 +- .../fmt/serializers/compilation_data.h} | 24 +- .../fmt/serializers/format_chrono.h} | 44 ++-- .../fmt/serializers/format_stdlib.h} | 32 +-- src/stream/fmt/serializers/parse_chrono.h | 14 ++ src/stream/fmt/serializers/parse_stdlib.h | 12 + .../serializers/std_container}/FMT_array.h | 8 +- .../serializers/std_container}/FMT_deque.h | 8 +- .../std_container}/FMT_forward_list.h | 8 +- .../fmt/serializers/std_container}/FMT_list.h | 8 +- .../fmt/serializers/std_container}/FMT_map.h | 12 +- .../serializers/std_container}/FMT_queue.h | 6 +- .../fmt/serializers/std_container}/FMT_set.h | 12 +- .../serializers/std_container}/FMT_stack.h | 6 +- .../serializers/std_container}/FMT_tuple.h | 24 +- .../std_container}/FMT_unordered_map.h | 12 +- .../std_container}/FMT_unordered_set.h | 12 +- .../serializers/std_container}/FMT_vector.h | 8 +- .../text_properties/base_text_properties.h} | 4 +- .../fmt/text_properties/text_properties.h | 20 ++ .../text_properties/text_properties_color.h} | 14 +- .../text_properties/text_properties_front.h} | 12 +- .../text_properties/text_properties_style.h} | 8 +- src/{StreamFormat/Json.h => stream/json.h} | 2 +- .../Json/Detail.h => stream/json/detail.h} | 4 +- .../json/json_factory.h} | 36 +-- .../json/json_formatter.h} | 24 +- .../json/json_formatter_impl.h} | 6 +- src/stream/json/json_objects.cpp | 59 +++++ .../json/json_objects.h} | 48 ++-- .../json/json_parser.cpp} | 24 +- .../json/json_parser.h} | 54 ++--- .../json/json_serializer.h} | 178 +++++++------- .../json/serializers/base_serializers.h} | 26 +-- .../serializers/json_objects_serializer.h} | 38 +-- .../json/serializers/serializers.h} | 0 .../std_serializers/basic_std_serializers.h} | 12 +- .../serializers/std_serializers/json_map.h} | 12 +- .../std_serializers/json_unordered_map.h} | 14 +- .../std_serializers/json_vector.h} | 10 +- .../ProfilerManager.h => stream/profiler.h} | 0 .../profiler/all_events.h} | 2 +- .../Detail.h => stream/profiler/detail.h} | 2 +- .../Event.h => stream/profiler/event.h} | 20 +- .../profiler/event_data.h} | 12 +- .../profiler/get_pid.cpp} | 2 +- .../Profiler.h => stream/profiler/profiler.h} | 10 +- .../profiler/profiler_event_creator.cpp} | 8 +- .../profiler/profiler_event_creator.h} | 2 +- .../profiler/profiler_factory.cpp} | 4 +- .../profiler/profiler_factory.h} | 2 +- .../profiler/profiler_json_serializers.h | 83 +++++++ src/stream/profiler/profiler_macros.h | 17 ++ .../tester/copy_move_check.h} | 26 +-- .../tester/test_suite/all_test_suite.h} | 0 .../tester/test_suite/basic_test.h} | 28 +-- .../tester/test_suite/test_suite.cpp} | 30 +-- .../tester/test_suite/test_suite.h} | 76 +++--- .../tester/tests_macros.h} | 24 +- tests/fmt/base_fmt_tests.h | 5 + .../fmt/complex_pattern.cpp | 6 +- .../FMT/Globber.cpp => tests/fmt/globber.cpp | 26 +-- Tests/FMT/Index.cpp => tests/fmt/index.cpp | 4 +- Tests/FMT/Limits.cpp => tests/fmt/limits.cpp | 40 ++-- Tests/FMT/Shift.cpp => tests/fmt/shift.cpp | 6 +- .../Specifier.cpp => tests/fmt/specifier.cpp | 6 +- .../fmt/text_properties.cpp | 10 +- tests/tests.cpp | 9 + 165 files changed, 2490 insertions(+), 2492 deletions(-) delete mode 100644 Examples/HelloWorld/main.cpp delete mode 100644 Examples/README.md delete mode 100644 Tests/FMT/BaseFMTTests.h delete mode 100644 Tests/Tests.cpp rename {conf => custom}/BUILD.bazel (89%) rename {Examples => examples}/.bazelrc (100%) rename {Examples => examples}/MODULE.bazel (100%) create mode 100644 examples/README.md rename {Examples/HelloWorld => examples/hello}/BUILD.bazel (85%) create mode 100644 examples/hello/main.cpp delete mode 100644 src/StreamFormat/FLog.h delete mode 100644 src/StreamFormat/FLog/LoggerFactory.h delete mode 100644 src/StreamFormat/FLog/LoggerImpl/XLogger.cpp delete mode 100644 src/StreamFormat/FLog/LoggerImpl/XLogger.h delete mode 100644 src/StreamFormat/FMT.h delete mode 100644 src/StreamFormat/FMT/Buffer/Utils/BufferUtils.h delete mode 100644 src/StreamFormat/FMT/Context/BasicContext/ITextPropertiesExecutor.h delete mode 100644 src/StreamFormat/FMT/Context/FormatterExecutor/FormatterTextPropertiesExecutor/FormatterTextPropertiesExecutor.h delete mode 100644 src/StreamFormat/FMT/Context/ParserExecutor/ParserTextPropertiesExecutor/ParserANSITextPropertiesExecutor.h delete mode 100644 src/StreamFormat/FMT/Context/ParserExecutor/ParserTextPropertiesExecutor/ParserTextPropertiesExecutor.h delete mode 100644 src/StreamFormat/FMT/Serializers/ParseChrono.h delete mode 100644 src/StreamFormat/FMT/Serializers/ParseSTDLib.h delete mode 100644 src/StreamFormat/FMT/TextProperties/TextProperties.h delete mode 100644 src/StreamFormat/Json/JsonObjects.cpp delete mode 100644 src/StreamFormat/ProfilerManager/ProfilerJsonSerializers.h delete mode 100644 src/StreamFormat/ProfilerManager/ProfilerMacro.h rename src/{StreamFormat/Core/Prelude.h => stream/core/prelude.h} (91%) rename src/{StreamFormat/FLog/DefaultLogger.h => stream/default_logger.h} (58%) create mode 100644 src/stream/flog.h rename src/{StreamFormat/FLog/Loggers/BasicLogger.h => stream/flog/backends/basic_logger.h} (83%) rename src/{StreamFormat/FLog/Loggers/LoggerMultiSinks.h => stream/flog/backends/logger_multi_sink.h} (92%) rename src/{StreamFormat/FLog/Loggers/LoggerMultiSinkFast.h => stream/flog/backends/logger_multi_sink_fast.h} (70%) rename src/{StreamFormat/FLog/Loggers/LoggerMultiSinkSafe.h => stream/flog/backends/logger_multi_sink_safe.h} (77%) rename src/{StreamFormat/FLog/Detail/Detail.h => stream/flog/detail/detail.h} (54%) create mode 100644 src/stream/flog/frontends/xlogger.cpp create mode 100644 src/stream/flog/frontends/xlogger.h create mode 100644 src/stream/flog/logger_factory.h rename src/{StreamFormat/FLog/Sinks/FileSink.h => stream/flog/sinks/file_sink.h} (83%) rename src/{StreamFormat/FLog/Sinks/LoggerSink.h => stream/flog/sinks/logger_sink.h} (88%) create mode 100644 src/stream/fmt.h rename src/{StreamFormat/FMT/Buffer/BufferInfo.h => stream/fmt/buffer/buffer_info.h} (91%) rename src/{StreamFormat/FMT/Buffer/BufferManip.h => stream/fmt/buffer/buffer_manip.h} (85%) rename src/{StreamFormat/FMT/Buffer/BufferOutManager/BasicBufferOutManager.h => stream/fmt/buffer/buffer_out_manager/basic_buffer_out_manager.h} (94%) rename src/{StreamFormat/FMT/Buffer/BufferOutManager/DynamicBufferOutManager.h => stream/fmt/buffer/buffer_out_manager/dynamic_buffer_out_manager.h} (98%) rename src/{StreamFormat/FMT/Buffer/BufferOutManager/GivenBufferOutManager.h => stream/fmt/buffer/buffer_out_manager/given_buffer_out_manager.h} (94%) rename src/{StreamFormat/FMT/Buffer/BufferOutManager/StaticBufferOutManager.h => stream/fmt/buffer/buffer_out_manager/static_buffer_out_manager.h} (92%) rename src/{StreamFormat/FMT/Buffer/BufferOutManip.h => stream/fmt/buffer/buffer_out_manip.h} (91%) rename src/{StreamFormat/FMT/Buffer/BufferReadManip.h => stream/fmt/buffer/buffer_read_manip.h} (69%) rename src/{StreamFormat/FMT/Buffer/BufferTestManip.h => stream/fmt/buffer/buffer_test_manip.h} (80%) rename src/{StreamFormat/FMT/Buffer/BufferWriteManip.h => stream/fmt/buffer/buffer_write_manip.h} (93%) rename src/{StreamFormat/FMT/Buffer/FMTBufferOutManip.h => stream/fmt/buffer/fmt_buffer_out_manip.h} (79%) rename src/{StreamFormat/FMT/Buffer/FMTBufferReadManip.h => stream/fmt/buffer/fmt_buffer_read_manip.h} (82%) rename src/{StreamFormat/FMT/Buffer/FMTBufferWriteManip.h => stream/fmt/buffer/fmt_buffer_write_manip.h} (76%) rename src/{StreamFormat/FMT/Buffer/Utils/BufferGlobberManip.h => stream/fmt/buffer/utils/buffer_globber_manip.h} (97%) rename src/{StreamFormat/FMT/Buffer/Utils/BufferShiftManip.h => stream/fmt/buffer/utils/buffer_shift_manip.h} (56%) create mode 100644 src/stream/fmt/buffer/utils/buffer_utils.h rename src/{StreamFormat/FMT/Context/BasicContext/BasicArgsInterface.h => stream/fmt/context/basic_context/basic_args_interface.h} (93%) rename src/{StreamFormat/FMT/Context/BasicContext/BasicContext.h => stream/fmt/context/basic_context/basic_context.h} (68%) rename src/{StreamFormat/FMT/Context/BasicContext/BasicContextParse-impl.h => stream/fmt/context/basic_context/basic_context_parse_impl.h} (66%) create mode 100644 src/stream/fmt/context/basic_context/text_properties_executor.h rename src/{StreamFormat/FMT/Context/BasicContext/TextPropertiesManager.cpp => stream/fmt/context/basic_context/text_properties_manager.cpp} (73%) rename src/{StreamFormat/FMT/Context/BasicContext/TextPropertiesManager.h => stream/fmt/context/basic_context/text_properties_manager.h} (65%) rename src/{StreamFormat/FMT/Context/BasicContext/TextPropertiesManager-impl.h => stream/fmt/context/basic_context/text_properties_manager_impl.h} (60%) rename src/{StreamFormat/FMT/Context/FormatterExecutor/BasicFormatterExecutor.h => stream/fmt/context/formatter_executor/basic_formatter_executor.h} (69%) rename src/{StreamFormat/FMT/Context/FormatterExecutor/FormatBasics-impl.h => stream/fmt/context/formatter_executor/format_basics_impl.h} (63%) rename src/{StreamFormat/FMT/Context/FormatterExecutor/FormatTextProperties-impl.h => stream/fmt/context/formatter_executor/format_text_properties_impl.h} (54%) rename src/{StreamFormat/FMT/Context/FormatterExecutor/FormatterArgs.h => stream/fmt/context/formatter_executor/formatter_args.h} (94%) create mode 100644 src/stream/fmt/context/formatter_executor/formatter_text_properties_executor/formatter_text_properties_executor.h rename src/{StreamFormat/FMT/Context/FormatterExecutor/FormatterTextPropertiesExecutor/FormatterANSITextPropertiesExecutor.h => stream/fmt/context/formatter_executor/formatter_text_properties_executor/formatter_text_properties_executor_ansi.h} (61%) rename src/{StreamFormat/FMT/Context/FormatterExecutor/FormatterType.h => stream/fmt/context/formatter_executor/formatter_type.h} (73%) rename src/{StreamFormat/FMT/Context/FormatterExecutor/IndexArgs.h => stream/fmt/context/formatter_executor/index_args.h} (87%) rename src/{StreamFormat/FMT/Context/FormatterExecutor/NamedArgs.h => stream/fmt/context/formatter_executor/named_args.h} (88%) rename src/{StreamFormat/FMT/Context/FormatterExecutor/STDEnumerable.h => stream/fmt/context/formatter_executor/std_enumerable.h} (81%) rename src/{StreamFormat/FMT/Context/FormatterExecutor/UtilityFunctions.h => stream/fmt/context/formatter_executor/utility_functions.h} (54%) rename src/{StreamFormat/FMT/Context/ParserExecutor/BasicParserExecutor.h => stream/fmt/context/parser_executor/basic_parser_executor.h} (67%) rename src/{StreamFormat/FMT/Context/ParserExecutor/ParseBasics-impl.h => stream/fmt/context/parser_executor/parse_basics_impl.h} (69%) rename src/{StreamFormat/FMT/Context/ParserExecutor/ParseTextProperties-impl.h => stream/fmt/context/parser_executor/parse_text_properties_impl.h} (66%) rename src/{StreamFormat/FMT/Context/ParserExecutor/ParserArgs.h => stream/fmt/context/parser_executor/parser_args.h} (95%) create mode 100644 src/stream/fmt/context/parser_executor/parser_text_properties_executor/parser_text_properties_executor.h create mode 100644 src/stream/fmt/context/parser_executor/parser_text_properties_executor/parser_text_properties_executor_ansi.h rename src/{StreamFormat/FMT/Context/ParserExecutor/ParserType.h => stream/fmt/context/parser_executor/parser_type.h} (74%) rename src/{StreamFormat/FMT/Context/ParserExecutor/UtilityFunctions.h => stream/fmt/context/parser_executor/utility_functions.h} (57%) rename src/{StreamFormat/FMT/Context/Utils/ContextFunctions.h => stream/fmt/context/utils/context_functions.h} (75%) rename src/{StreamFormat/FMT/Detail/ConvertTraits.h => stream/fmt/detail/convert_traits.h} (93%) rename src/{StreamFormat/FMT/Detail/FMTResult.h => stream/fmt/detail/fmt_result.h} (75%) rename src/{StreamFormat/FMT/Detail/IndentHandlers.h => stream/fmt/detail/indent_handlers.h} (57%) rename src/{StreamFormat/FMT/Detail/Prelude.h => stream/fmt/detail/prelude.h} (82%) rename src/{StreamFormat/FMT/Detail/Specifiers.h => stream/fmt/detail/specifiers.h} (98%) rename src/{StreamFormat/FMT/Detail/TypesTraits.h => stream/fmt/detail/types_traits.h} (87%) rename src/{StreamFormat/FMT/Serializers/CompilationData.h => stream/fmt/serializers/compilation_data.h} (70%) rename src/{StreamFormat/FMT/Serializers/FormatChrono.h => stream/fmt/serializers/format_chrono.h} (81%) rename src/{StreamFormat/FMT/Serializers/FormatSTDLib.h => stream/fmt/serializers/format_stdlib.h} (65%) create mode 100644 src/stream/fmt/serializers/parse_chrono.h create mode 100644 src/stream/fmt/serializers/parse_stdlib.h rename src/{StreamFormat/FMT/Serializers/STDContainer => stream/fmt/serializers/std_container}/FMT_array.h (60%) rename src/{StreamFormat/FMT/Serializers/STDContainer => stream/fmt/serializers/std_container}/FMT_deque.h (57%) rename src/{StreamFormat/FMT/Serializers/STDContainer => stream/fmt/serializers/std_container}/FMT_forward_list.h (60%) rename src/{StreamFormat/FMT/Serializers/STDContainer => stream/fmt/serializers/std_container}/FMT_list.h (57%) rename src/{StreamFormat/FMT/Serializers/STDContainer => stream/fmt/serializers/std_container}/FMT_map.h (66%) rename src/{StreamFormat/FMT/Serializers/STDContainer => stream/fmt/serializers/std_container}/FMT_queue.h (65%) rename src/{StreamFormat/FMT/Serializers/STDContainer => stream/fmt/serializers/std_container}/FMT_set.h (62%) rename src/{StreamFormat/FMT/Serializers/STDContainer => stream/fmt/serializers/std_container}/FMT_stack.h (62%) rename src/{StreamFormat/FMT/Serializers/STDContainer => stream/fmt/serializers/std_container}/FMT_tuple.h (75%) rename src/{StreamFormat/FMT/Serializers/STDContainer => stream/fmt/serializers/std_container}/FMT_unordered_map.h (66%) rename src/{StreamFormat/FMT/Serializers/STDContainer => stream/fmt/serializers/std_container}/FMT_unordered_set.h (64%) rename src/{StreamFormat/FMT/Serializers/STDContainer => stream/fmt/serializers/std_container}/FMT_vector.h (57%) rename src/{StreamFormat/FMT/TextProperties/BaseTextProperties.h => stream/fmt/text_properties/base_text_properties.h} (79%) create mode 100644 src/stream/fmt/text_properties/text_properties.h rename src/{StreamFormat/FMT/TextProperties/TextPropertiesColor.h => stream/fmt/text_properties/text_properties_color.h} (98%) rename src/{StreamFormat/FMT/TextProperties/TextPropertiesFront.h => stream/fmt/text_properties/text_properties_front.h} (87%) rename src/{StreamFormat/FMT/TextProperties/TextPropertiesStyle.h => stream/fmt/text_properties/text_properties_style.h} (98%) rename src/{StreamFormat/Json.h => stream/json.h} (72%) rename src/{StreamFormat/Json/Detail.h => stream/json/detail.h} (96%) rename src/{StreamFormat/Json/JsonFactory.h => stream/json/json_factory.h} (66%) rename src/{StreamFormat/Json/JsonFormatter.h => stream/json/json_formatter.h} (76%) rename src/{StreamFormat/Json/JsonFormatter-inl.h => stream/json/json_formatter_impl.h} (85%) create mode 100644 src/stream/json/json_objects.cpp rename src/{StreamFormat/Json/JsonObjects.h => stream/json/json_objects.h} (80%) rename src/{StreamFormat/Json/JsonParser.cpp => stream/json/json_parser.cpp} (80%) rename src/{StreamFormat/Json/JsonParser.h => stream/json/json_parser.h} (55%) rename src/{StreamFormat/Json/JsonSerializer.h => stream/json/json_serializer.h} (51%) rename src/{StreamFormat/Json/Serializers/BaseSerializers.h => stream/json/serializers/base_serializers.h} (67%) rename src/{StreamFormat/Json/Serializers/JsonObjectsSerializer.h => stream/json/serializers/json_objects_serializer.h} (65%) rename src/{StreamFormat/Json/Serializers/Serializers.h => stream/json/serializers/serializers.h} (100%) rename src/{StreamFormat/Json/Serializers/STDSerializers/BasicSTDSerializers.h => stream/json/serializers/std_serializers/basic_std_serializers.h} (58%) rename src/{StreamFormat/Json/Serializers/STDSerializers/JSON_map.h => stream/json/serializers/std_serializers/json_map.h} (81%) rename src/{StreamFormat/Json/Serializers/STDSerializers/JSON_unordered_map.h => stream/json/serializers/std_serializers/json_unordered_map.h} (77%) rename src/{StreamFormat/Json/Serializers/STDSerializers/JSON_vector.h => stream/json/serializers/std_serializers/json_vector.h} (74%) rename src/{StreamFormat/ProfilerManager.h => stream/profiler.h} (100%) rename src/{StreamFormat/ProfilerManager/AllEvents.h => stream/profiler/all_events.h} (96%) rename src/{StreamFormat/ProfilerManager/Detail.h => stream/profiler/detail.h} (85%) rename src/{StreamFormat/ProfilerManager/Event.h => stream/profiler/event.h} (85%) rename src/{StreamFormat/ProfilerManager/EventData.h => stream/profiler/event_data.h} (53%) rename src/{StreamFormat/ProfilerManager/GetPid.cpp => stream/profiler/get_pid.cpp} (90%) rename src/{StreamFormat/ProfilerManager/Profiler.h => stream/profiler/profiler.h} (80%) rename src/{StreamFormat/ProfilerManager/ProfilerEventCreator.cpp => stream/profiler/profiler_event_creator.cpp} (87%) rename src/{StreamFormat/ProfilerManager/ProfilerEventCreator.h => stream/profiler/profiler_event_creator.h} (97%) rename src/{StreamFormat/ProfilerManager/ProfilerFactory.cpp => stream/profiler/profiler_factory.cpp} (84%) rename src/{StreamFormat/ProfilerManager/ProfilerFactory.h => stream/profiler/profiler_factory.h} (83%) create mode 100644 src/stream/profiler/profiler_json_serializers.h create mode 100644 src/stream/profiler/profiler_macros.h rename src/{StreamFormat/Tester/CopyMoveCheck.h => stream/tester/copy_move_check.h} (74%) rename src/{StreamFormat/Tester/TestSuite/AllTestSuite.h => stream/tester/test_suite/all_test_suite.h} (100%) rename src/{StreamFormat/Tester/TestSuite/BasicTest.h => stream/tester/test_suite/basic_test.h} (85%) rename src/{StreamFormat/Tester/TestSuite/TestSuite.cpp => stream/tester/test_suite/test_suite.cpp} (85%) rename src/{StreamFormat/Tester/TestSuite/TestSuite.h => stream/tester/test_suite/test_suite.h} (69%) rename src/{StreamFormat/Tester/TestsMacros.h => stream/tester/tests_macros.h} (78%) create mode 100644 tests/fmt/base_fmt_tests.h rename Tests/FMT/ComplexPattern.cpp => tests/fmt/complex_pattern.cpp (50%) rename Tests/FMT/Globber.cpp => tests/fmt/globber.cpp (64%) rename Tests/FMT/Index.cpp => tests/fmt/index.cpp (53%) rename Tests/FMT/Limits.cpp => tests/fmt/limits.cpp (69%) rename Tests/FMT/Shift.cpp => tests/fmt/shift.cpp (98%) rename Tests/FMT/Specifier.cpp => tests/fmt/specifier.cpp (88%) rename Tests/FMT/TextProperties.cpp => tests/fmt/text_properties.cpp (88%) create mode 100644 tests/tests.cpp diff --git a/.buildkite/linux_amd64.yml b/.buildkite/linux_amd64.yml index cbc49fef..187bd166 100644 --- a/.buildkite/linux_amd64.yml +++ b/.buildkite/linux_amd64.yml @@ -4,10 +4,10 @@ agents: steps: - label: ":bazel: Build and Test on gcc (W asan)" commands: - - CC=gcc-14 bazelisk build --features=asan //:StreamFormatTests - - CC=gcc-14 bazelisk test --features=asan //:StreamFormatTests + - CC=gcc-14 bazelisk build --features=asan //:streamTests + - CC=gcc-14 bazelisk test --features=asan //:streamTests - label: ":bazel: Build and Test on Clang (W asan)" commands: - - CC=clang-20 bazelisk build --features=asan //:StreamFormatTests - - CC=clang-20 bazelisk test --features=asan //:StreamFormatTests + - CC=clang-20 bazelisk build --features=asan //:streamTests + - CC=clang-20 bazelisk test --features=asan //:streamTests diff --git a/.buildkite/template.yml b/.buildkite/template.yml index f9554e65..93406276 100644 --- a/.buildkite/template.yml +++ b/.buildkite/template.yml @@ -1,4 +1,4 @@ -name: "StreamFormat" +name: "stream" steps: - label: ":pipeline: Launch Embbeded Pipeline" command: "buildkite-agent pipeline upload .builkite/pipeline.yml" diff --git a/.buildkite/windows_amd64.yml b/.buildkite/windows_amd64.yml index b446e4b9..fe79bee9 100644 --- a/.buildkite/windows_amd64.yml +++ b/.buildkite/windows_amd64.yml @@ -4,11 +4,11 @@ agents: steps: # - label: ":bazel: Build And Test MSVC" # commands: - # - bazelisk test //:StreamFormatTests + # - bazelisk test //:streamTests - label: ":bazel: Build And Test Winlibs/clang" commands: - - bazelisk build --config=winlibs-clang //:StreamFormatTests + - bazelisk build --config=winlibs-clang //:streamTests - label: ":bazel: Build And Test Winlibs/gcc" commands: - - bazelisk build --config=winlibs-gcc //:StreamFormatTests + - bazelisk build --config=winlibs-gcc //:streamTests diff --git a/.github/workflows/CodeChecker.yml.nop b/.github/workflows/CodeChecker.yml.nop index 2c679d7d..601952e8 100644 --- a/.github/workflows/CodeChecker.yml.nop +++ b/.github/workflows/CodeChecker.yml.nop @@ -23,7 +23,7 @@ jobs: - name: build & retreive compile_commands.json run: | bazelisk clean - bazelisk build //:StreamFormatTests + bazelisk build //:streamTests bazelisk run //conf:compile_commands - uses: whisperity/CodeChecker-Action@v1.0.4 diff --git a/.github/workflows/StreamFormat.yml b/.github/workflows/StreamFormat.yml index ed85f641..6de47744 100644 --- a/.github/workflows/StreamFormat.yml +++ b/.github/workflows/StreamFormat.yml @@ -1,4 +1,4 @@ -name: StreamFormat +name: stream on: push: @@ -20,9 +20,9 @@ jobs: # path: "~/.cache/bazel" # key: bazel # - name: Building... - # run: bazelisk build //:StreamFormatTests + # run: bazelisk build //:streamTests # - name: Testing... - # run: bazelisk test //:StreamFormatTests + # run: bazelisk test //:streamTests windows-latest-winlibs: runs-on: windows-latest @@ -35,9 +35,9 @@ jobs: path: "~/.cache/bazel" key: bazel - name: Build Winlibs/clang... - run: bazelisk build --config=winlibs-clang //:StreamFormatTests + run: bazelisk build --config=winlibs-clang //:streamTests - name: Build Winlibs/gcc... - run: bazelisk build --config=winlibs-gcc //:StreamFormatTests + run: bazelisk build --config=winlibs-gcc //:streamTests ubuntu-latest-gcc: runs-on: ubuntu-latest @@ -60,9 +60,9 @@ jobs: - name: Version run: gcc-13 --version - name: Building... - run: CC=gcc-13 bazelisk build //:StreamFormatTests + run: CC=gcc-13 bazelisk build //:streamTests - name: Testing... (W asan) - run: CC=gcc-13 bazelisk test --features=asan //:StreamFormatTests + run: CC=gcc-13 bazelisk test --features=asan //:streamTests ubuntu-latest-clang: runs-on: ubuntu-latest @@ -82,6 +82,6 @@ jobs: - name: Version run: clang++-20 --version - name: Building... - run: CC=clang++-20 bazelisk build //:StreamFormatTests + run: CC=clang++-20 bazelisk build //:streamTests - name: Testing... (W asan) - run: CC=clang++-20 bazelisk test --features=asan //:StreamFormatTests + run: CC=clang++-20 bazelisk test --features=asan //:streamTests diff --git a/.gitignore b/.gitignore index 60a935ff..431b3530 100644 --- a/.gitignore +++ b/.gitignore @@ -1,13 +1,11 @@ # bazel -MODULE.bazel.lock -bazel-bin -bazel-out -bazel-streamformat -bazel-StreamFormat -bazel-examples -bazel-Examples -bazel-testlogs +*.lock +bazel-* + +.coverage +.codechecker +compile_commands.json # VS .vs diff --git a/BUILD.bazel b/BUILD.bazel index d9fd5828..67944ba3 100644 --- a/BUILD.bazel +++ b/BUILD.bazel @@ -3,7 +3,7 @@ load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test") cc_library( - name = "StreamFormat", + name = "stream", srcs = glob([ "src/**/*.h", "src/**/*.cpp" ]), hdrs = glob([ "src/**/*.h" ]), includes = [ "src/" ], @@ -12,13 +12,13 @@ cc_library( "//conditions:default": ["-std=c++23"], }), strip_include_prefix = "src", - include_prefix = "StreamFormat", + include_prefix = "stream", linkstatic = True, visibility = ["//visibility:public"], ) cc_test( - name = "StreamFormatTests", + name = "streamTests", srcs = glob([ "Tests/**/*.h", "Tests/**/*.cpp" ]), copts = select({ "@rules_cc//cc/compiler:msvc-cl": ["/std:latest"], @@ -30,7 +30,7 @@ cc_test( "-Werror=return-type" ], }), - deps = [ ":StreamFormat" ], + deps = [ ":stream" ], linkopts = select({ "@rules_cc//cc/compiler:msvc-cl": [""], "//conditions:default": ["-pthread"], diff --git a/Examples/HelloWorld/main.cpp b/Examples/HelloWorld/main.cpp deleted file mode 100644 index cca27e5e..00000000 --- a/Examples/HelloWorld/main.cpp +++ /dev/null @@ -1,15 +0,0 @@ -#include "StreamFormat/FLog.h" -#include "StreamFormat/FLog/DefaultLogger.h" -#include "StreamFormat/FMT/Context/FormatterExecutor/UtilityFunctions.h" - -#include - -int main() -{ - StreamFormat::FLog::DefaultLogger::Core().Info("HelloWorld !"); - - using namespace std::chrono_literals; - std::this_thread::sleep_for(100ms); - - StreamFormat::FLog::DefaultLogger::Core().Warn("After 100ms !"); -} diff --git a/Examples/README.md b/Examples/README.md deleted file mode 100644 index 017bf429..00000000 --- a/Examples/README.md +++ /dev/null @@ -1,30 +0,0 @@ -# Example of StreamFormat - -### Try thoses examples ! - -##### Build and Run examples one by one (Recommended) -Example with `//HelloWorld:HelloWorld` (see below for the list of example) -``` -bazelisk run //HelloWorld:HelloWorld - -[00:00:00:000] APP-Core >> HelloWorld ! -[00:00:00:105] APP-Core >> After 100ms ! -``` - -##### Compile all examples, then run binaries -To compile every example: -``` -bazelisk build //... -``` - -Then you can run a program with (example with `//HelloWorld:HelloWorld`, see below for the list of example) -``` -.\bazel-bin\HelloWorld\HelloWorld - -[00:00:00:000] APP-Core >> HelloWorld ! -[00:00:00:105] APP-Core >> After 100ms ! -``` - -### List Of Examples - -- `//HelloWorld:HelloWorld`: HelloWorld using the Internal Logger diff --git a/README.md b/README.md index a7ee7133..fd4e2b5a 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ [![Build status](https://badge.buildkite.com/c74bfd00e5543dcb5645acecbfd9d1fc3a0487bc5de13db0b9.svg)](https://buildkite.com/sacha/streamformat) -[![StreamFormat](https://github.com/0-Sacha/StreamFormat/actions/workflows/StreamFormat.yml/badge.svg)](https://github.com/0-Sacha/StreamFormat/actions/workflows/StreamFormat.yml) +[![stream](https://github.com/0-Sacha/stream/actions/workflows/stream.yml/badge.svg)](https://github.com/0-Sacha/stream/actions/workflows/stream.yml) -# StreamFormat +# stream -StreamFormat is a C++23 String Formatter, like [<fmt>](https://github.com/fmtlib/fmt) +stream is a C++23 String Formatter, like [<fmt>](https://github.com/fmtlib/fmt) Using this formatter, it define others functionalities: - Logger like [spdlog](https://github.com/gabime/spdlog) - Json Serializer @@ -21,12 +21,12 @@ For now, at least, you have the [Examples](Examples/README.md) (and maybe the Te ## Download ``` -git clone git@github.com:0-Sacha/StreamFormat.git +git clone git@github.com:0-Sacha/stream.git ``` ## Using the Lib It can be used using [Bazel](https://bazel.build/). -A `cc_library` rule has been created: `@StreamFormat//:StreamFormat`. +A `cc_library` rule has been created: `@stream//:stream`. You need to add the module `streamformat` to your dependencies. ## Examples diff --git a/Tests/FMT/BaseFMTTests.h b/Tests/FMT/BaseFMTTests.h deleted file mode 100644 index daed614f..00000000 --- a/Tests/FMT/BaseFMTTests.h +++ /dev/null @@ -1,5 +0,0 @@ -#pragma once - -#include "StreamFormat/Tester/TestSuite/AllTestSuite.h" - -inline SFT_TEST_SUITE(FMT); diff --git a/Tests/Tests.cpp b/Tests/Tests.cpp deleted file mode 100644 index b5d3dd84..00000000 --- a/Tests/Tests.cpp +++ /dev/null @@ -1,9 +0,0 @@ - -#include "StreamFormat/Tester/TestSuite/AllTestSuite.h" -#include "StreamFormat/FLog/DefaultLogger.h" - -int main() -{ - StreamFormat::Tester::TestSuitesManager::Verbose = false; - return StreamFormat::Tester::TestSuitesManager::ExecAllTestSuites(); -} diff --git a/buildbuddy.yaml b/buildbuddy.yaml index eaae239f..f8fcbba6 100644 --- a/buildbuddy.yaml +++ b/buildbuddy.yaml @@ -15,4 +15,4 @@ actions: branches: - "*" bazel_commands: - - "test -s --config=buildbuddy --remote_header=x-buildbuddy-api-key=${BUILDBUDDY_WINDOWS_WSL} //:StreamFormatTests" + - "test -s --config=buildbuddy --remote_header=x-buildbuddy-api-key=${BUILDBUDDY_WINDOWS_WSL} //:streamTests" diff --git a/conf/BUILD.bazel b/custom/BUILD.bazel similarity index 89% rename from conf/BUILD.bazel rename to custom/BUILD.bazel index 1fd3760b..247112d4 100644 --- a/conf/BUILD.bazel +++ b/custom/BUILD.bazel @@ -8,6 +8,6 @@ refresh_compile_commands( exclude_external_sources = True, exclude_headers = "external", targets = { - "//:StreamFormat": "", + "//:stream": "", }, ) diff --git a/Examples/.bazelrc b/examples/.bazelrc similarity index 100% rename from Examples/.bazelrc rename to examples/.bazelrc diff --git a/Examples/MODULE.bazel b/examples/MODULE.bazel similarity index 100% rename from Examples/MODULE.bazel rename to examples/MODULE.bazel diff --git a/examples/README.md b/examples/README.md new file mode 100644 index 00000000..5a46ec67 --- /dev/null +++ b/examples/README.md @@ -0,0 +1,30 @@ +# Example of stream + +### Try thoses examples ! + +##### Build and Run examples one by one (Recommended) +Example with `//hello:hello` (see below for the list of example) +``` +bazelisk run //hello:hello + +[00:00:00:000] APP-Core >> hello ! +[00:00:00:105] APP-Core >> After 100ms ! +``` + +##### Compile all examples, then run binaries +To compile every example: +``` +bazelisk build //... +``` + +Then you can run a program with (example with `//hello:hello`, see below for the list of example) +``` +.\bazel-bin\hello\hello + +[00:00:00:000] APP-Core >> hello ! +[00:00:00:105] APP-Core >> After 100ms ! +``` + +### List Of Examples + +- `//hello:hello`: hello using the Internal Logger diff --git a/Examples/HelloWorld/BUILD.bazel b/examples/hello/BUILD.bazel similarity index 85% rename from Examples/HelloWorld/BUILD.bazel rename to examples/hello/BUILD.bazel index 0c7e4769..f981b427 100644 --- a/Examples/HelloWorld/BUILD.bazel +++ b/examples/hello/BUILD.bazel @@ -3,7 +3,7 @@ load("@rules_cc//cc:defs.bzl", "cc_binary") cc_binary( - name = "HelloWorld", + name = "hello", srcs = glob([ "*.h", "*.cpp" ]), includes = [ "" ], copts = select({ @@ -14,6 +14,6 @@ cc_binary( "@rules_cc//cc/compiler:msvc-cl": [""], "//conditions:default": ["-pthread"], }), - deps = [ "@streamformat//:StreamFormat" ], + deps = [ "@streamformat//:stream" ], visibility = ["//visibility:public"], ) diff --git a/examples/hello/main.cpp b/examples/hello/main.cpp new file mode 100644 index 00000000..9afc867e --- /dev/null +++ b/examples/hello/main.cpp @@ -0,0 +1,15 @@ +#include "stream/flog.h" +#include "stream/flog/DefaultLogger.h" +#include "stream/fmt/context/formatter_executor/utility_functions.h" + +#include + +int main() +{ + stream::flog::DefaultLogger::Core().info("HelloWorld !"); + + using namespace std::chrono_literals; + std::this_thread::sleep_for(100ms); + + stream::flog::DefaultLogger::Core().warn("After 100ms !"); +} diff --git a/src/StreamFormat/FLog.h b/src/StreamFormat/FLog.h deleted file mode 100644 index 759c94a2..00000000 --- a/src/StreamFormat/FLog.h +++ /dev/null @@ -1,11 +0,0 @@ -#pragma once - -#include "FLog/Loggers/BasicLogger.h" -#include "FLog/Loggers/LoggerMultiSinkFast.h" -#include "FLog/Loggers/LoggerMultiSinkSafe.h" - -#include "FLog/Sinks/FileSink.h" - -#include "FLog/LoggerImpl/XLogger.h" - -#include "FLog/LoggerFactory.h" diff --git a/src/StreamFormat/FLog/LoggerFactory.h b/src/StreamFormat/FLog/LoggerFactory.h deleted file mode 100644 index 5d155a41..00000000 --- a/src/StreamFormat/FLog/LoggerFactory.h +++ /dev/null @@ -1,13 +0,0 @@ -#pragma once - -#include "Loggers/BasicLogger.h" -#include "Loggers/LoggerMultiSinkFast.h" -#include "Loggers/LoggerMultiSinkSafe.h" - -// TODO: -namespace StreamFormat::FLog -{ - class LoggerFactory - { - }; -} diff --git a/src/StreamFormat/FLog/LoggerImpl/XLogger.cpp b/src/StreamFormat/FLog/LoggerImpl/XLogger.cpp deleted file mode 100644 index 835a4777..00000000 --- a/src/StreamFormat/FLog/LoggerImpl/XLogger.cpp +++ /dev/null @@ -1,14 +0,0 @@ -#include "XLogger.h" - -namespace StreamFormat::FLog -{ - template class Detail::XLogger>; - template class Detail::XLogger>; - template class Detail::XLogger>; -} - -namespace StreamFormat::FLog::Sinks -{ - template class BasicConsoleSink; - template class BasicFileSink; -} diff --git a/src/StreamFormat/FLog/LoggerImpl/XLogger.h b/src/StreamFormat/FLog/LoggerImpl/XLogger.h deleted file mode 100644 index 41ff5e1a..00000000 --- a/src/StreamFormat/FLog/LoggerImpl/XLogger.h +++ /dev/null @@ -1,220 +0,0 @@ -#pragma once - -#include "StreamFormat/FLog/Detail/Detail.h" -#include "StreamFormat/FLog/Loggers/BasicLogger.h" -#include "StreamFormat/FLog/Loggers/LoggerMultiSinkFast.h" -#include "StreamFormat/FLog/Loggers/LoggerMultiSinkSafe.h" -#include "StreamFormat/FLog/Sinks/FileSink.h" - -namespace StreamFormat::FLog -{ - struct LogSeverity - { - public: - enum class Value : int - { - Trace, - Debug, - Info, - Warn, - Error, - Fatal, - DefaultSeverity = Trace - }; - - public: - static constexpr Value Trace{Value::Trace}; - static constexpr Value Debug{Value::Debug}; - static constexpr Value Info{Value::Info}; - static constexpr Value Warn{Value::Warn}; - static constexpr Value Error{Value::Error}; - static constexpr Value Fatal{Value::Fatal}; - static constexpr Value DefaultSeverity = Trace; - - public: - class PatternOverride - { - public: - std::basic_string TracePattern = ""; - std::basic_string DebugPattern = ""; - std::basic_string InfoPattern = ""; - std::basic_string WarnPattern = ""; - std::basic_string ErrorPattern = ""; - std::basic_string FatalPattern = ""; - - std::basic_string_view GetPattern(const Value& severity) const - { - switch (severity) - { - case Value::Trace: - if (TracePattern.empty() == false) return TracePattern; - break; - case Value::Debug: - if (DebugPattern.empty() == false) return DebugPattern; - break; - case Value::Info: - if (InfoPattern.empty() == false) return InfoPattern; - break; - case Value::Warn: - if (WarnPattern.empty() == false) return WarnPattern; - break; - case Value::Error: - if (ErrorPattern.empty() == false) return ErrorPattern; - break; - case Value::Fatal: - if (FatalPattern.empty() == false) return FatalPattern; - break; - } - return std::basic_string_view{nullptr, 0}; - } - }; - }; -} - -namespace StreamFormat::FLog::Detail -{ - template - class XLogger : public Master - { - public: - template - XLogger(Args&&... args) - : Master(std::forward(args)...) - {} - - ~XLogger() override = default; - - public: - template - requires FMT::Detail::ConvertibleToBufferInfoView - [[nodiscard]] std::expected Log(Severity status, Format&& format, Args&&... args) - { - return Master::template Log(status, format, std::forward(args)...); - } - - template - [[nodiscard]] std::expected Log(Severity status, T&& t) - { - return Master::template Log(status, std::forward(t)); - } - - public: - /////---------- Logger Severity with array as format ----------///// - template - requires FMT::Detail::ConvertibleToBufferInfoView - inline std::expected Trace(Format&& format, Args&&... args) - { - return Log(LogSeverity::Trace, format, std::forward(args)...); - } - template - requires FMT::Detail::ConvertibleToBufferInfoView - inline std::expected Debug(Format&& format, Args&&... args) - { - return Log(LogSeverity::Debug, format, std::forward(args)...); - } - template - requires FMT::Detail::ConvertibleToBufferInfoView - inline std::expected Info(Format&& format, Args&&... args) - { - return Log(LogSeverity::Info, format, std::forward(args)...); - } - template - requires FMT::Detail::ConvertibleToBufferInfoView - inline std::expected Warn(Format&& format, Args&&... args) - { - return Log(LogSeverity::Warn, format, std::forward(args)...); - } - template - requires FMT::Detail::ConvertibleToBufferInfoView - inline std::expected Error(Format&& format, Args&&... args) - { - return Log(LogSeverity::Error, format, std::forward(args)...); - } - template - requires FMT::Detail::ConvertibleToBufferInfoView - inline std::expected Fatal(Format&& format, Args&&... args) - { - return Log(LogSeverity::Fatal, format, std::forward(args)...); - } - - /////---------- NO-FORMAT Logger Severity ----------///// - template - inline std::expected Trace(T&& t) - { - return Log(LogSeverity::Trace, std::forward(t)); - } - template - inline std::expected Debug(T&& t) - { - return Log(LogSeverity::Debug, std::forward(t)); - } - template - inline std::expected Info(T&& t) - { - return Log(LogSeverity::Info, std::forward(t)); - } - template - inline std::expected Warn(T&& t) - { - return Log(LogSeverity::Warn, std::forward(t)); - } - template - inline std::expected Error(T&& t) - { - return Log(LogSeverity::Error, std::forward(t)); - } - template - inline std::expected Fatal(T&& t) - { - return Log(LogSeverity::Fatal, std::forward(t)); - } - }; -} - -namespace StreamFormat::FMT -{ - template - struct FormatterType - { - [[nodiscard]] static std::expected Format(const StreamFormat::FLog::LogSeverity::Value t, FormatterExecutor& executor) - { - executor.Data.KeepNewStyle = true; - switch (t) - { - case StreamFormat::FLog::LogSeverity::Trace: - return FormatterType::Format(Detail::TextProperties::TextColor::BasicColorFG::BrightBlack, executor); - case StreamFormat::FLog::LogSeverity::Debug: - return FormatterType::Format(Detail::TextProperties::TextColor::BasicColorFG::Blue, executor); - case StreamFormat::FLog::LogSeverity::Info: - return FormatterType::Format(Detail::TextProperties::TextColor::BasicColorFG::Green, executor); - case StreamFormat::FLog::LogSeverity::Warn: - return FormatterType::Format(Detail::TextProperties::TextColor::BasicColorFG::Yellow, executor); - case StreamFormat::FLog::LogSeverity::Error: - return FormatterType::Format(Detail::TextProperties::TextColor::BasicColorFG::Red, executor); - case StreamFormat::FLog::LogSeverity::Fatal: - return FormatterType::Format(Detail::TextProperties::TextColor::BasicColorFG::BrightMagenta, executor); - } - return {}; - } - }; -} - -namespace StreamFormat::FLog -{ - using BasicLogger = Detail::XLogger>; - using LoggerMultiSinkFast = Detail::XLogger>; - using LoggerMultiSinkSafe = Detail::XLogger>; - - extern template class Detail::XLogger>; - extern template class Detail::XLogger>; - extern template class Detail::XLogger>; -} - -namespace StreamFormat::FLog::Sinks -{ - using ConsoleSink = BasicConsoleSink; - using FileSink = BasicFileSink; - - extern template class BasicConsoleSink; - extern template class BasicFileSink; -} diff --git a/src/StreamFormat/FMT.h b/src/StreamFormat/FMT.h deleted file mode 100644 index ba1ab432..00000000 --- a/src/StreamFormat/FMT.h +++ /dev/null @@ -1,5 +0,0 @@ -#pragma once - -#include "FMT/Context/FormatterExecutor/UtilityFunctions.h" - -#include "FMT/Serializers/FormatSTDLib.h" diff --git a/src/StreamFormat/FMT/Buffer/Utils/BufferUtils.h b/src/StreamFormat/FMT/Buffer/Utils/BufferUtils.h deleted file mode 100644 index 80c394c5..00000000 --- a/src/StreamFormat/FMT/Buffer/Utils/BufferUtils.h +++ /dev/null @@ -1,131 +0,0 @@ -#pragma once - -#include "StreamFormat/FMT/Buffer/BufferInfo.h" -#include "StreamFormat/FMT/Buffer/BufferOutManip.h" -#include "StreamFormat/FMT/Buffer/BufferTestManip.h" -#include "StreamFormat/FMT/Buffer/BufferWriteManip.h" -#include "StreamFormat/FMT/Buffer/BufferReadManip.h" - -#include "StreamFormat/FMT/Buffer/BufferOutManager/DynamicBufferOutManager.h" -#include "StreamFormat/FMT/Buffer/BufferOutManager/GivenBufferOutManager.h" -#include "StreamFormat/FMT/Buffer/BufferOutManager/StaticBufferOutManager.h" - -namespace StreamFormat::FMT::Detail -{ - template - class BufferUtilsManip - { - public: - constexpr inline BufferUtilsManip(BufferInfo& buffer) noexcept : Buffer(buffer) {} - public: - BufferInfo& Buffer; - - using TConstChar = std::remove_const_t; - - public: - template - [[nodiscard]] std::expected GetWordFromList(const std::basic_string_view (&data)[SIZE]) - { - for (std::size_t idx = 0; idx < SIZE; ++idx) - { - bool found = SF_TRY(BufferTestManip(Buffer).IsSameForward(data[idx])); - if (found) return idx; - } - return std::unexpected(FMTResult::Specifers_Invalid); - } - - // TODO: use static map ? - template - using DictPairs = std::pair, T>; - - template - [[nodiscard]] std::expected GetWordFromDictPairs(const DictPairs (&data)[SIZE]) - { - for (std::size_t idx = 0; idx < SIZE; ++idx) - { - bool found = SF_TRY(BufferTestManip(Buffer).IsSameForward(data[idx].first)); - if (found) - return data[idx].second; - } - return std::unexpected(FMTResult::Specifers_Invalid); - } - }; - - class BufferUtils - { - public: - template - [[nodiscard]] static std::expected ParseEscapedQuotedString(Detail::BufferInfo& buffer, Detail::BufferOutInfo& stringOut) - { - SF_TRY(Detail::BufferTestManip(buffer).SkipOneOf('"')); - while (Detail::BufferAccess(buffer).IsEndOfString() == false) - { - auto view = SF_TRY(Detail::BufferTestManip(buffer).ViewUntil('"', '\\')); - SF_TRY(Detail::BufferWriteManip(stringOut).FastWriteString(view)); - - if (Detail::BufferTestAccess(buffer).IsEqualTo('"')) - { break; } - - SF_TRY(Detail::BufferTestManip(buffer).SkipOneOf('\\')); - switch (buffer.Get()) - { - // TODO : Do all others escape char - case '"': - SF_TRY(Detail::BufferOutManip(stringOut).Pushback('"')); - break; - case 't': - SF_TRY(Detail::BufferOutManip(stringOut).Pushback('\t')); - break; - case 'r': - SF_TRY(Detail::BufferOutManip(stringOut).Pushback('\r')); - break; - case 'n': - SF_TRY(Detail::BufferOutManip(stringOut).Pushback('\n')); - break; - default: - break; - } - } - SF_TRY(Detail::BufferTestManip(buffer).SkipOneOf('"')); - - return {}; - } - - template - [[nodiscard]] static std::expected FormatEscapedQuotedString(Detail::BufferOutInfo& buffer, Detail::BufferInfo& stringIn) - { - SF_TRY(Detail::BufferOutManip(buffer).Pushback('"')); - while (Detail::BufferAccess(stringIn).IsEndOfString() == false) - { - auto view = SF_TRY(Detail::BufferTestManip(stringIn).ViewUntil('\\')); - SF_TRY(Detail::BufferWriteManip(buffer).FastWriteString(view)); - - if (Detail::BufferAccess(stringIn).IsEndOfString()) break; - - // TODO - SF_TRY(Detail::BufferTestManip(stringIn).SkipOneOf('\\')); - switch (stringIn.Get()) - { - // TODO : Do all others escape char - case '"': - SF_TRY(Detail::BufferOutManip(buffer).Pushback('"')); - break; - case 't': - SF_TRY(Detail::BufferOutManip(buffer).Pushback('\t')); - break; - case 'r': - SF_TRY(Detail::BufferOutManip(buffer).Pushback('\r')); - break; - case 'n': - SF_TRY(Detail::BufferOutManip(buffer).Pushback('\n')); - break; - default: - break; - } - } - SF_TRY(Detail::BufferOutManip(buffer).Pushback('"')); - - return {}; - } - }; -} diff --git a/src/StreamFormat/FMT/Context/BasicContext/ITextPropertiesExecutor.h b/src/StreamFormat/FMT/Context/BasicContext/ITextPropertiesExecutor.h deleted file mode 100644 index cdf0151e..00000000 --- a/src/StreamFormat/FMT/Context/BasicContext/ITextPropertiesExecutor.h +++ /dev/null @@ -1,48 +0,0 @@ -#pragma once - -#include "StreamFormat/FMT/Detail/Prelude.h" -#include "StreamFormat/FMT/TextProperties/TextProperties.h" - -namespace StreamFormat::FMT::Detail -{ - class ITextPropertiesExecutor - { - public: - virtual ~ITextPropertiesExecutor() = default; - - public: - virtual void LinkToExecutor(void* executor) = 0; - - public: - [[nodiscard]] virtual std::expected AllPropertiesReset() = 0; - - public: - [[nodiscard]] virtual std::expected ResetColor() = 0; - [[nodiscard]] virtual std::expected ExecuteColor(const TextProperties::TextColor::BasicColorFG& t) = 0; - [[nodiscard]] virtual std::expected ExecuteColor(const TextProperties::TextColor::BasicColorBG& t) = 0; - [[nodiscard]] virtual std::expected ExecuteColor(const TextProperties::TextColor::BasicColor& t) = 0; - [[nodiscard]] virtual std::expected ExecuteColor(const TextProperties::TextColor::Color24bFG& t) = 0; - [[nodiscard]] virtual std::expected ExecuteColor(const TextProperties::TextColor::Color24bBG& t) = 0; - [[nodiscard]] virtual std::expected ExecuteColor(const TextProperties::TextColor::Color24b& t) = 0; - [[nodiscard]] virtual std::expected ExecuteColor(const TextProperties::TextColor::ColorCubeFG& t) = 0; - [[nodiscard]] virtual std::expected ExecuteColor(const TextProperties::TextColor::ColorCubeBG& t) = 0; - [[nodiscard]] virtual std::expected ExecuteColor(const TextProperties::TextColor::ColorCube& t) = 0; - - public: - [[nodiscard]] virtual std::expected ResetFront() = 0; - [[nodiscard]] virtual std::expected ExecuteFront(const TextProperties::TextFront::FrontID& t) = 0; - - public: - [[nodiscard]] virtual std::expected ResetStyle() = 0; - [[nodiscard]] virtual std::expected ExecuteStyle(const TextProperties::TextStyle::Intensity& t) = 0; - [[nodiscard]] virtual std::expected ExecuteStyle(const TextProperties::TextStyle::Italic& t) = 0; - [[nodiscard]] virtual std::expected ExecuteStyle(const TextProperties::TextStyle::Underline& t) = 0; - [[nodiscard]] virtual std::expected ExecuteStyle(const TextProperties::TextStyle::UnderlineColor::Color& t) = 0; - [[nodiscard]] virtual std::expected ExecuteStyle(const TextProperties::TextStyle::UnderlineColor::ColorCube& t) = 0; - [[nodiscard]] virtual std::expected ExecuteStyle(const TextProperties::TextStyle::UnderlineColor::Color24b& t) = 0; - [[nodiscard]] virtual std::expected ExecuteStyle(const TextProperties::TextStyle::Blink& t) = 0; - [[nodiscard]] virtual std::expected ExecuteStyle(const TextProperties::TextStyle::Inverted& t) = 0; - [[nodiscard]] virtual std::expected ExecuteStyle(const TextProperties::TextStyle::Ideogram& t) = 0; - [[nodiscard]] virtual std::expected ExecuteStyle(const TextProperties::TextStyle::Script& t) = 0; - }; -} diff --git a/src/StreamFormat/FMT/Context/FormatterExecutor/FormatterTextPropertiesExecutor/FormatterTextPropertiesExecutor.h b/src/StreamFormat/FMT/Context/FormatterExecutor/FormatterTextPropertiesExecutor/FormatterTextPropertiesExecutor.h deleted file mode 100644 index 0a8b6fb3..00000000 --- a/src/StreamFormat/FMT/Context/FormatterExecutor/FormatterTextPropertiesExecutor/FormatterTextPropertiesExecutor.h +++ /dev/null @@ -1,66 +0,0 @@ -#pragma once - -#include "StreamFormat/FMT/Context/BasicContext/ITextPropertiesExecutor.h" -#include "StreamFormat/FMT/Buffer/FMTBufferOutManip.h" -#include "StreamFormat/FMT/Context/FormatterExecutor/BasicFormatterExecutor.h" - -namespace StreamFormat::FMT::Detail -{ - template - class IFormatterTextPropertiesExecutor : public ITextPropertiesExecutor - { - public: - ~IFormatterTextPropertiesExecutor() override = default; - - void LinkToExecutor(void* executor) override - { - Buffer = &reinterpret_cast*>(executor)->BufferOut; - } - - protected: - Detail::FMTBufferOutInfo* Buffer{nullptr}; - }; -} - -namespace StreamFormat::FMT::Detail -{ - template - class FormatterNOTextPropertiesExecutor final : public IFormatterTextPropertiesExecutor - { - public: - FormatterNOTextPropertiesExecutor() = default; - ~FormatterNOTextPropertiesExecutor() override = default; - - public: - [[nodiscard]] std::expected AllPropertiesReset() override {} - - public: - [[nodiscard]] std::expected ResetColor() override {} - [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::BasicColorFG&) override {} - [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::BasicColorBG&) override {} - [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::BasicColor&) override {} - [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::Color24bFG&) override {} - [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::Color24bBG&) override {} - [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::Color24b&) override {} - [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::ColorCubeFG&) override {} - [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::ColorCubeBG&) override {} - [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::ColorCube&) override {} - - public: - [[nodiscard]] std::expected ResetFront() override {} - [[nodiscard]] std::expected ExecuteFront(const Detail::TextProperties::TextFront::FrontID&) override {} - - public: - [[nodiscard]] std::expected ResetStyle() override {} - [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Intensity&) override {} - [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Italic&) override {} - [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Underline&) override {} - [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::UnderlineColor::Color&) override {} - [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::UnderlineColor::ColorCube&) override {} - [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::UnderlineColor::Color24b&) override {} - [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Blink&) override {} - [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Inverted&) override {} - [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Ideogram&) override {} - [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Script&) override {} - }; -} diff --git a/src/StreamFormat/FMT/Context/ParserExecutor/ParserTextPropertiesExecutor/ParserANSITextPropertiesExecutor.h b/src/StreamFormat/FMT/Context/ParserExecutor/ParserTextPropertiesExecutor/ParserANSITextPropertiesExecutor.h deleted file mode 100644 index 3f22e8f9..00000000 --- a/src/StreamFormat/FMT/Context/ParserExecutor/ParserTextPropertiesExecutor/ParserANSITextPropertiesExecutor.h +++ /dev/null @@ -1,144 +0,0 @@ -#pragma once - -#include "ParserTextPropertiesExecutor.h" - -namespace StreamFormat::FMT::Detail -{ - template - class ParserANSITextPropertiesExecutor : public IParserTextPropertiesExecutor - { - public: - ParserANSITextPropertiesExecutor() = default; - ~ParserANSITextPropertiesExecutor() override = default; - - using IParserTextPropertiesExecutor::Buffer; - - public: - [[nodiscard]] std::expected AllPropertiesReset() override - { - return std::unexpected(FMTResult::FunctionNotImpl); - /*BufferReadManip(Buffer).BasicReadType('\033', '[', 0, 'm');*/ - } - - public: - [[nodiscard]] std::expected ResetColor() override - { - return std::unexpected(FMTResult::FunctionNotImpl); - /*BufferReadManip(Buffer).BasicReadType('\033', '[', 39, ';', 49, 'm');*/ - } - [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::BasicColorFG&) override - { - return std::unexpected(FMTResult::FunctionNotImpl); - /*BufferReadManip(Buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ - } - [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::BasicColorBG&) override - { - return std::unexpected(FMTResult::FunctionNotImpl); - /*BufferReadManip(Buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ - } - [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::BasicColor&) override - { - return std::unexpected(FMTResult::FunctionNotImpl); - /*BufferReadManip(Buffer).BasicReadType('\033', '[', static_cast(t.Fg) , ';', static_cast(t.Bg), 'm');*/ - } - [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::Color24bFG&) override - { - return std::unexpected(FMTResult::FunctionNotImpl); - /*BufferReadManip(Buffer).BasicReadType("\033[38;2;", t.R, ';', t.G, ';', t.B, 'm');*/ - } - [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::Color24bBG&) override - { - return std::unexpected(FMTResult::FunctionNotImpl); - /*BufferReadManip(Buffer).BasicReadType("\033[48;2;", t.R, ';', t.G, ';', t.B, 'm');*/ - } - [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::Color24b&) override - { - return std::unexpected(FMTResult::FunctionNotImpl); - /*BufferReadManip(Buffer).BasicReadType("\033[38;2;", t.Fg.R, ';', t.Fg.G, ';', t.Fg.B, "; 48; 2;", t.Bg.R, ';', t.Bg.G, ';', t.Bg.B, 'm');*/ - } - [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::ColorCubeFG&) override - { - return std::unexpected(FMTResult::FunctionNotImpl); - /*BufferReadManip(Buffer).BasicReadType("\033[38;5;", t.GetColorRef(), 'm');*/ - } - [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::ColorCubeBG&) override - { - return std::unexpected(FMTResult::FunctionNotImpl); - /*BufferReadManip(Buffer).BasicReadType("\033[48;5;", t.GetColorRef(), 'm');*/ - } - [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::ColorCube&) override - { - return std::unexpected(FMTResult::FunctionNotImpl); - /*BufferReadManip(Buffer).BasicReadType("\033[48;5;", t.Fg.GetColorRef(), ";48;5;", t.Bg.GetColorRef(), 'm');*/ - } - - public: - [[nodiscard]] std::expected ResetFront() override - { - return std::unexpected(FMTResult::FunctionNotImpl); - /*BufferReadManip(Buffer).BasicReadType('\033', '[', Detail::TextProperties::TextFront::FrontID::DefaultFrontID, 'm');*/ - } - [[nodiscard]] std::expected ExecuteFront(const Detail::TextProperties::TextFront::FrontID&) override - { - return std::unexpected(FMTResult::FunctionNotImpl); - /*BufferReadManip(Buffer).BasicReadType('\033', '[', t.ID, 'm');*/ - } - - public: - [[nodiscard]] std::expected ResetStyle() override - { - return std::unexpected(FMTResult::FunctionNotImpl); - /*BufferReadManip(Buffer).BasicReadType('\033', '[', 0, 'm');*/ - } - [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Intensity&) override - { - return std::unexpected(FMTResult::FunctionNotImpl); - /*BufferReadManip(Buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ - } - [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Italic&) override - { - return std::unexpected(FMTResult::FunctionNotImpl); - /*BufferReadManip(Buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ - } - [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Underline&) override - { - return std::unexpected(FMTResult::FunctionNotImpl); - /*BufferReadManip(Buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ - } - [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::UnderlineColor::Color&) override - { - return std::unexpected(FMTResult::FunctionNotImpl); - /*BufferReadManip(Buffer).BasicReadType("\033[59m");*/ - } - [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::UnderlineColor::ColorCube&) override - { - return std::unexpected(FMTResult::FunctionNotImpl); - /*BufferReadManip(Buffer).BasicReadType("\033[58;5;", t.GetColorRef(), 'm');*/ - } - [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::UnderlineColor::Color24b&) override - { - return std::unexpected(FMTResult::FunctionNotImpl); - /*BufferReadManip(Buffer).BasicReadType("\033[58;2;", t.R, ';', t.G, ';', t.B, 'm');*/ - } - [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Blink&) override - { - return std::unexpected(FMTResult::FunctionNotImpl); - /*BufferReadManip(Buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ - } - [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Inverted&) override - { - return std::unexpected(FMTResult::FunctionNotImpl); - /*BufferReadManip(Buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ - } - [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Ideogram&) override - { - return std::unexpected(FMTResult::FunctionNotImpl); - /*BufferReadManip(Buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ - } - [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Script&) override - { - return std::unexpected(FMTResult::FunctionNotImpl); - /*BufferReadManip(Buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ - } - }; -} diff --git a/src/StreamFormat/FMT/Context/ParserExecutor/ParserTextPropertiesExecutor/ParserTextPropertiesExecutor.h b/src/StreamFormat/FMT/Context/ParserExecutor/ParserTextPropertiesExecutor/ParserTextPropertiesExecutor.h deleted file mode 100644 index 6f8e60b6..00000000 --- a/src/StreamFormat/FMT/Context/ParserExecutor/ParserTextPropertiesExecutor/ParserTextPropertiesExecutor.h +++ /dev/null @@ -1,69 +0,0 @@ -#pragma once - -#include "StreamFormat/FMT/Context/BasicContext/ITextPropertiesExecutor.h" -#include "StreamFormat/FMT/Detail/Prelude.h" -#include "StreamFormat/FMT/Context/ParserExecutor/BasicParserExecutor.h" - -namespace StreamFormat::FMT::Detail -{ - template - class IParserTextPropertiesExecutor : public ITextPropertiesExecutor - { - public: - IParserTextPropertiesExecutor() = default; - ~IParserTextPropertiesExecutor() override = default; - - void LinkToExecutor(void* executor) override - { - Buffer = &reinterpret_cast*>(executor)->BufferIn; - } - - protected: - BufferInfoView* Buffer{nullptr}; - }; -} - -namespace StreamFormat::FMT::Detail -{ - template - class ParserNOTextPropertiesExecutor : public IParserTextPropertiesExecutor - { - public: - ParserNOTextPropertiesExecutor() = default; - ~ParserNOTextPropertiesExecutor() override = default; - - using IParserTextPropertiesExecutor::Buffer; - - public: - [[nodiscard]] std::expected AllPropertiesReset() override { return {}; } - - public: - [[nodiscard]] std::expected ResetColor() override {} - [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::BasicColorFG&) override { return {}; } - [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::BasicColorBG&) override { return {}; } - [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::BasicColor&) override { return {}; } - [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::Color24bFG&) override { return {}; } - [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::Color24bBG&) override { return {}; } - [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::Color24b&) override { return {}; } - [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::ColorCubeFG&) override { return {}; } - [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::ColorCubeBG&) override { return {}; } - [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::ColorCube&) override { return {}; } - - public: - [[nodiscard]] std::expected ResetFront() override { return {}; } - [[nodiscard]] std::expected ExecuteFront(const Detail::TextProperties::TextFront::FrontID&) override { return {}; } - - public: - [[nodiscard]] std::expected ResetStyle() override { return {}; } - [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Intensity&) override { return {}; } - [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Italic&) override { return {}; } - [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Underline&) override { return {}; } - [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::UnderlineColor::Color&) override { return {}; } - [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::UnderlineColor::ColorCube&) override { return {}; } - [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::UnderlineColor::Color24b&) override { return {}; } - [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Blink&) override { return {}; } - [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Inverted&) override { return {}; } - [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Ideogram&) override { return {}; } - [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Script&) override { return {}; } - }; -} diff --git a/src/StreamFormat/FMT/Serializers/ParseChrono.h b/src/StreamFormat/FMT/Serializers/ParseChrono.h deleted file mode 100644 index ecc98536..00000000 --- a/src/StreamFormat/FMT/Serializers/ParseChrono.h +++ /dev/null @@ -1,14 +0,0 @@ -#pragma once - -#include -#include "StreamFormat/FMT/Context/ParserExecutor/BasicParserExecutor.h" - -namespace StreamFormat::FMT::Detail -{ - -} - -namespace StreamFormat::FMT -{ - -} diff --git a/src/StreamFormat/FMT/Serializers/ParseSTDLib.h b/src/StreamFormat/FMT/Serializers/ParseSTDLib.h deleted file mode 100644 index 3ffdf841..00000000 --- a/src/StreamFormat/FMT/Serializers/ParseSTDLib.h +++ /dev/null @@ -1,12 +0,0 @@ -#pragma once - -#include "StreamFormat/FMT/Context/ParserExecutor/BasicParserExecutor.h" - -#include -#include -#include - -namespace StreamFormat::FMT -{ - // TODO: -} diff --git a/src/StreamFormat/FMT/TextProperties/TextProperties.h b/src/StreamFormat/FMT/TextProperties/TextProperties.h deleted file mode 100644 index aa52ea13..00000000 --- a/src/StreamFormat/FMT/TextProperties/TextProperties.h +++ /dev/null @@ -1,20 +0,0 @@ -#pragma once - -#include "TextPropertiesColor.h" -#include "TextPropertiesFront.h" -#include "TextPropertiesStyle.h" - -namespace StreamFormat::FMT::Detail -{ - struct TextProperties::Properties - { - TextProperties::TextColor::Color Color; - TextProperties::TextStyle::Style Style; - TextProperties::TextFront::Front Front; - }; - - inline bool operator==(const TextProperties::Properties& lhs, const TextProperties::Properties& rhs) - { - return lhs.Color == rhs.Color && lhs.Style == rhs.Style && lhs.Front == rhs.Front; - } -} diff --git a/src/StreamFormat/Json/JsonObjects.cpp b/src/StreamFormat/Json/JsonObjects.cpp deleted file mode 100644 index 45a154f5..00000000 --- a/src/StreamFormat/Json/JsonObjects.cpp +++ /dev/null @@ -1,59 +0,0 @@ -#include "JsonObjects.h" -#include "Serializers/JsonObjectsSerializer.h" - -namespace StreamFormat::JSON -{ - void JsonStringObject::ParserExecute(Detail::JsonParser& parser) - { - JsonSerializer::Parse(*this, parser); - } - void JsonStringObject::FormatterExecute(Detail::JsonFormatter& formatter) const - { - JsonSerializer::Format(*this, formatter); - } - - void JsonNumberObject::ParserExecute(Detail::JsonParser& parser) - { - JsonSerializer::Parse(*this, parser); - } - void JsonNumberObject::FormatterExecute(Detail::JsonFormatter& formatter) const - { - JsonSerializer::Format(*this, formatter); - } - - void JsonBooleanObject::ParserExecute(Detail::JsonParser& parser) - { - JsonSerializer::Parse(*this, parser); - } - void JsonBooleanObject::FormatterExecute(Detail::JsonFormatter& formatter) const - { - JsonSerializer::Format(*this, formatter); - } - - void JsonStructObject::ParserExecute(Detail::JsonParser& parser) - { - JsonSerializer::Parse(*this, parser); - } - void JsonStructObject::FormatterExecute(Detail::JsonFormatter& formatter) const - { - JsonSerializer::Format(*this, formatter); - } - - void JsonArrayObject::ParserExecute(Detail::JsonParser& parser) - { - JsonSerializer::Parse(*this, parser); - } - void JsonArrayObject::FormatterExecute(Detail::JsonFormatter& formatter) const - { - JsonSerializer::Format(*this, formatter); - } - - void JsonNullObject::ParserExecute(Detail::JsonParser& parser) - { - JsonSerializer::Parse(*this, parser); - } - void JsonNullObject::FormatterExecute(Detail::JsonFormatter& formatter) const - { - JsonSerializer::Format(*this, formatter); - } -} diff --git a/src/StreamFormat/ProfilerManager/ProfilerJsonSerializers.h b/src/StreamFormat/ProfilerManager/ProfilerJsonSerializers.h deleted file mode 100644 index 8c432951..00000000 --- a/src/StreamFormat/ProfilerManager/ProfilerJsonSerializers.h +++ /dev/null @@ -1,83 +0,0 @@ -#pragma once - -#include "ProfilerFactory.h" -#include "StreamFormat/Json.h" - -namespace StreamFormat::JSON -{ - template <> - struct JsonSerializer - { - static inline void Format(const ProfilerManager::Profiler& t, Detail::JsonFormatter& formatter) - { - auto intermediate = formatter.GetStructIntermediate(); - intermediate.Format("displayTimeUnit", "us"); - intermediate.Format("traceEvents", t.Events); - } - - static inline void Parse(ProfilerManager::Profiler& t, Detail::JsonParser& parser) - { - auto intermediate = parser.GetStructIntermediate(); - intermediate.Parse("traceEvents", t.Events); - } - }; - - template <> - struct JsonSerializer - { - static inline void Format(const ProfilerManager::EventType& t, Detail::JsonFormatter& formatter) { formatter.Format(static_cast(t)); } - - static inline void Parse(ProfilerManager::EventType& t, Detail::JsonParser& parser) { parser.Parse(reinterpret_cast(t)); } - }; - - template <> - struct JsonSerializer - { - static inline void Format(const ProfilerManager::EventData& t, Detail::JsonFormatter& formatter) { t.ToJson(formatter); } - - static inline void Parse(ProfilerManager::EventData& t, Detail::JsonParser& parser) { t.FromJson(parser); } - }; - - template <> - struct JsonSerializer - { - static inline void Format(const ProfilerManager::EventInfo& t, Detail::JsonFormatter& formatter) - { - auto intermediate = formatter.GetStructIntermediate(); - intermediate.Format("name", t.Name); - intermediate.Format("cat", t.Category); - intermediate.Format("ph", t.Type); - intermediate.Format("pid", t.PID); - intermediate.Format("tid", t.TID); - intermediate.Format("ts", t.TimeOfEvent); - intermediate.Format("dur", t.Duration); - intermediate.Format("id", t.Id); - if (t.Data != nullptr) intermediate.Format("args", *t.Data); - } - - static inline void Parse(ProfilerManager::EventInfo& t, Detail::JsonParser& parser) - { - auto intermediate = parser.GetStructIntermediate(); - intermediate.Parse("name", t.Name); - intermediate.Parse("cat", t.Category); - intermediate.Parse("ph", t.Type); - intermediate.Parse("pid", t.PID); - intermediate.Parse("tid", t.TID); - intermediate.Parse("ts", t.TimeOfEvent); - intermediate.Parse("dur", t.Duration); - intermediate.Parse("id", t.Id); - intermediate.Parse("args", *t.Data); - } - }; - - template <> - struct JsonSerializer - { - static inline void Format(const ProfilerManager::Event& t, Detail::JsonFormatter& formatter) - { - return JsonSerializer::Format(t.Info, formatter); - } - - static inline void Parse(ProfilerManager::Event& t, Detail::JsonParser& parser) { return JsonSerializer::Parse(t.Info, parser); } - }; -} diff --git a/src/StreamFormat/ProfilerManager/ProfilerMacro.h b/src/StreamFormat/ProfilerManager/ProfilerMacro.h deleted file mode 100644 index ae84b803..00000000 --- a/src/StreamFormat/ProfilerManager/ProfilerMacro.h +++ /dev/null @@ -1,17 +0,0 @@ -#pragma once - -#ifdef STREAMFORMAT_PROFILING_ENABLE - -#define SFP_PROFILE_FUNCTION() StreamFormat::ProfilerManager::ScopeProfile profile##__LINE__(StreamFormat::ProfilerManager::Profiler::GetInstance(), __FUNCSIG__, "Function") -#define SFP_PROFILE_FUNCTION_FMT(...) \ - StreamFormat::ProfilerManager::ScopeProfile profile##__LINE__(StreamFormat::ProfilerManager::Profiler::GetInstance(), \ - StreamFormat::ProfilerManager::FMT::FormatString(__VA_ARGS__), "Function") -#define SFP_SAVE_DEFAULT_PROFILER() StreamFormat::ProfilerManager::ProfilerFactory::ToJson(StreamFormat::ProfilerManager::Profiler::GetInstance()) - -#else // STREAMFORMAT_PROFILING_ENABLE - -#define SFP_PROFILE_FUNCTION() -#define SFP_PROFILE_FUNCTION_FMT(...) -#define SFP_SAVE_DEFAULT_PROFILER() - -#endif // STREAMFORMAT_PROFILING_ENABLE diff --git a/src/StreamFormat/Core/Prelude.h b/src/stream/core/prelude.h similarity index 91% rename from src/StreamFormat/Core/Prelude.h rename to src/stream/core/prelude.h index 23f1ac95..28579737 100644 --- a/src/StreamFormat/Core/Prelude.h +++ b/src/stream/core/prelude.h @@ -35,7 +35,7 @@ #include #include -namespace StreamFormat::Detail +namespace stream::detail { template T forward_error(T t) @@ -47,7 +47,7 @@ namespace StreamFormat::Detail #define SF_TRY(exp) ({ \ auto __expected = exp; \ if (not __expected) [[unlikely]] \ - return std::unexpected(StreamFormat::Detail::forward_error(__expected.error())); \ + return std::unexpected(stream::detail::forward_error(__expected.error())); \ __expected.value(); \ }); diff --git a/src/StreamFormat/FLog/DefaultLogger.h b/src/stream/default_logger.h similarity index 58% rename from src/StreamFormat/FLog/DefaultLogger.h rename to src/stream/default_logger.h index 34281830..8e037ed5 100644 --- a/src/StreamFormat/FLog/DefaultLogger.h +++ b/src/stream/default_logger.h @@ -1,13 +1,13 @@ #pragma once -#include "LoggerImpl/XLogger.h" +#include "flog/frontends/xlogger.h" #ifndef STREAMFORMAT_BASE_LOGGER_NAME #undef STREAMFORMAT_BASE_LOGGER_NAME #define STREAMFORMAT_BASE_LOGGER_NAME "APP" #endif -namespace StreamFormat::FLog +namespace stream::flog { class DefaultLogger { @@ -26,12 +26,12 @@ namespace StreamFormat::FLog } #ifdef STREAMFORMAT_LOGGER_ENABLE - #define CORE_TRACE(...) StreamFormat::FLog::BasicLogger::Core().Trace(__VA_ARGS__) - #define CORE_DEBUG(...) StreamFormat::FLog::BasicLogger::Core().Debug(__VA_ARGS__) - #define CORE_INFO(...) StreamFormat::FLog::BasicLogger::Core().Info(__VA_ARGS__) - #define CORE_WARN(...) StreamFormat::FLog::BasicLogger::Core().Warn(__VA_ARGS__) - #define CORE_ERROR(...) StreamFormat::FLog::BasicLogger::Core().Error(__VA_ARGS__) - #define CORE_FATAL(...) StreamFormat::FLog::BasicLogger::Core().Fatal(__VA_ARGS__) + #define CORE_TRACE(...) stream::flog::BasicLogger::Core().trace(__VA_ARGS__) + #define CORE_DEBUG(...) stream::flog::BasicLogger::Core().debug(__VA_ARGS__) + #define CORE_INFO(...) stream::flog::BasicLogger::Core().info(__VA_ARGS__) + #define CORE_WARN(...) stream::flog::BasicLogger::Core().warn(__VA_ARGS__) + #define CORE_ERROR(...) stream::flog::BasicLogger::Core().error(__VA_ARGS__) + #define CORE_FATAL(...) stream::flog::BasicLogger::Core().fatal(__VA_ARGS__) #else #define CORE_TRACE(...) #define CORE_DEBUG(...) diff --git a/src/stream/flog.h b/src/stream/flog.h new file mode 100644 index 00000000..9ceb3c76 --- /dev/null +++ b/src/stream/flog.h @@ -0,0 +1,11 @@ +#pragma once + +#include "flog/backends/basic_logger.h" +#include "flog/backends/logger_multi_sink_fast.h" +#include "flog/backends/logger_multi_sink_safe.h" + +#include "flog/sinks/file_sink.h" + +#include "flog/LoggerImpl/XLogger.h" + +#include "flog/LoggerFactory.h" diff --git a/src/StreamFormat/FLog/Loggers/BasicLogger.h b/src/stream/flog/backends/basic_logger.h similarity index 83% rename from src/StreamFormat/FLog/Loggers/BasicLogger.h rename to src/stream/flog/backends/basic_logger.h index 0a6d6cb4..b7b6904a 100644 --- a/src/StreamFormat/FLog/Loggers/BasicLogger.h +++ b/src/stream/flog/backends/basic_logger.h @@ -1,12 +1,12 @@ #pragma once -#include "StreamFormat/FLog/Detail/Detail.h" -#include "StreamFormat/FMT/Serializers/FormatChrono.h" +#include "stream/flog/detail/detail.h" +#include "stream/fmt/serializers/FormatChrono.h" #include #include -namespace StreamFormat::FLog::Detail +namespace stream::flog::detail { template class BasicLoggerImpl @@ -66,8 +66,8 @@ namespace StreamFormat::FLog::Detail SeverityValueType m_Severity; std::ostream& m_Stream; std::string m_Pattern; - FMT::Detail::DynamicBufferOutManager preFormatBufferOutManager; - FMT::Detail::DynamicBufferOutManager fullFormatBufferOutManager; + fmt::detail::DynamicBufferOutManager preFormatBufferOutManager; + fmt::detail::DynamicBufferOutManager fullFormatBufferOutManager; std::chrono::time_point m_StartTime; @@ -75,18 +75,18 @@ namespace StreamFormat::FLog::Detail void NewLine() { m_Stream.write("\n", 1); } template - requires FMT::Detail::ConvertibleToBufferInfoView - [[nodiscard]] std::expected Log(const SeverityValueType& severity, Format&& format, Args&&... args) + requires fmt::detail::ConvertibleToBufferInfoView + [[nodiscard]] std::expected log(const SeverityValueType& severity, Format&& format, Args&&... args) { if (severity < m_Severity) return {}; std::chrono::nanoseconds logTime = std::chrono::high_resolution_clock::now() - m_StartTime; - SF_TRY(FMT::Detail::FormatInManager(preFormatBufferOutManager, false, FMT::Detail::BufferInfoView(m_Pattern), FORMAT_SV("time", logTime), FORMAT_SV("name", m_Name), - FORMAT_SV("data", FLog::AddIndentInFormat(format)))); + SF_TRY(fmt::detail::FormatInManager(preFormatBufferOutManager, false, fmt::detail::BufferInfoView(m_Pattern), FORMAT_SV("time", logTime), FORMAT_SV("name", m_Name), + FORMAT_SV("data", flog::AddIndentInFormat(format)))); - SF_TRY(FMT::Detail::FormatInManager(fullFormatBufferOutManager, true, preFormatBufferOutManager.GetLastGeneratedBufferInfoView(), std::forward(args)..., FORMAT_SV("color", severity))); + SF_TRY(fmt::detail::FormatInManager(fullFormatBufferOutManager, true, preFormatBufferOutManager.GetLastGeneratedBufferInfoView(), std::forward(args)..., FORMAT_SV("color", severity))); m_Stream.write(fullFormatBufferOutManager.GetBuffer(), static_cast(fullFormatBufferOutManager.GetLastGeneratedDataSize())); m_Stream.flush(); @@ -94,14 +94,14 @@ namespace StreamFormat::FLog::Detail } template - [[nodiscard]] std::expected Log(const SeverityValueType& severity, T&& t) + [[nodiscard]] std::expected log(const SeverityValueType& severity, T&& t) { if (severity < m_Severity) return {}; std::chrono::nanoseconds logTime = std::chrono::high_resolution_clock::now() - m_StartTime; - SF_TRY(FMT::Detail::FormatInManager(fullFormatBufferOutManager, true, FMT::Detail::BufferInfoView(m_Pattern), FORMAT_SV("data", t), FORMAT_SV("color", severity), + SF_TRY(fmt::detail::FormatInManager(fullFormatBufferOutManager, true, fmt::detail::BufferInfoView(m_Pattern), FORMAT_SV("data", t), FORMAT_SV("color", severity), FORMAT_SV("time", logTime), FORMAT_SV("name", m_Name))); m_Stream.write(fullFormatBufferOutManager.GetBuffer(), static_cast(fullFormatBufferOutManager.GetLastGeneratedDataSize())); m_Stream.flush(); diff --git a/src/StreamFormat/FLog/Loggers/LoggerMultiSinks.h b/src/stream/flog/backends/logger_multi_sink.h similarity index 92% rename from src/StreamFormat/FLog/Loggers/LoggerMultiSinks.h rename to src/stream/flog/backends/logger_multi_sink.h index 86dcea76..8c8b704b 100644 --- a/src/StreamFormat/FLog/Loggers/LoggerMultiSinks.h +++ b/src/stream/flog/backends/logger_multi_sink.h @@ -1,9 +1,9 @@ #pragma once -#include "StreamFormat/FLog/Detail/Detail.h" -#include "StreamFormat/FLog/Sinks/LoggerSink.h" +#include "stream/flog/detail/detail.h" +#include "stream/flog/sinks/LoggerSink.h" -namespace StreamFormat::FLog::Detail +namespace stream::flog::detail { template class BasicLoggerMultiSinkImpl diff --git a/src/StreamFormat/FLog/Loggers/LoggerMultiSinkFast.h b/src/stream/flog/backends/logger_multi_sink_fast.h similarity index 70% rename from src/StreamFormat/FLog/Loggers/LoggerMultiSinkFast.h rename to src/stream/flog/backends/logger_multi_sink_fast.h index a91eaf5e..b2e4930d 100644 --- a/src/StreamFormat/FLog/Loggers/LoggerMultiSinkFast.h +++ b/src/stream/flog/backends/logger_multi_sink_fast.h @@ -2,7 +2,7 @@ #include "LoggerMultiSinks.h" -namespace StreamFormat::FLog::Detail +namespace stream::flog::detail { template class BasicLoggerMultiSinkFastImpl : public BasicLoggerMultiSinkImpl @@ -40,31 +40,31 @@ namespace StreamFormat::FLog::Detail public: template - requires FMT::Detail::ConvertibleToBufferInfoView - [[nodiscard]] std::expected Log(const SeverityValueType& severity, const Format& format, Args&&... args) + requires fmt::detail::ConvertibleToBufferInfoView + [[nodiscard]] std::expected log(const SeverityValueType& severity, const Format& format, Args&&... args) { std::chrono::nanoseconds logTime = std::chrono::high_resolution_clock::now() - m_StartTime; - FMT::Detail::DynamicBufferOutManager manager(256); - auto formatBuffer = SF_TRY(FMT::Detail::FormatInManager(manager, false, format, std::forward(args)...)); + fmt::detail::DynamicBufferOutManager manager(256); + auto formatBuffer = SF_TRY(fmt::detail::FormatInManager(manager, false, format, std::forward(args)...)); for (auto& sink : m_Sinks) if (sink->NeedToLog(severity)) - { SF_TRY(sink->FormatAndWriteToSink(sink->GetPattern(severity), logTime, m_Name, static_cast>(*formatBuffer))); } + { SF_TRY(sink->FormatAndWriteToSink(sink->get_pattern(severity), logTime, m_Name, static_cast>(*formatBuffer))); } Await(severity); return {}; } template - [[nodiscard]] std::expected Log(const SeverityValueType& severity, T&& t) + [[nodiscard]] std::expected log(const SeverityValueType& severity, T&& t) { std::chrono::nanoseconds logTime = std::chrono::high_resolution_clock::now() - m_StartTime; - FMT::Detail::DynamicBufferOutManager manager(256); - auto formatBuffer = SF_TRY(FMT::Detail::FormatInManager(manager, false, std::forward(t))); + fmt::detail::DynamicBufferOutManager manager(256); + auto formatBuffer = SF_TRY(fmt::detail::FormatInManager(manager, false, std::forward(t))); for (auto& sink : m_Sinks) if (sink->NeedToLog(severity)) - { SF_TRY(sink->FormatAndWriteToSink(sink->GetPattern(severity), logTime, m_Name, static_cast>(*formatBuffer))); } + { SF_TRY(sink->FormatAndWriteToSink(sink->get_pattern(severity), logTime, m_Name, static_cast>(*formatBuffer))); } Await(severity); diff --git a/src/StreamFormat/FLog/Loggers/LoggerMultiSinkSafe.h b/src/stream/flog/backends/logger_multi_sink_safe.h similarity index 77% rename from src/StreamFormat/FLog/Loggers/LoggerMultiSinkSafe.h rename to src/stream/flog/backends/logger_multi_sink_safe.h index 984bfec0..2ef2c3dd 100644 --- a/src/StreamFormat/FLog/Loggers/LoggerMultiSinkSafe.h +++ b/src/stream/flog/backends/logger_multi_sink_safe.h @@ -2,7 +2,7 @@ #include "LoggerMultiSinks.h" -namespace StreamFormat::FLog::Detail +namespace stream::flog::detail { template class BasicLoggerMultiSinkSafeImpl : public BasicLoggerMultiSinkImpl @@ -40,8 +40,8 @@ namespace StreamFormat::FLog::Detail public: template - requires FMT::Detail::ConvertibleToBufferInfoView - [[nodiscard]] std::expected Log(const SeverityValueType& severity, const Format& format, Args&&... args) + requires fmt::detail::ConvertibleToBufferInfoView + [[nodiscard]] std::expected log(const SeverityValueType& severity, const Format& format, Args&&... args) { std::chrono::nanoseconds logTime = std::chrono::high_resolution_clock::now() - m_StartTime; @@ -50,12 +50,12 @@ namespace StreamFormat::FLog::Detail { if (sink->NeedToLog(severity)) { - FMT::Detail::DynamicBufferOutManager managerPattern(256); - FMT::Detail::DynamicBufferOutManager managerFormat(256); + fmt::detail::DynamicBufferOutManager managerPattern(256); + fmt::detail::DynamicBufferOutManager managerFormat(256); auto formatPatternStr = - SF_TRY(FMT::Detail::FormatInManager(managerPattern, false, std::string_view(sink->GetPattern(severity)), FORMAT_SV("time", logTime), - FORMAT_SV("name", FuturConcateNameAndSinkName(m_Name)), FORMAT_SV("data", FLog::AddIndentInFormat(format)))); - auto formatFormatStr = SF_TRY(FMT::Detail::FormatInManager(managerFormat, false, static_cast(*formatPatternStr), std::forward(args)..., + SF_TRY(fmt::detail::FormatInManager(managerPattern, false, std::string_view(sink->get_pattern(severity)), FORMAT_SV("time", logTime), + FORMAT_SV("name", FuturConcateNameAndSinkName(m_Name)), FORMAT_SV("data", flog::AddIndentInFormat(format)))); + auto formatFormatStr = SF_TRY(fmt::detail::FormatInManager(managerFormat, false, static_cast(*formatPatternStr), std::forward(args)..., FORMAT_SV("sink", sink->GetName()), FORMAT_SV("color", severity))); SF_TRY(sink->WriteToSink(static_cast>(*formatFormatStr))); } @@ -66,7 +66,7 @@ namespace StreamFormat::FLog::Detail } template - [[nodiscard]] std::expected Log(const SeverityValueType& severity, T&& t) + [[nodiscard]] std::expected log(const SeverityValueType& severity, T&& t) { std::chrono::nanoseconds logTime = std::chrono::high_resolution_clock::now() - m_StartTime; @@ -74,8 +74,8 @@ namespace StreamFormat::FLog::Detail { if (sink->NeedToLog(severity)) { - FMT::Detail::DynamicBufferOutManager manager(256); - auto formatBuffer = SF_TRY(FMT::Detail::FormatInManager(manager, false, std::string_view(sink->GetPattern(severity)), FORMAT_SV("time", logTime), + fmt::detail::DynamicBufferOutManager manager(256); + auto formatBuffer = SF_TRY(fmt::detail::FormatInManager(manager, false, std::string_view(sink->get_pattern(severity)), FORMAT_SV("time", logTime), FORMAT_SV("name", ConcateNameAndSinkName(m_Name, sink->GetName())), FORMAT_SV("data", t))); SF_TRY(sink->WriteToSink(static_cast>(*formatBuffer))); } diff --git a/src/StreamFormat/FLog/Detail/Detail.h b/src/stream/flog/detail/detail.h similarity index 54% rename from src/StreamFormat/FLog/Detail/Detail.h rename to src/stream/flog/detail/detail.h index 041d05df..5b3d98e1 100644 --- a/src/StreamFormat/FLog/Detail/Detail.h +++ b/src/stream/flog/detail/detail.h @@ -1,17 +1,17 @@ #pragma once -#include "StreamFormat/FMT.h" +#include "stream/fmt.h" -#include "StreamFormat/FMT/Buffer/BufferManip.h" -#include "StreamFormat/FMT/Buffer/BufferWriteManip.h" +#include "stream/fmt/buffer/buffer_manip.h" +#include "stream/fmt/buffer/buffer_write_manip.h" -namespace StreamFormat::FLog +namespace stream::flog { template struct AddIndentInFormat { AddIndentInFormat(const FormatStr& format) - : Format(format) + : format(format) {} const FormatStr& Format; }; @@ -37,31 +37,31 @@ namespace StreamFormat::FLog }; } -namespace StreamFormat::FMT +namespace stream::fmt { template - struct FormatterType, FormatterExecutor> + struct FormatterType, FormatterExecutor> { - [[nodiscard]] static std::expected Format(const StreamFormat::FLog::AddIndentInFormat& format, FormatterExecutor& executor) + [[nodiscard]] static std::expected format(const stream::flog::AddIndentInFormat& format, FormatterExecutor& executor) { - SF_TRY(Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("{K:indent}")); + SF_TRY(detail::BufferWriteManip(executor.buffer_out).FastWriteStringLitteral("{K:indent}")); return executor.WriteType(format.Format); } }; template - struct FormatterType, FormatterExecutor> + struct FormatterType, FormatterExecutor> { - [[nodiscard]] static std::expected Format(const StreamFormat::FLog::ConcateNameAndSinkName& names, FormatterExecutor& executor) + [[nodiscard]] static std::expected format(const stream::flog::ConcateNameAndSinkName& names, FormatterExecutor& executor) { return executor.Run(names.LoggerName, FORMAT_SV("sink", names.SinkName)); } }; template - struct FormatterType, FormatterExecutor> + struct FormatterType, FormatterExecutor> { - [[nodiscard]] static std::expected Format(const StreamFormat::FLog::FuturConcateNameAndSinkName& names, FormatterExecutor& executor) + [[nodiscard]] static std::expected format(const stream::flog::FuturConcateNameAndSinkName& names, FormatterExecutor& executor) { return executor.Run(names.LoggerName, "sink"); } diff --git a/src/stream/flog/frontends/xlogger.cpp b/src/stream/flog/frontends/xlogger.cpp new file mode 100644 index 00000000..6e098267 --- /dev/null +++ b/src/stream/flog/frontends/xlogger.cpp @@ -0,0 +1,14 @@ +#include "XLogger.h" + +namespace stream::flog +{ + template class detail::XLogger>; + template class detail::XLogger>; + template class detail::XLogger>; +} + +namespace stream::flog::Sinks +{ + template class BasicConsoleSink; + template class BasicFileSink; +} diff --git a/src/stream/flog/frontends/xlogger.h b/src/stream/flog/frontends/xlogger.h new file mode 100644 index 00000000..50c11d27 --- /dev/null +++ b/src/stream/flog/frontends/xlogger.h @@ -0,0 +1,220 @@ +#pragma once + +#include "stream/flog/detail/detail.h" +#include "stream/flog/backends/basic_logger.h" +#include "stream/flog/backends/logger_multi_sink_fast.h" +#include "stream/flog/backends/logger_multi_sink_safe.h" +#include "stream/flog/sinks/file_sink.h" + +namespace stream::flog +{ + struct LogSeverity + { + public: + enum class Value : int + { + trace, + debug, + Info, + Warn, + Error, + Fatal, + DefaultSeverity = trace + }; + + public: + static constexpr Value trace{Value::Trace}; + static constexpr Value debug{Value::Debug}; + static constexpr Value Info{Value::Info}; + static constexpr Value Warn{Value::Warn}; + static constexpr Value Error{Value::Error}; + static constexpr Value Fatal{Value::Fatal}; + static constexpr Value DefaultSeverity = trace; + + public: + class PatternOverride + { + public: + std::basic_string trace_pattern = ""; + std::basic_string debug_pattern = ""; + std::basic_string info_pattern = ""; + std::basic_string warn_pattern = ""; + std::basic_string error_pattern = ""; + std::basic_string fatal_pattern = ""; + + std::basic_string_view get_pattern(const Value& severity) const + { + switch (severity) + { + case Value::Trace: + if (trace_pattern.empty() == false) return trace_pattern; + break; + case Value::Debug: + if (debug_pattern.empty() == false) return debug_pattern; + break; + case Value::Info: + if (info_pattern.empty() == false) return info_pattern; + break; + case Value::Warn: + if (warn_pattern.empty() == false) return warn_pattern; + break; + case Value::Error: + if (error_pattern.empty() == false) return error_pattern; + break; + case Value::Fatal: + if (fatal_pattern.empty() == false) return fatal_pattern; + break; + } + return std::basic_string_view{nullptr, 0}; + } + }; + }; +} + +namespace stream::flog::detail +{ + template + class XLogger : public Master + { + public: + template + XLogger(Args&&... args) + : Master(std::forward(args)...) + {} + + ~XLogger() override = default; + + public: + template + requires fmt::detail::ConvertibleToBufferInfoView + [[nodiscard]] std::expected log(Severity status, Format&& format, Args&&... args) + { + return Master::template log(status, format, std::forward(args)...); + } + + template + [[nodiscard]] std::expected log(Severity status, T&& t) + { + return Master::template log(status, std::forward(t)); + } + + public: + /////---------- Logger Severity with array as format ----------///// + template + requires fmt::detail::ConvertibleToBufferInfoView + inline std::expected trace(Format&& format, Args&&... args) + { + return log(LogSeverity::Trace, format, std::forward(args)...); + } + template + requires fmt::detail::ConvertibleToBufferInfoView + inline std::expected debug(Format&& format, Args&&... args) + { + return log(LogSeverity::Debug, format, std::forward(args)...); + } + template + requires fmt::detail::ConvertibleToBufferInfoView + inline std::expected info(Format&& format, Args&&... args) + { + return log(LogSeverity::Info, format, std::forward(args)...); + } + template + requires fmt::detail::ConvertibleToBufferInfoView + inline std::expected warn(Format&& format, Args&&... args) + { + return log(LogSeverity::Warn, format, std::forward(args)...); + } + template + requires fmt::detail::ConvertibleToBufferInfoView + inline std::expected error(Format&& format, Args&&... args) + { + return log(LogSeverity::Error, format, std::forward(args)...); + } + template + requires fmt::detail::ConvertibleToBufferInfoView + inline std::expected fatal(Format&& format, Args&&... args) + { + return log(LogSeverity::Fatal, format, std::forward(args)...); + } + + /////---------- NO-FORMAT Logger Severity ----------///// + template + inline std::expected trace(T&& t) + { + return log(LogSeverity::Trace, std::forward(t)); + } + template + inline std::expected debug(T&& t) + { + return log(LogSeverity::Debug, std::forward(t)); + } + template + inline std::expected info(T&& t) + { + return log(LogSeverity::Info, std::forward(t)); + } + template + inline std::expected warn(T&& t) + { + return log(LogSeverity::Warn, std::forward(t)); + } + template + inline std::expected error(T&& t) + { + return log(LogSeverity::Error, std::forward(t)); + } + template + inline std::expected fatal(T&& t) + { + return log(LogSeverity::Fatal, std::forward(t)); + } + }; +} + +namespace stream::fmt +{ + template + struct FormatterType + { + [[nodiscard]] static std::expected format(const stream::flog::LogSeverity::Value t, FormatterExecutor& executor) + { + executor.Data.KeepNewStyle = true; + switch (t) + { + case stream::flog::LogSeverity::Trace: + return FormatterType::format(detail::TextProperties::TextColor::BasicColorFG::BrightBlack, executor); + case stream::flog::LogSeverity::Debug: + return FormatterType::format(detail::TextProperties::TextColor::BasicColorFG::Blue, executor); + case stream::flog::LogSeverity::Info: + return FormatterType::format(detail::TextProperties::TextColor::BasicColorFG::Green, executor); + case stream::flog::LogSeverity::Warn: + return FormatterType::format(detail::TextProperties::TextColor::BasicColorFG::Yellow, executor); + case stream::flog::LogSeverity::Error: + return FormatterType::format(detail::TextProperties::TextColor::BasicColorFG::Red, executor); + case stream::flog::LogSeverity::Fatal: + return FormatterType::format(detail::TextProperties::TextColor::BasicColorFG::BrightMagenta, executor); + } + return {}; + } + }; +} + +namespace stream::flog +{ + using BasicLogger = detail::XLogger>; + using LoggerMultiSinkFast = detail::XLogger>; + using LoggerMultiSinkSafe = detail::XLogger>; + + extern template class detail::XLogger>; + extern template class detail::XLogger>; + extern template class detail::XLogger>; +} + +namespace stream::flog::Sinks +{ + using ConsoleSink = BasicConsoleSink; + using FileSink = BasicFileSink; + + extern template class BasicConsoleSink; + extern template class BasicFileSink; +} diff --git a/src/stream/flog/logger_factory.h b/src/stream/flog/logger_factory.h new file mode 100644 index 00000000..6fc7ed9f --- /dev/null +++ b/src/stream/flog/logger_factory.h @@ -0,0 +1,13 @@ +#pragma once + +#include "backends/basic_logger.h" +#include "backends/logger_multi_sink_fast.h" +#include "backends/logger_multi_sink_safe.h" + +// TODO: +namespace stream::flog +{ + class LoggerFactory + { + }; +} diff --git a/src/StreamFormat/FLog/Sinks/FileSink.h b/src/stream/flog/sinks/file_sink.h similarity index 83% rename from src/StreamFormat/FLog/Sinks/FileSink.h rename to src/stream/flog/sinks/file_sink.h index d9e76830..667285ef 100644 --- a/src/StreamFormat/FLog/Sinks/FileSink.h +++ b/src/stream/flog/sinks/file_sink.h @@ -6,13 +6,13 @@ #include #include -namespace StreamFormat::FLog::Sinks +namespace stream::flog::Sinks { template - class BasicConsoleSink : public Detail::BasicLoggerSink + class BasicConsoleSink : public detail::BasicLoggerSink { public: - using Base = Detail::BasicLoggerSink; + using Base = detail::BasicLoggerSink; using typename Base::PatternType; using typename Base::NameType; using typename Base::BufferType; @@ -23,7 +23,7 @@ namespace StreamFormat::FLog::Sinks , m_Stream(stream) {} - BasicConsoleSink(std::basic_ostream& stream, NameType&& name, Detail::AsyncSink isAsync) + BasicConsoleSink(std::basic_ostream& stream, NameType&& name, detail::AsyncSink isAsync) : Base(std::forward(name), isAsync) , m_Stream(stream) {} @@ -46,16 +46,16 @@ namespace StreamFormat::FLog::Sinks }; template - class BasicFileSink : public Detail::BasicLoggerSink + class BasicFileSink : public detail::BasicLoggerSink { public: - using Base = Detail::BasicLoggerSink; + using Base = detail::BasicLoggerSink; using typename Base::PatternType; using typename Base::NameType; using typename Base::BufferType; public: - BasicFileSink(const std::filesystem::path& filePath, NameType&& name, Detail::AsyncSink isAsync) + BasicFileSink(const std::filesystem::path& filePath, NameType&& name, detail::AsyncSink isAsync) : Base(std::forward(name), isAsync) , m_Stream(filePath, std::ios::out) {} diff --git a/src/StreamFormat/FLog/Sinks/LoggerSink.h b/src/stream/flog/sinks/logger_sink.h similarity index 88% rename from src/StreamFormat/FLog/Sinks/LoggerSink.h rename to src/stream/flog/sinks/logger_sink.h index 9442e9e7..34d1bda5 100644 --- a/src/StreamFormat/FLog/Sinks/LoggerSink.h +++ b/src/stream/flog/sinks/logger_sink.h @@ -1,10 +1,10 @@ #pragma once -#include "StreamFormat/FLog/Detail/Detail.h" +#include "stream/flog/detail/detail.h" #include -namespace StreamFormat::FLog::Detail +namespace stream::flog::detail { enum class AsyncSink { @@ -55,9 +55,9 @@ namespace StreamFormat::FLog::Detail } public: - PatternTransfertType GetPattern(const typename Severity::Value& severity) const + PatternTransfertType get_pattern(const typename Severity::Value& severity) const { - PatternTransfertType customPattern = SeverityPatternOverride.GetPattern(severity); + PatternTransfertType customPattern = SeverityPatternOverride.get_pattern(severity); if (customPattern.data() == nullptr || customPattern.size() == 0) return Pattern; return customPattern; } @@ -86,24 +86,24 @@ namespace StreamFormat::FLog::Detail if (IsAsync == AsyncSink::Async) return m_AsyncWaiter.get(); } - [[nodiscard]] std::expected FormatAndWriteToSinkSync(PatternTransfertType pattern, const std::chrono::nanoseconds& logTime, const NameType& loggerName, const BufferType& formatBuffer) + [[nodiscard]] std::expected FormatAndWriteToSinkSync(PatternTransfertType pattern, const std::chrono::nanoseconds& logTime, const NameType& loggerName, const BufferType& formatBuffer) { - FMT::Detail::DynamicBufferOutManager manager(256); - auto formatPatternStr = SF_TRY(FMT::Detail::FormatInManager(manager, false, pattern, FORMAT_SV("time", logTime), FORMAT_SV("name", ConcateNameAndSinkName(loggerName, Name)), + fmt::detail::DynamicBufferOutManager manager(256); + auto formatPatternStr = SF_TRY(fmt::detail::FormatInManager(manager, false, pattern, FORMAT_SV("time", logTime), FORMAT_SV("name", ConcateNameAndSinkName(loggerName, Name)), FORMAT_SV("data", formatBuffer))); BufferType buffer(*formatPatternStr); WriteToSinkSync(buffer); return {}; } - [[nodiscard]] std::expected FormatAndWriteToSinkAsync(PatternTransfertType pattern, const std::chrono::nanoseconds& logTime, const NameType& loggerName, const BufferType& formatBuffer) + [[nodiscard]] std::expected FormatAndWriteToSinkAsync(PatternTransfertType pattern, const std::chrono::nanoseconds& logTime, const NameType& loggerName, const BufferType& formatBuffer) { // TODO m_AsyncWaiter = std::async(std::launch::async, &BasicLoggerSink::FormatAndWriteToSinkSync, this, pattern, logTime, loggerName, formatBuffer); return {}; } - [[nodiscard]] std::expected FormatAndWriteToSink(PatternTransfertType pattern, const std::chrono::nanoseconds& logTime, const NameType& loggerName, const BufferType& formatBuffer) + [[nodiscard]] std::expected FormatAndWriteToSink(PatternTransfertType pattern, const std::chrono::nanoseconds& logTime, const NameType& loggerName, const BufferType& formatBuffer) { if (IsAsync == AsyncSink::Sync) return FormatAndWriteToSinkSync(pattern, logTime, loggerName, formatBuffer); diff --git a/src/stream/fmt.h b/src/stream/fmt.h new file mode 100644 index 00000000..efdacdf9 --- /dev/null +++ b/src/stream/fmt.h @@ -0,0 +1,5 @@ +#pragma once + +#include "fmt/context/formatter_executor/utility_functions.h" + +#include "fmt/serializers/format_stdlib.h" diff --git a/src/StreamFormat/FMT/Buffer/BufferInfo.h b/src/stream/fmt/buffer/buffer_info.h similarity index 91% rename from src/StreamFormat/FMT/Buffer/BufferInfo.h rename to src/stream/fmt/buffer/buffer_info.h index 0e596a78..9aca210a 100644 --- a/src/StreamFormat/FMT/Buffer/BufferInfo.h +++ b/src/stream/fmt/buffer/buffer_info.h @@ -1,8 +1,8 @@ #pragma once -#include "StreamFormat/FMT/Detail/Prelude.h" +#include "stream/fmt/detail/prelude.h" -namespace StreamFormat::FMT::Detail +namespace stream::fmt::detail { template class BufferInfo @@ -17,7 +17,7 @@ namespace StreamFormat::FMT::Detail public: constexpr inline TChar Get() const { return *CurrentPos; } - template typename TManip> constexpr inline TManip Manip() { return TManip(Buffer); } + template typename TManip> constexpr inline TManip Manip() { return TManip(buffer); } public: BufferInfo() noexcept @@ -68,7 +68,7 @@ namespace StreamFormat::FMT::Detail {} public: - operator BufferInfo() const { return BufferInfo {.Buffer = Buffer, .CurrentPos = CurrentPos, .BufferEnd = BufferEnd}; } + operator BufferInfo() const { return BufferInfo {.buffer = Buffer, .CurrentPos = CurrentPos, .BufferEnd = BufferEnd}; } }; template diff --git a/src/StreamFormat/FMT/Buffer/BufferManip.h b/src/stream/fmt/buffer/buffer_manip.h similarity index 85% rename from src/StreamFormat/FMT/Buffer/BufferManip.h rename to src/stream/fmt/buffer/buffer_manip.h index 9c390178..37fa8873 100644 --- a/src/StreamFormat/FMT/Buffer/BufferManip.h +++ b/src/stream/fmt/buffer/buffer_manip.h @@ -1,8 +1,8 @@ #pragma once -#include "BufferInfo.h" +#include "buffer_info.h" -namespace StreamFormat::FMT::Detail +namespace stream::fmt::detail { template class BufferAccess @@ -13,29 +13,29 @@ namespace StreamFormat::FMT::Detail const BufferInfo& Buffer; public: - constexpr inline std::size_t GetBufferTotalSize() const noexcept { return static_cast(Buffer.BufferEnd - Buffer.Buffer); } - constexpr inline std::size_t GetBufferCurrentSize() const noexcept { return static_cast(Buffer.CurrentPos - Buffer.Buffer); } + constexpr inline std::size_t GetBufferTotalSize() const noexcept { return static_cast(Buffer.BufferEnd - Buffer.buffer); } + constexpr inline std::size_t GetBufferCurrentSize() const noexcept { return static_cast(Buffer.CurrentPos - Buffer.buffer); } constexpr inline std::size_t GetBufferRemainingSize() const noexcept { return static_cast(Buffer.BufferEnd - Buffer.CurrentPos); } public: constexpr inline bool CanMoveForward(const std::size_t count = 1) const noexcept { return Buffer.CurrentPos + count <= Buffer.BufferEnd; } - constexpr inline bool CanMoveBackward(const std::size_t count = 1) const noexcept { return Buffer.CurrentPos - count >= Buffer.Buffer; } + constexpr inline bool CanMoveBackward(const std::size_t count = 1) const noexcept { return Buffer.CurrentPos - count >= Buffer.buffer; } - constexpr inline bool IsOutOfBound() const noexcept { return Buffer.CurrentPos < Buffer.Buffer || Buffer.CurrentPos >= Buffer.BufferEnd; } + constexpr inline bool IsOutOfBound() const noexcept { return Buffer.CurrentPos < Buffer.buffer || Buffer.CurrentPos >= Buffer.BufferEnd; } constexpr inline bool IsEmpty() const noexcept { return Buffer.CurrentPos >= Buffer.BufferEnd; } constexpr inline bool IsEndOfString() const noexcept { return IsEmpty() || Buffer.Get() == 0; } [[nodiscard]] constexpr inline std::expected, FMTResult> GetNext(const std::size_t count = 1) const { - if (BufferAccess(Buffer).CanMoveForward(count) == false) + if (BufferAccess(buffer).CanMoveForward(count) == false) return std::unexpected(FMTResult::Buffer_OutOfBoundAccess); - return BufferManip(Buffer).GetNextForce(count); + return BufferManip(buffer).GetNextForce(count); } [[nodiscard]] constexpr inline std::expected, FMTResult> GetPrev(const std::size_t count = 1) const { - if (BufferAccess(Buffer).CanMoveBackward(count) == false) + if (BufferAccess(buffer).CanMoveBackward(count) == false) return std::unexpected(FMTResult::Buffer_OutOfBoundAccess); - return BufferManip(Buffer).GetPrevForce(count); + return BufferManip(buffer).GetPrevForce(count); } constexpr inline TChar GetNextForce(const std::size_t count = 1) const noexcept { return *(Buffer.CurrentPos + count); } @@ -53,19 +53,19 @@ namespace StreamFormat::FMT::Detail public: constexpr inline void Set(TChar* const buffer, const std::size_t size) noexcept { - Buffer.Buffer = buffer; + Buffer.buffer = buffer; Buffer.CurrentPos = buffer; Buffer.BufferEnd = buffer + size; } constexpr inline void Reload(BufferInfo& buffer) noexcept { - Buffer.Buffer = buffer.Buffer; + Buffer.buffer = buffer.buffer; Buffer.CurrentPos = buffer.CurrentPos; Buffer.BufferEnd = buffer.BufferEnd; } - BufferAccess Access() { return BufferAccess(Buffer); } + BufferAccess Access() { return BufferAccess(buffer); } public: constexpr inline void ForceForward(const std::size_t count = 1) noexcept { Buffer.CurrentPos += count; } @@ -88,13 +88,13 @@ namespace StreamFormat::FMT::Detail [[nodiscard]] constexpr inline std::expected, FMTResult> GetAndForward() { - if (BufferAccess(Buffer).CanMoveForward(1) == false) + if (BufferAccess(buffer).CanMoveForward(1) == false) return std::unexpected(FMTResult::Buffer_OutOfBoundAccess); return *Buffer.CurrentPos++; } [[nodiscard]] constexpr inline std::expected, FMTResult> GetAndBackward() { - if (BufferAccess(Buffer).CanMoveBackward(1) == false) + if (BufferAccess(buffer).CanMoveBackward(1) == false) return std::unexpected(FMTResult::Buffer_OutOfBoundAccess); return *Buffer.CurrentPos--; } diff --git a/src/StreamFormat/FMT/Buffer/BufferOutManager/BasicBufferOutManager.h b/src/stream/fmt/buffer/buffer_out_manager/basic_buffer_out_manager.h similarity index 94% rename from src/StreamFormat/FMT/Buffer/BufferOutManager/BasicBufferOutManager.h rename to src/stream/fmt/buffer/buffer_out_manager/basic_buffer_out_manager.h index 4c97d0eb..2d714756 100644 --- a/src/StreamFormat/FMT/Buffer/BufferOutManager/BasicBufferOutManager.h +++ b/src/stream/fmt/buffer/buffer_out_manager/basic_buffer_out_manager.h @@ -1,9 +1,9 @@ #pragma once -#include "StreamFormat/FMT/Detail/Prelude.h" -#include "StreamFormat/FMT/Buffer/BufferInfo.h" +#include "stream/fmt/detail/prelude.h" +#include "stream/fmt/buffer/buffer_info.h" -namespace StreamFormat::FMT::Detail +namespace stream::fmt::detail { template class BasicBufferOutManager diff --git a/src/StreamFormat/FMT/Buffer/BufferOutManager/DynamicBufferOutManager.h b/src/stream/fmt/buffer/buffer_out_manager/dynamic_buffer_out_manager.h similarity index 98% rename from src/StreamFormat/FMT/Buffer/BufferOutManager/DynamicBufferOutManager.h rename to src/stream/fmt/buffer/buffer_out_manager/dynamic_buffer_out_manager.h index 85fc8482..fbe81d12 100644 --- a/src/StreamFormat/FMT/Buffer/BufferOutManager/DynamicBufferOutManager.h +++ b/src/stream/fmt/buffer/buffer_out_manager/dynamic_buffer_out_manager.h @@ -1,12 +1,12 @@ #pragma once -#include "BasicBufferOutManager.h" +#include "basic_buffer_out_manager.h" #include #include #include -namespace StreamFormat::FMT::Detail +namespace stream::fmt::detail { template class DynamicBufferOutManager : public BasicBufferOutManager diff --git a/src/StreamFormat/FMT/Buffer/BufferOutManager/GivenBufferOutManager.h b/src/stream/fmt/buffer/buffer_out_manager/given_buffer_out_manager.h similarity index 94% rename from src/StreamFormat/FMT/Buffer/BufferOutManager/GivenBufferOutManager.h rename to src/stream/fmt/buffer/buffer_out_manager/given_buffer_out_manager.h index 614f528e..70949cae 100644 --- a/src/StreamFormat/FMT/Buffer/BufferOutManager/GivenBufferOutManager.h +++ b/src/stream/fmt/buffer/buffer_out_manager/given_buffer_out_manager.h @@ -1,8 +1,8 @@ #pragma once -#include "BasicBufferOutManager.h" +#include "basic_buffer_out_manager.h" -namespace StreamFormat::FMT::Detail +namespace stream::fmt::detail { template class GivenBufferOutManager : public BasicBufferOutManager diff --git a/src/StreamFormat/FMT/Buffer/BufferOutManager/StaticBufferOutManager.h b/src/stream/fmt/buffer/buffer_out_manager/static_buffer_out_manager.h similarity index 92% rename from src/StreamFormat/FMT/Buffer/BufferOutManager/StaticBufferOutManager.h rename to src/stream/fmt/buffer/buffer_out_manager/static_buffer_out_manager.h index 078aab71..4b1859f9 100644 --- a/src/StreamFormat/FMT/Buffer/BufferOutManager/StaticBufferOutManager.h +++ b/src/stream/fmt/buffer/buffer_out_manager/static_buffer_out_manager.h @@ -1,8 +1,8 @@ #pragma once -#include "BasicBufferOutManager.h" +#include "basic_buffer_out_manager.h" -namespace StreamFormat::FMT::Detail +namespace stream::fmt::detail { template class StaticBufferOutManager : public BasicBufferOutManager diff --git a/src/StreamFormat/FMT/Buffer/BufferOutManip.h b/src/stream/fmt/buffer/buffer_out_manip.h similarity index 91% rename from src/StreamFormat/FMT/Buffer/BufferOutManip.h rename to src/stream/fmt/buffer/buffer_out_manip.h index e62b9851..542e131a 100644 --- a/src/StreamFormat/FMT/Buffer/BufferOutManip.h +++ b/src/stream/fmt/buffer/buffer_out_manip.h @@ -1,11 +1,11 @@ #pragma once -#include "BufferInfo.h" -#include "BufferManip.h" +#include "buffer_info.h" +#include "buffer_manip.h" -#include "BufferOutManager/BasicBufferOutManager.h" +#include "buffer_out_manager/basic_buffer_out_manager.h" -namespace StreamFormat::FMT::Detail +namespace stream::fmt::detail { template class BufferOutInfo : public BufferInfo @@ -61,14 +61,14 @@ namespace StreamFormat::FMT::Detail BufferOutInfo& Buffer; public: - void ComputeGeneratedSize() noexcept { Buffer.Manager.ComputeGeneratedSize(BufferAccess(Buffer).GetBufferCurrentSize()); } + void ComputeGeneratedSize() noexcept { Buffer.Manager.ComputeGeneratedSize(BufferAccess(buffer).GetBufferCurrentSize()); } public: [[nodiscard]] std::expected AddSize(const std::size_t count) noexcept { - std::size_t currentSize = BufferAccess(Buffer).GetBufferCurrentSize(); + std::size_t currentSize = BufferAccess(buffer).GetBufferCurrentSize(); SF_TRY(Buffer.Manager.AddSize(count)) - BufferManip(Buffer).Set(Buffer.Manager.GetBuffer(), Buffer.Manager.GetBufferSize()); + BufferManip(buffer).Set(Buffer.Manager.GetBuffer(), Buffer.Manager.GetBufferSize()); Buffer.CurrentPos = Buffer.Manager.GetBuffer() + currentSize; return {}; } @@ -97,7 +97,7 @@ namespace StreamFormat::FMT::Detail } [[nodiscard]] inline std::expected SetInverse(const TChar c) noexcept { - SF_TRY(BufferAccess(Buffer).CanMoveBackward(1)); + SF_TRY(BufferAccess(buffer).CanMoveBackward(1)); *--Buffer.CurrentPos = c; return {}; } diff --git a/src/StreamFormat/FMT/Buffer/BufferReadManip.h b/src/stream/fmt/buffer/buffer_read_manip.h similarity index 69% rename from src/StreamFormat/FMT/Buffer/BufferReadManip.h rename to src/stream/fmt/buffer/buffer_read_manip.h index 02198e8b..9479da8f 100644 --- a/src/StreamFormat/FMT/Buffer/BufferReadManip.h +++ b/src/stream/fmt/buffer/buffer_read_manip.h @@ -1,17 +1,17 @@ #pragma once -#include "StreamFormat/FMT/Buffer/BufferInfo.h" -#include "StreamFormat/FMT/Buffer/BufferManip.h" +#include "stream/fmt/buffer/buffer_info.h" +#include "stream/fmt/buffer/buffer_manip.h" -namespace StreamFormat::FMT::Detail +namespace stream::fmt::detail { template class BufferReadManip { public: - constexpr inline BufferReadManip(BufferInfo& buffer) noexcept : Buffer(buffer) {} + constexpr inline BufferReadManip(BufferInfo& buffer_) noexcept : buffer(buffer_) {} public: - BufferInfo& Buffer; + BufferInfo& buffer; public: template @@ -19,15 +19,15 @@ namespace StreamFormat::FMT::Detail { bool sign = false; if constexpr (std::is_signed_v) - { sign = SF_TRY(BufferTestManip(Buffer).IsEqualToForward('-')); } + { sign = SF_TRY(BufferTestManip(buffer).IsEqualToForward('-')); } - if (!BufferTestAccess(Buffer).IsADigit()) + if (!BufferTestAccess(buffer).IsADigit()) { return std::unexpected(FMTResult::Parse_NonValidDigit); } T value = static_cast(0); - while (BufferTestAccess(Buffer).IsADigit()) + while (BufferTestAccess(buffer).IsADigit()) { - char c = SF_TRY(BufferManip(Buffer).GetAndForward()); + char c = SF_TRY(BufferManip(buffer).GetAndForward()); value = value * static_cast(10) + static_cast(c - static_cast('0')); } @@ -41,37 +41,37 @@ namespace StreamFormat::FMT::Detail { T intpart = static_cast(0); - BufferTestAccess access(Buffer); - BufferTestManip manip(Buffer); + BufferTestAccess access(buffer); + BufferTestManip manip(buffer); bool sign = SF_TRY(manip.IsEqualToForward('-')); if (access.IsADigit()) { SF_TRY(FastReadInteger(intpart)); } else if (access.IsEqualTo('.')) - { SF_TRY(Detail::BufferManip(Buffer).Forward()); } + { SF_TRY(detail::BufferManip(buffer).Forward()); } else { return std::unexpected(FMTResult::Parse_NonValidDigit); } if (floatPrecision < 0) { - while (access.IsADigit() && BufferAccess(Buffer).IsEndOfString() == false) - { BufferManip(Buffer).ForceForward(); } + while (access.IsADigit() && BufferAccess(buffer).IsEndOfString() == false) + { BufferManip(buffer).ForceForward(); } } else { - while (access.IsADigit() && floatPrecision > 0 && BufferAccess(Buffer).IsEndOfString() == false) + while (access.IsADigit() && floatPrecision > 0 && BufferAccess(buffer).IsEndOfString() == false) { - BufferManip(Buffer).ForceForward(); + BufferManip(buffer).ForceForward(); floatPrecision--; } } - BufferManip(Buffer).ForceBackward(); + BufferManip(buffer).ForceBackward(); T dec = static_cast(0); while (access.IsADigit()) { - dec += static_cast(BufferManip(Buffer).GetAndForceBackward() - '0'); + dec += static_cast(BufferManip(buffer).GetAndForceBackward() - '0'); dec /= 10; } @@ -83,14 +83,14 @@ namespace StreamFormat::FMT::Detail template [[nodiscard]] std::expected FastReadCharPtr(const CharPtr* str, std::size_t sizeToCopy, bool isZeroEnded = true) { - if (BufferAccess(Buffer).CanMoveForward(sizeToCopy) == false) + if (BufferAccess(buffer).CanMoveForward(sizeToCopy) == false) { - return BufferReadManip(Buffer).FastReadCharPtr(str, BufferAccess(Buffer).GetBufferRemainingSize(), isZeroEnded); + return BufferReadManip(buffer).FastReadCharPtr(str, BufferAccess(buffer).GetBufferRemainingSize(), isZeroEnded); } // TODO : Opti with bigger types while (sizeToCopy-- != 0) - { *str++ = SF_TRY(BufferManip(Buffer).GetAndForward()); } + { *str++ = SF_TRY(BufferManip(buffer).GetAndForward()); } if (isZeroEnded) { *str = 0; } return {}; diff --git a/src/StreamFormat/FMT/Buffer/BufferTestManip.h b/src/stream/fmt/buffer/buffer_test_manip.h similarity index 80% rename from src/StreamFormat/FMT/Buffer/BufferTestManip.h rename to src/stream/fmt/buffer/buffer_test_manip.h index b4bf47b7..fd36d4e3 100644 --- a/src/StreamFormat/FMT/Buffer/BufferTestManip.h +++ b/src/stream/fmt/buffer/buffer_test_manip.h @@ -1,9 +1,9 @@ #pragma once -#include "StreamFormat/FMT/Buffer/BufferInfo.h" -#include "StreamFormat/FMT/Buffer/BufferManip.h" +#include "stream/fmt/buffer/buffer_info.h" +#include "stream/fmt/buffer/buffer_manip.h" -namespace StreamFormat::FMT::Detail +namespace stream::fmt::detail { template class BufferTestAccess @@ -27,10 +27,10 @@ namespace StreamFormat::FMT::Detail return IsNotEqualTo(c) && IsNotEqualTo(ele...); } - constexpr inline bool NextIsEqualTo(const TChar c) const noexcept { return BufferAccess(Buffer).GetNextForce() + 1 == c; } - constexpr inline bool NextIsNotEqualTo(const TChar c) const noexcept { return BufferAccess(Buffer).GetNextForce() + 1 != c; } - constexpr inline bool PrevIsEqualTo(const TChar c) const noexcept { return BufferAccess(Buffer).GetPrevForce() - 1 == c; } - constexpr inline bool PrevIsNotEqualTo(const TChar c) const noexcept { return BufferAccess(Buffer).GetPrevForce() - 1 != c; } + constexpr inline bool NextIsEqualTo(const TChar c) const noexcept { return BufferAccess(buffer).GetNextForce() + 1 == c; } + constexpr inline bool NextIsNotEqualTo(const TChar c) const noexcept { return BufferAccess(buffer).GetNextForce() + 1 != c; } + constexpr inline bool PrevIsEqualTo(const TChar c) const noexcept { return BufferAccess(buffer).GetPrevForce() - 1 == c; } + constexpr inline bool PrevIsNotEqualTo(const TChar c) const noexcept { return BufferAccess(buffer).GetPrevForce() - 1 != c; } public: constexpr inline bool IsLowerCase() const noexcept { return Buffer.Get() >= 'a' && Buffer.Get() <= 'z'; } @@ -41,7 +41,7 @@ namespace StreamFormat::FMT::Detail template constexpr bool IsSame(const CharToTest* str, std::size_t size) const noexcept { - if (size > BufferAccess(Buffer).GetBufferRemainingSize()) + if (size > BufferAccess(buffer).GetBufferRemainingSize()) { return false; } const TChar* bufferStr = Buffer.CurrentPos; @@ -73,7 +73,7 @@ namespace StreamFormat::FMT::Detail using TConstChar = std::remove_const_t; public: - BufferTestAccess Access() const noexcept { return BufferTestAccess(Buffer); } + BufferTestAccess Access() const noexcept { return BufferTestAccess(buffer); } public: template @@ -81,7 +81,7 @@ namespace StreamFormat::FMT::Detail { if (Access().IsEqualTo(ele...)) { - SF_TRY(BufferManip(Buffer).Forward()); + SF_TRY(BufferManip(buffer).Forward()); return true; } return false; @@ -91,7 +91,7 @@ namespace StreamFormat::FMT::Detail { if (Access().IsNotEqualTo(ele...)) { - SF_TRY(BufferManip(Buffer).Forward()); + SF_TRY(BufferManip(buffer).Forward()); return true; } return false; @@ -99,21 +99,21 @@ namespace StreamFormat::FMT::Detail public: template - [[nodiscard]] constexpr std::expected IsSameForward(const CharToTest* str, std::size_t size) noexcept + [[nodiscard]] constexpr std::expected is_same_forward(const CharToTest* str, std::size_t size) noexcept { if (Access().IsSame(str, size)) { - SF_TRY(BufferManip(Buffer).Forward(size)); + SF_TRY(BufferManip(buffer).Forward(size)); return true; } return false; } template - [[nodiscard]] constexpr inline std::expected IsSameForward(std::basic_string_view sv) noexcept + [[nodiscard]] constexpr inline std::expected is_same_forward(std::basic_string_view sv) noexcept { if (Access().IsSame(sv)) { - SF_TRY(BufferManip(Buffer).Forward(sv.size())); + SF_TRY(BufferManip(buffer).Forward(sv.size())); return true; } return false; @@ -125,7 +125,7 @@ namespace StreamFormat::FMT::Detail { if (Access().IsEqualTo(ele...)) { - SF_TRY(BufferManip(Buffer).Forward()); + SF_TRY(BufferManip(buffer).Forward()); return {}; } return std::unexpected(FMTResult::Parse_TokenNotExpected); @@ -134,15 +134,15 @@ namespace StreamFormat::FMT::Detail template inline void IgnoreOneOf(const CharToTest... ele) noexcept { - if (Access().IsEqualTo(ele...) && BufferAccess(Buffer).CanMoveForward()) - { BufferManip(Buffer).ForceForward(); } + if (Access().IsEqualTo(ele...) && BufferAccess(buffer).CanMoveForward()) + { BufferManip(buffer).ForceForward(); } } template inline void IgnoreEvery(const CharToTest... ele) noexcept { - while (Access().IsEqualTo(ele...) && BufferAccess(Buffer).CanMoveForward()) - { BufferManip(Buffer).ForceForward(); } + while (Access().IsEqualTo(ele...) && BufferAccess(buffer).CanMoveForward()) + { BufferManip(buffer).ForceForward(); } } public: @@ -156,14 +156,14 @@ namespace StreamFormat::FMT::Detail template inline void GoTo(const CharToTest... ele) noexcept { - while (Access().IsNotEqualTo(ele...) && BufferAccess(Buffer).CanMoveForward()) - BufferManip(Buffer).ForceForward(); + while (Access().IsNotEqualTo(ele...) && BufferAccess(buffer).CanMoveForward()) + BufferManip(buffer).ForceForward(); } template [[nodiscard]] inline std::expected GoToForward(const CharToTest... ele) noexcept { GoTo(ele...); - return BufferManip(Buffer).Forward(); + return BufferManip(buffer).Forward(); } public: @@ -179,7 +179,7 @@ namespace StreamFormat::FMT::Detail template [[nodiscard]] inline std::expected, FMTResult> ViewUntil(CharToTest&&... c) { - return ViewExec([&] -> std::expected { BufferTestManip(Buffer).GoTo(std::forward(c)...); return {}; }); + return ViewExec([&] -> std::expected { BufferTestManip(buffer).GoTo(std::forward(c)...); return {}; }); } }; } diff --git a/src/StreamFormat/FMT/Buffer/BufferWriteManip.h b/src/stream/fmt/buffer/buffer_write_manip.h similarity index 93% rename from src/StreamFormat/FMT/Buffer/BufferWriteManip.h rename to src/stream/fmt/buffer/buffer_write_manip.h index 1d7d8de1..6edf6d60 100644 --- a/src/StreamFormat/FMT/Buffer/BufferWriteManip.h +++ b/src/stream/fmt/buffer/buffer_write_manip.h @@ -1,14 +1,14 @@ #pragma once -#include "BufferInfo.h" -#include "BufferManip.h" -#include "BufferTestManip.h" -#include "BufferOutManip.h" +#include "buffer_info.h" +#include "buffer_manip.h" +#include "buffer_test_manip.h" +#include "buffer_out_manip.h" #include #include -namespace StreamFormat::FMT::Detail +namespace stream::fmt::detail { class BufferWriteUtils { @@ -59,7 +59,7 @@ namespace StreamFormat::FMT::Detail requires std::is_integral_v [[nodiscard]] constexpr std::expected FastWriteInteger(T i) { - BufferOutManip manip(Buffer); + BufferOutManip manip(buffer); if (i == 0) { SF_TRY(manip.Pushback('0')); return {}; } @@ -85,7 +85,7 @@ namespace StreamFormat::FMT::Detail requires std::is_floating_point_v [[nodiscard]] constexpr std::expected FastWriteFloat(T i, std::int32_t floatPrecision = 2) { - BufferOutManip manip(Buffer); + BufferOutManip manip(buffer); if (i == 0) { SF_TRY(manip.Pushback('0')); return {}; } @@ -120,13 +120,13 @@ namespace StreamFormat::FMT::Detail template [[nodiscard]] constexpr std::expected FastWriteCharArray(const CharInput* str, std::size_t size) { - auto reserve = BufferOutManip(Buffer).Reserve(size); + auto reserve = BufferOutManip(buffer).Reserve(size); if (reserve.has_value() == false) - return FastWriteCharArray(str, BufferAccess(Buffer).GetBufferRemainingSize()); + return FastWriteCharArray(str, BufferAccess(buffer).GetBufferRemainingSize()); // TODO: Opti with bigger types while (size-- != 0 && *str != 0) - BufferOutManip(Buffer).ForcePushback(*str++); + BufferOutManip(buffer).ForcePushback(*str++); return {}; } diff --git a/src/StreamFormat/FMT/Buffer/FMTBufferOutManip.h b/src/stream/fmt/buffer/fmt_buffer_out_manip.h similarity index 79% rename from src/StreamFormat/FMT/Buffer/FMTBufferOutManip.h rename to src/stream/fmt/buffer/fmt_buffer_out_manip.h index 818103bf..c90113b8 100644 --- a/src/StreamFormat/FMT/Buffer/FMTBufferOutManip.h +++ b/src/stream/fmt/buffer/fmt_buffer_out_manip.h @@ -1,10 +1,10 @@ #pragma once -#include "BufferInfo.h" -#include "BufferOutManip.h" -#include "BufferTestManip.h" +#include "buffer_info.h" +#include "buffer_out_manip.h" +#include "buffer_test_manip.h" -namespace StreamFormat::FMT::Detail +namespace stream::fmt::detail { template class FMTBufferOutInfo : public BufferOutInfo @@ -52,20 +52,20 @@ namespace StreamFormat::FMT::Detail constexpr inline void AddIndent(const std::size_t indent) noexcept { Buffer.Indent += indent; } constexpr inline void RemoveIndent(const std::size_t indent) noexcept { Buffer.Indent -= indent; } - constexpr inline void SetIndent() noexcept { Buffer.Indent = BufferManip(Buffer).GetBufferCurrentSize() - Buffer.NoStride; } + constexpr inline void SetIndent() noexcept { Buffer.Indent = BufferManip(buffer).GetBufferCurrentSize() - Buffer.NoStride; } public: [[nodiscard]] constexpr inline std::expected NewLineIndent() { - SF_TRY(BufferOutManip(Buffer).Pushback('\n')); - return BufferOutManip(Buffer).Pushback(' ', Buffer.Indent); + SF_TRY(BufferOutManip(buffer).Pushback('\n')); + return BufferOutManip(buffer).Pushback(' ', Buffer.Indent); } [[nodiscard]] constexpr inline std::expected PushbackCheckIndent(const TChar c) { - SF_TRY(BufferOutManip(Buffer).Pushback(c)); + SF_TRY(BufferOutManip(buffer).Pushback(c)); if (c == '\n') - { return BufferOutManip(Buffer).Pushback(' ', Buffer.Indent); } + { return BufferOutManip(buffer).Pushback(' ', Buffer.Indent); } return {}; } }; @@ -82,32 +82,32 @@ namespace StreamFormat::FMT::Detail template inline void ParamGoTo(const CharToTest... ele) { - BufferTestManip(Buffer).GoTo(ele..., '}'); + BufferTestManip(buffer).GoTo(ele..., '}'); } template [[nodiscard]] inline std::expected ParamGoToForward(const CharToTest... ele) { - return BufferTestManip(Buffer).GoToForward(ele..., '}'); + return BufferTestManip(buffer).GoToForward(ele..., '}'); } inline bool IsBeginOfParameter() { - return BufferTestAccess(Buffer).IsEqualTo('{'); + return BufferTestAccess(buffer).IsEqualTo('{'); } inline bool IsEndOfParameter() { - return BufferTestAccess(Buffer).IsEqualTo('}'); + return BufferTestAccess(buffer).IsEqualTo('}'); } public: template [[nodiscard]] std::expected NextIsNamedArgs(const std::basic_string_view& sv) { - BufferTestAccess access(Buffer); - BufferTestManip manip(Buffer); + BufferTestAccess access(buffer); + BufferTestManip manip(buffer); TChar* const oldpos = Buffer.CurrentPos; - auto isSame = SF_TRY(manip.IsSameForward(sv)); + auto isSame = SF_TRY(manip.is_same_forward(sv)); if (isSame && (access.IsEqualTo(':') || access.IsEqualTo('}'))) { return true; diff --git a/src/StreamFormat/FMT/Buffer/FMTBufferReadManip.h b/src/stream/fmt/buffer/fmt_buffer_read_manip.h similarity index 82% rename from src/StreamFormat/FMT/Buffer/FMTBufferReadManip.h rename to src/stream/fmt/buffer/fmt_buffer_read_manip.h index 466fc68b..050bdd91 100644 --- a/src/StreamFormat/FMT/Buffer/FMTBufferReadManip.h +++ b/src/stream/fmt/buffer/fmt_buffer_read_manip.h @@ -1,12 +1,12 @@ #pragma once -#include "StreamFormat/FMT/Buffer/BufferInfo.h" -#include "StreamFormat/FMT/Buffer/Utils/BufferShiftManip.h" -#include "StreamFormat/FMT/Buffer/BufferManip.h" -#include "StreamFormat/FMT/Buffer/BufferTestManip.h" -#include "StreamFormat/FMT/Buffer/BufferReadManip.h" +#include "stream/fmt/buffer/buffer_info.h" +#include "stream/fmt/buffer/utils/BufferShiftManip.h" +#include "stream/fmt/buffer/buffer_manip.h" +#include "stream/fmt/buffer/buffer_test_manip.h" +#include "stream/fmt/buffer/buffer_read_manip.h" -namespace StreamFormat::FMT::Detail +namespace stream::fmt::detail { template class FMTBufferReadManip @@ -20,9 +20,9 @@ namespace StreamFormat::FMT::Detail template [[nodiscard]] std::expected ReadInteger(T& i, ShiftInfo shift = ShiftInfo{}) { - BufferShiftReadManip shiftManip(Buffer); - Detail::BufferTestAccess access(Buffer); - Detail::BufferTestManip manip(Buffer); + BufferShiftReadManip shiftManip(buffer); + detail::BufferTestAccess access(buffer); + detail::BufferTestManip manip(buffer); SF_TRY(shiftManip.IgnoreShiftBeginSpace(shift)); @@ -38,7 +38,7 @@ namespace StreamFormat::FMT::Detail T res = (T)0; while (access.IsADigit()) { - char c = SF_TRY(BufferManip(Buffer).GetAndForward()); + char c = SF_TRY(BufferManip(buffer).GetAndForward()); res = res * 10 + (c - '0'); --shift.Size; } @@ -52,9 +52,9 @@ namespace StreamFormat::FMT::Detail template [[nodiscard]] std::expected ReadFloat(T& t, std::int32_t floatPrecision = -1, ShiftInfo shift = ShiftInfo{}) { - BufferShiftReadManip shiftManip(Buffer); - Detail::BufferTestAccess access(Buffer); - Detail::BufferTestManip manip(Buffer); + BufferShiftReadManip shiftManip(buffer); + detail::BufferTestAccess access(buffer); + detail::BufferTestManip manip(buffer); SF_TRY(shiftManip.IgnoreShiftBeginSpace(shift)); @@ -66,37 +66,37 @@ namespace StreamFormat::FMT::Detail { while (access.IsADigit()) { - char c = SF_TRY(BufferManip(Buffer).GetAndForward()); + char c = SF_TRY(BufferManip(buffer).GetAndForward()); intpart = intpart * 10 + (c - '0'); --shift.Size; } } else if (access.IsEqualTo('.')) - { SF_TRY(Detail::BufferManip(Buffer).Forward()); } + { SF_TRY(detail::BufferManip(buffer).Forward()); } else { return std::unexpected(FMTResult::Parse_NonValidDigit); } if (floatPrecision <= 0) while (access.IsADigit() && access.IsEndOfString() == false) { - BufferManip(Buffer).ForceForward(); + BufferManip(buffer).ForceForward(); --shift.Size; } else { - while (BufferAccess(Buffer).IsADigit() && floatPrecision > 0 && BufferAccess(Buffer).IsEndOfString() == false) + while (BufferAccess(buffer).IsADigit() && floatPrecision > 0 && BufferAccess(buffer).IsEndOfString() == false) { - BufferManip(Buffer).ForceForward(); + BufferManip(buffer).ForceForward(); floatPrecision--; --shift.Size; } } - BufferManip(Buffer).ForceBackward(); + BufferManip(buffer).ForceBackward(); T dec = (T)0; while (access.IsADigit()) { - dec += static_cast(BufferManip(Buffer).GetAndForceBackward() - '0'); + dec += static_cast(BufferManip(buffer).GetAndForceBackward() - '0'); dec /= 10; } @@ -110,9 +110,9 @@ namespace StreamFormat::FMT::Detail template [[nodiscard]] std::expected ReadIntegerH(T& i, std::uint8_t digitSize, std::uint8_t (&digitLUT)(TChar), TChar base_prefix = '\0', ShiftInfo shift = ShiftInfo{}) { - BufferShiftReadManip shiftManip(Buffer); - Detail::BufferTestAccess access(Buffer); - Detail::BufferTestManip manip(Buffer); + BufferShiftReadManip shiftManip(buffer); + detail::BufferTestAccess access(buffer); + detail::BufferTestManip manip(buffer); shift.Size -= sizeof(T) * 8; if (base_prefix != '\0') shift.Size -= 2; @@ -130,7 +130,7 @@ namespace StreamFormat::FMT::Detail { res = res << digitSize; res += digitLUT(Buffer.Get()); - BufferManip(Buffer).ForceForward(); + BufferManip(buffer).ForceForward(); } SF_TRY(shiftManip.IgnoreShiftEnd(shift)); @@ -185,7 +185,7 @@ namespace StreamFormat::FMT::Detail { case IntegerPrintBase::Dec: if (formatData.Shift.Type == ShiftInfo::ShiftType::Nothing) - return BufferReadManip(Buffer).FastReadInteger(i); + return BufferReadManip(buffer).FastReadInteger(i); else return ReadInteger(i, formatData.Shift); case IntegerPrintBase::Bin: @@ -200,7 +200,7 @@ namespace StreamFormat::FMT::Detail return ReadIntegerH(i, 4, DigitLUT_HEXUPPER, formatData.PrefixSuffix ? (char)formatData.IntegerPrint : '\0', formatData.Shift); } } - return BufferReadManip(Buffer).FastReadInteger(i); + return BufferReadManip(buffer).FastReadInteger(i); } template [[nodiscard]] std::expected ReadFloatFormatData(T& i, const FormatData& formatData) @@ -208,11 +208,11 @@ namespace StreamFormat::FMT::Detail if (formatData.HasSpec) { if (formatData.ShiftType == ShiftInfo::ShiftType::Nothing) - return BufferReadManip(Buffer).FastReadFloat(i, formatData.FloatPrecision); + return BufferReadManip(buffer).FastReadFloat(i, formatData.FloatPrecision); else return ReadFloat(i, formatData.FloatPrecision, formatData.Shift); } - return BufferReadManip(Buffer).FastReadFloat(i, formatData.FloatPrecision); + return BufferReadManip(buffer).FastReadFloat(i, formatData.FloatPrecision); } public: diff --git a/src/StreamFormat/FMT/Buffer/FMTBufferWriteManip.h b/src/stream/fmt/buffer/fmt_buffer_write_manip.h similarity index 76% rename from src/StreamFormat/FMT/Buffer/FMTBufferWriteManip.h rename to src/stream/fmt/buffer/fmt_buffer_write_manip.h index 6da095b9..3f292eb3 100644 --- a/src/StreamFormat/FMT/Buffer/FMTBufferWriteManip.h +++ b/src/stream/fmt/buffer/fmt_buffer_write_manip.h @@ -1,14 +1,14 @@ #pragma once -#include "BufferInfo.h" -#include "FMTBufferOutManip.h" -#include "Utils/BufferShiftManip.h" -#include "BufferOutManip.h" -#include "BufferWriteManip.h" +#include "buffer_info.h" +#include "fmt_buffer_out_manip.h" +#include "utils/BufferShiftManip.h" +#include "buffer_out_manip.h" +#include "buffer_write_manip.h" #include -namespace StreamFormat::FMT::Detail +namespace stream::fmt::detail { template class FMTBufferWriteManip @@ -20,7 +20,7 @@ namespace StreamFormat::FMT::Detail public: template - [[nodiscard]] std::expected WriteInteger(T i, Detail::ShiftInfo shift = Detail::ShiftInfo{}) + [[nodiscard]] std::expected WriteInteger(T i, detail::ShiftInfo shift = detail::ShiftInfo{}) { char oldAfter = shift.Print.After; if (shift.Print.After >= '0' && shift.Print.After <= '9') @@ -32,34 +32,34 @@ namespace StreamFormat::FMT::Detail if (i < 0) --shift.Size; if (shift.Size <= 0) - { return BufferWriteManip(Buffer).FastWriteInteger(i); } + { return BufferWriteManip(buffer).FastWriteInteger(i); } if (!shift.Print.BeforeIsADigit()) - { SF_TRY(BufferShiftWriteManip(Buffer).WriteShiftBegin(shift)); } + { SF_TRY(BufferShiftWriteManip(buffer).WriteShiftBegin(shift)); } if (i < 0) { - SF_TRY(BufferOutManip(Buffer).Pushback('-')); + SF_TRY(BufferOutManip(buffer).Pushback('-')); i = -i; } if (shift.Print.BeforeIsADigit()) - { SF_TRY(BufferShiftWriteManip(Buffer).WriteShiftRightAll(shift)); } + { SF_TRY(BufferShiftWriteManip(buffer).WriteShiftRightAll(shift)); } if (i == 0) - { SF_TRY(BufferOutManip(Buffer).Pushback('0')); } + { SF_TRY(BufferOutManip(buffer).Pushback('0')); } else { - SF_TRY(BufferOutManip(Buffer).Forward(nbDigit)); + SF_TRY(BufferOutManip(buffer).Forward(nbDigit)); std::int32_t nbDigit_ = nbDigit; while (nbDigit_ > 0) { - BufferOutManip(Buffer).ForceSetInverse(i % 10 + '0'); + BufferOutManip(buffer).ForceSetInverse(i % 10 + '0'); i /= 10; nbDigit_--; } - SF_TRY(BufferOutManip(Buffer).Forward(nbDigit)); + SF_TRY(BufferOutManip(buffer).Forward(nbDigit)); } - SF_TRY(BufferShiftWriteManip(Buffer).WriteShiftEnd(shift)); + SF_TRY(BufferShiftWriteManip(buffer).WriteShiftEnd(shift)); shift.Print.After = oldAfter; return {}; @@ -67,7 +67,7 @@ namespace StreamFormat::FMT::Detail public: template - [[nodiscard]] std::expected WriteFloat(T i, std::int32_t floatPrecision = 2, Detail::ShiftInfo shift = Detail::ShiftInfo{}) + [[nodiscard]] std::expected WriteFloat(T i, std::int32_t floatPrecision = 2, detail::ShiftInfo shift = detail::ShiftInfo{}) { char oldBefore = shift.Print.Before; if (shift.Print.Before >= '0' && shift.Print.Before <= '9') @@ -79,44 +79,44 @@ namespace StreamFormat::FMT::Detail if (i < 0) --shift.Size; if (shift.Size <= 0) - { return BufferWriteManip(Buffer).FastWriteFloat(i, floatPrecision); } + { return BufferWriteManip(buffer).FastWriteFloat(i, floatPrecision); } if (!shift.Print.BeforeIsADigit()) - { SF_TRY(BufferShiftWriteManip(Buffer).WriteShiftBegin(shift)); } + { SF_TRY(BufferShiftWriteManip(buffer).WriteShiftBegin(shift)); } if (i < 0) { - SF_TRY(BufferOutManip(Buffer).Pushback('-')); + SF_TRY(BufferOutManip(buffer).Pushback('-')); i = -i; } if (shift.Print.BeforeIsADigit()) - { SF_TRY(BufferShiftWriteManip(Buffer).WriteShiftRightAll(shift)); } + { SF_TRY(BufferShiftWriteManip(buffer).WriteShiftRightAll(shift)); } T k = std::trunc(i); if (k == 0) - { SF_TRY(BufferOutManip(Buffer).Pushback('0')); } + { SF_TRY(BufferOutManip(buffer).Pushback('0')); } else { - SF_TRY(BufferOutManip(Buffer).Forward(nbDigit)); + SF_TRY(BufferOutManip(buffer).Forward(nbDigit)); std::int32_t nbDigit_ = nbDigit; while (nbDigit_ > 0) { - BufferOutManip(Buffer).ForceSetInverse(char(std::fmod(i, 10)) + '0'); + BufferOutManip(buffer).ForceSetInverse(char(std::fmod(i, 10)) + '0'); k /= 10; nbDigit_--; } - SF_TRY(BufferOutManip(Buffer).Forward(nbDigit)); + SF_TRY(BufferOutManip(buffer).Forward(nbDigit)); } - SF_TRY(BufferOutManip(Buffer).Pushback('.')); + SF_TRY(BufferOutManip(buffer).Pushback('.')); i -= k; while (floatPrecision-- != 0) { T decimal = std::trunc(i *= 10); - SF_TRY(BufferOutManip(Buffer).Pushback((char)decimal + '0')); + SF_TRY(BufferOutManip(buffer).Pushback((char)decimal + '0')); i -= decimal; } - SF_TRY(BufferShiftWriteManip(Buffer).WriteShiftEnd(shift)); + SF_TRY(BufferShiftWriteManip(buffer).WriteShiftEnd(shift)); shift.Print.Before = oldBefore; return {}; @@ -126,7 +126,7 @@ namespace StreamFormat::FMT::Detail template [[nodiscard]] std::expected WriteIntegerH(T i, std::uint8_t digitSize, const TChar* const lut, TChar base_prefix = '\0', ShiftInfo shift = ShiftInfo{}) { - BufferOutManip manip(Buffer); + BufferOutManip manip(buffer); std::int32_t digitCount = sizeof(T) * 8; { @@ -144,8 +144,8 @@ namespace StreamFormat::FMT::Detail if (base_prefix != '\0') { - SF_TRY(BufferOutManip(Buffer).Pushback('0')); - SF_TRY(BufferOutManip(Buffer).Pushback(base_prefix)); + SF_TRY(BufferOutManip(buffer).Pushback('0')); + SF_TRY(BufferOutManip(buffer).Pushback(base_prefix)); } SF_TRY(manip.Forward(digitCount)); @@ -169,7 +169,7 @@ namespace StreamFormat::FMT::Detail { case IntegerPrintBase::Dec: if (formatData.Shift.Type == ShiftInfo::ShiftType::Nothing) - return BufferWriteManip(Buffer).FastWriteInteger(i); + return BufferWriteManip(buffer).FastWriteInteger(i); else return WriteInteger(i, formatData.Shift); case IntegerPrintBase::Bin: @@ -185,7 +185,7 @@ namespace StreamFormat::FMT::Detail } } - return BufferWriteManip(Buffer).FastWriteInteger(i); + return BufferWriteManip(buffer).FastWriteInteger(i); } template [[nodiscard]] std::expected WriteFloatFormatData(T i, const FormatData& formatData) @@ -196,7 +196,7 @@ namespace StreamFormat::FMT::Detail return WriteFloat(i, formatData.FloatPrecision, formatData.Shift); } - return BufferWriteManip(Buffer).FastWriteFloat(i, formatData.FloatPrecision); + return BufferWriteManip(buffer).FastWriteFloat(i, formatData.FloatPrecision); } public: @@ -212,11 +212,11 @@ namespace StreamFormat::FMT::Detail } const CharStr* const end = str; - SF_TRY(BufferWriteManip(Buffer).FastWriteCharArray(begin, end - begin)); + SF_TRY(BufferWriteManip(buffer).FastWriteCharArray(begin, end - begin)); if (size > 0 && *str == '\n') { - SF_TRY(FMTBufferOutManip(Buffer).NewLineIndent()); + SF_TRY(FMTBufferOutManip(buffer).NewLineIndent()); ++str; --size; } @@ -238,23 +238,23 @@ namespace StreamFormat::FMT::Detail [[nodiscard]] inline std::expected WriteCharPtr(const CharStr* str, std::size_t size, ShiftInfo& shift) { if (shift.Size <= 0) - return BufferWriteManip(Buffer).FastWriteCharArray(str, size); + return BufferWriteManip(buffer).FastWriteCharArray(str, size); - SF_TRY(BufferOutManip(Buffer).Reserve(std::max(static_cast(shift.Size), size))); + SF_TRY(BufferOutManip(buffer).Reserve(std::max(static_cast(shift.Size), size))); if (static_cast(shift.Size) > size) { shift.Size -= static_cast(size); - SF_TRY(BufferShiftWriteManip(Buffer).WriteShiftBegin(shift)); + SF_TRY(BufferShiftWriteManip(buffer).WriteShiftBegin(shift)); - SF_TRY(BufferWriteManip(Buffer).FastWriteCharArray(str, size)); + SF_TRY(BufferWriteManip(buffer).FastWriteCharArray(str, size)); - SF_TRY(BufferShiftWriteManip(Buffer).WriteShiftEnd(shift)); + SF_TRY(BufferShiftWriteManip(buffer).WriteShiftEnd(shift)); } else { - SF_TRY(BufferWriteManip(Buffer).FastWriteCharArray(str, size)); + SF_TRY(BufferWriteManip(buffer).FastWriteCharArray(str, size)); } return {}; } diff --git a/src/StreamFormat/FMT/Buffer/Utils/BufferGlobberManip.h b/src/stream/fmt/buffer/utils/buffer_globber_manip.h similarity index 97% rename from src/StreamFormat/FMT/Buffer/Utils/BufferGlobberManip.h rename to src/stream/fmt/buffer/utils/buffer_globber_manip.h index 4c1cc671..9f33eb42 100644 --- a/src/StreamFormat/FMT/Buffer/Utils/BufferGlobberManip.h +++ b/src/stream/fmt/buffer/utils/buffer_globber_manip.h @@ -1,9 +1,9 @@ #pragma once -#include "StreamFormat/FMT/Buffer/BufferInfo.h" -#include "StreamFormat/FMT/Buffer/BufferManip.h" +#include "stream/fmt/buffer/buffer_info.h" +#include "stream/fmt/buffer/buffer_manip.h" -namespace StreamFormat::FMT::Detail +namespace stream::fmt::detail { template class Globber diff --git a/src/StreamFormat/FMT/Buffer/Utils/BufferShiftManip.h b/src/stream/fmt/buffer/utils/buffer_shift_manip.h similarity index 56% rename from src/StreamFormat/FMT/Buffer/Utils/BufferShiftManip.h rename to src/stream/fmt/buffer/utils/buffer_shift_manip.h index 790cdb77..6b0958a0 100644 --- a/src/StreamFormat/FMT/Buffer/Utils/BufferShiftManip.h +++ b/src/stream/fmt/buffer/utils/buffer_shift_manip.h @@ -1,9 +1,9 @@ #pragma once -#include "StreamFormat/FMT/Buffer/BufferInfo.h" -#include "StreamFormat/FMT/Buffer/BufferOutManip.h" +#include "stream/fmt/buffer/buffer_info.h" +#include "stream/fmt/buffer/buffer_out_manip.h" -namespace StreamFormat::FMT::Detail +namespace stream::fmt::detail { template class BufferShiftWriteManip @@ -14,47 +14,47 @@ namespace StreamFormat::FMT::Detail BufferOutInfo& Buffer; public: - [[nodiscard]] inline std::expected WriteShiftCenterBegin(Detail::ShiftInfo& shift) + [[nodiscard]] inline std::expected WriteShiftCenterBegin(detail::ShiftInfo& shift) { - if (shift.Type == Detail::ShiftInfo::ShiftType::CenterRight || shift.Type == Detail::ShiftInfo::ShiftType::CenterLeft) + if (shift.Type == detail::ShiftInfo::ShiftType::CenterRight || shift.Type == detail::ShiftInfo::ShiftType::CenterLeft) { std::int32_t shift_ = shift.Size / 2; - if (shift.Type == Detail::ShiftInfo::ShiftType::CenterLeft) shift_ = (shift.Size + 1) / 2; - SF_TRY(BufferOutManip(Buffer).Pushback(shift.Print.Before, shift.Size - shift_)); + if (shift.Type == detail::ShiftInfo::ShiftType::CenterLeft) shift_ = (shift.Size + 1) / 2; + SF_TRY(BufferOutManip(buffer).Pushback(shift.Print.Before, shift.Size - shift_)); shift.Size = shift_; } return {}; } - [[nodiscard]] inline std::expected WriteShiftCenterEnd(Detail::ShiftInfo& shift) + [[nodiscard]] inline std::expected WriteShiftCenterEnd(detail::ShiftInfo& shift) { - if (shift.Type == Detail::ShiftInfo::ShiftType::CenterRight || shift.Type == Detail::ShiftInfo::ShiftType::CenterLeft) - return BufferOutManip(Buffer).Pushback(shift.Print.After, shift.Size); + if (shift.Type == detail::ShiftInfo::ShiftType::CenterRight || shift.Type == detail::ShiftInfo::ShiftType::CenterLeft) + return BufferOutManip(buffer).Pushback(shift.Print.After, shift.Size); return {}; } - [[nodiscard]] inline std::expected WriteShiftRightAll(Detail::ShiftInfo& shift) + [[nodiscard]] inline std::expected WriteShiftRightAll(detail::ShiftInfo& shift) { - if (shift.Type == Detail::ShiftInfo::ShiftType::Right) - return BufferOutManip(Buffer).Pushback(shift.Print.Before, shift.Size); + if (shift.Type == detail::ShiftInfo::ShiftType::Right) + return BufferOutManip(buffer).Pushback(shift.Print.Before, shift.Size); return {}; } - [[nodiscard]] inline std::expected WriteShiftLeftAll(Detail::ShiftInfo& shift) + [[nodiscard]] inline std::expected WriteShiftLeftAll(detail::ShiftInfo& shift) { - if (shift.Type == Detail::ShiftInfo::ShiftType::Left) - return BufferOutManip(Buffer).Pushback(shift.Print.After, shift.Size); + if (shift.Type == detail::ShiftInfo::ShiftType::Left) + return BufferOutManip(buffer).Pushback(shift.Print.After, shift.Size); return {}; } - [[nodiscard]] inline std::expected WriteShiftBegin(Detail::ShiftInfo& shift) + [[nodiscard]] inline std::expected WriteShiftBegin(detail::ShiftInfo& shift) { SF_TRY(WriteShiftCenterBegin(shift)); return WriteShiftRightAll(shift); } - [[nodiscard]] inline std::expected WriteShiftEnd(Detail::ShiftInfo& shift) + [[nodiscard]] inline std::expected WriteShiftEnd(detail::ShiftInfo& shift) { SF_TRY(WriteShiftLeftAll(shift)); return WriteShiftCenterEnd(shift); @@ -70,29 +70,29 @@ namespace StreamFormat::FMT::Detail BufferInfo& Buffer; public: - [[nodiscard]] std::expected IgnoreShiftBeginSpace(Detail::ShiftInfo& shift) + [[nodiscard]] std::expected IgnoreShiftBeginSpace(detail::ShiftInfo& shift) { if (shift.Print.BeforeIsADigit() == false) return {}; - if (shift.Type == Detail::ShiftInfo::ShiftType::Right || shift.Type == Detail::ShiftInfo::ShiftType::CenterLeft || shift.Type == Detail::ShiftInfo::ShiftType::CenterRight) + if (shift.Type == detail::ShiftInfo::ShiftType::Right || shift.Type == detail::ShiftInfo::ShiftType::CenterLeft || shift.Type == detail::ShiftInfo::ShiftType::CenterRight) { while (Buffer.Get() == ' ') { - SF_TRY(BufferManip(Buffer).Forward()); + SF_TRY(BufferManip(buffer).Forward()); --shift.Size; } } return {}; } - [[nodiscard]] std::expected IgnoreShiftEnd(Detail::ShiftInfo& shift) + [[nodiscard]] std::expected IgnoreShiftEnd(detail::ShiftInfo& shift) { - if (shift.Type == Detail::ShiftInfo::ShiftType::Left || shift.Type == Detail::ShiftInfo::ShiftType::CenterLeft || shift.Type == Detail::ShiftInfo::ShiftType::CenterRight) + if (shift.Type == detail::ShiftInfo::ShiftType::Left || shift.Type == detail::ShiftInfo::ShiftType::CenterLeft || shift.Type == detail::ShiftInfo::ShiftType::CenterRight) { while (Buffer.Get() == ' ' && shift.Size > 0) { - SF_TRY(BufferManip(Buffer).Forward()); + SF_TRY(BufferManip(buffer).Forward()); --shift.Size; } } diff --git a/src/stream/fmt/buffer/utils/buffer_utils.h b/src/stream/fmt/buffer/utils/buffer_utils.h new file mode 100644 index 00000000..8066ac8d --- /dev/null +++ b/src/stream/fmt/buffer/utils/buffer_utils.h @@ -0,0 +1,131 @@ +#pragma once + +#include "stream/fmt/buffer/buffer_info.h" +#include "stream/fmt/buffer/buffer_out_manip.h" +#include "stream/fmt/buffer/buffer_test_manip.h" +#include "stream/fmt/buffer/buffer_write_manip.h" +#include "stream/fmt/buffer/buffer_read_manip.h" + +#include "stream/fmt/buffer/buffer_out_manager/dynamic_buffer_out_manager.h" +#include "stream/fmt/buffer/buffer_out_manager/given_buffer_out_manager.h" +#include "stream/fmt/buffer/buffer_out_manager/static_buffer_out_manager.h" + +namespace stream::fmt::detail +{ + template + class BufferUtilsManip + { + public: + constexpr inline BufferUtilsManip(BufferInfo& buffer_) noexcept : buffer(buffer_) {} + public: + BufferInfo& buffer; + + using TConstChar = std::remove_const_t; + + public: + template + [[nodiscard]] std::expected get_word_from_list(const std::basic_string_view (&data)[SIZE]) + { + for (std::size_t idx = 0; idx < SIZE; ++idx) + { + bool found = SF_TRY(BufferTestManip(buffer).is_same_forward(data[idx])); + if (found) return idx; + } + return std::unexpected(FMTResult::Specifers_Invalid); + } + + // TODO: use static map ? + template + using DictPairs = std::pair, T>; + + template + [[nodiscard]] std::expected get_word_from_dict_pairs(const DictPairs (&data)[SIZE]) + { + for (std::size_t idx = 0; idx < SIZE; ++idx) + { + bool found = SF_TRY(BufferTestManip(buffer).is_same_forward(data[idx].first)); + if (found) + return data[idx].second; + } + return std::unexpected(FMTResult::Specifers_Invalid); + } + }; + + class BufferUtils + { + public: + template + [[nodiscard]] static std::expected parse_escaped_quoted_string(detail::BufferInfo& buffer, detail::BufferOutInfo& stringOut) + { + SF_TRY(detail::BufferTestManip(buffer).SkipOneOf('"')); + while (detail::BufferAccess(buffer).IsEndOfString() == false) + { + auto view = SF_TRY(detail::BufferTestManip(buffer).ViewUntil('"', '\\')); + SF_TRY(detail::BufferWriteManip(stringOut).FastWriteString(view)); + + if (detail::BufferTestAccess(buffer).IsEqualTo('"')) + { break; } + + SF_TRY(detail::BufferTestManip(buffer).SkipOneOf('\\')); + switch (buffer.Get()) + { + // TODO : Do all others escape char + case '"': + SF_TRY(detail::BufferOutManip(stringOut).Pushback('"')); + break; + case 't': + SF_TRY(detail::BufferOutManip(stringOut).Pushback('\t')); + break; + case 'r': + SF_TRY(detail::BufferOutManip(stringOut).Pushback('\r')); + break; + case 'n': + SF_TRY(detail::BufferOutManip(stringOut).Pushback('\n')); + break; + default: + break; + } + } + SF_TRY(detail::BufferTestManip(buffer).SkipOneOf('"')); + + return {}; + } + + template + [[nodiscard]] static std::expected FormatEscapedQuotedString(detail::BufferOutInfo& buffer, detail::BufferInfo& stringIn) + { + SF_TRY(detail::BufferOutManip(buffer).Pushback('"')); + while (detail::BufferAccess(stringIn).IsEndOfString() == false) + { + auto view = SF_TRY(detail::BufferTestManip(stringIn).ViewUntil('\\')); + SF_TRY(detail::BufferWriteManip(buffer).FastWriteString(view)); + + if (detail::BufferAccess(stringIn).IsEndOfString()) break; + + // TODO + SF_TRY(detail::BufferTestManip(stringIn).SkipOneOf('\\')); + switch (stringIn.Get()) + { + // TODO : Do all others escape char + case '"': + SF_TRY(detail::BufferOutManip(buffer).Pushback('"')); + break; + case 't': + SF_TRY(detail::BufferOutManip(buffer).Pushback('\t')); + break; + case 'r': + SF_TRY(detail::BufferOutManip(buffer).Pushback('\r')); + break; + case 'n': + SF_TRY(detail::BufferOutManip(buffer).Pushback('\n')); + break; + default: + break; + } + } + SF_TRY(detail::BufferOutManip(buffer).Pushback('"')); + + return {}; + } + }; +} diff --git a/src/StreamFormat/FMT/Context/BasicContext/BasicArgsInterface.h b/src/stream/fmt/context/basic_context/basic_args_interface.h similarity index 93% rename from src/StreamFormat/FMT/Context/BasicContext/BasicArgsInterface.h rename to src/stream/fmt/context/basic_context/basic_args_interface.h index 0e865d00..208023a5 100644 --- a/src/StreamFormat/FMT/Context/BasicContext/BasicArgsInterface.h +++ b/src/stream/fmt/context/basic_context/basic_args_interface.h @@ -1,14 +1,14 @@ #pragma once -#include "StreamFormat/FMT/Detail/ConvertTraits.h" -#include "StreamFormat/FMT/Detail/Prelude.h" -#include "StreamFormat/FMT/Buffer/BufferInfo.h" +#include "stream/fmt/detail/convert_traits.h" +#include "stream/fmt/detail/prelude.h" +#include "stream/fmt/buffer/buffer_info.h" #include #include #include -namespace StreamFormat::FMT::Context +namespace stream::fmt::context { template class BasicContext; @@ -17,7 +17,7 @@ namespace StreamFormat::FMT::Context class ContextExecutor; } -namespace StreamFormat::FMT::Detail +namespace stream::fmt::detail { struct PointerID { diff --git a/src/StreamFormat/FMT/Context/BasicContext/BasicContext.h b/src/stream/fmt/context/basic_context/basic_context.h similarity index 68% rename from src/StreamFormat/FMT/Context/BasicContext/BasicContext.h rename to src/stream/fmt/context/basic_context/basic_context.h index 04389fac..01214e9c 100644 --- a/src/StreamFormat/FMT/Context/BasicContext/BasicContext.h +++ b/src/stream/fmt/context/basic_context/basic_context.h @@ -1,20 +1,20 @@ #pragma once -#include "StreamFormat/FMT/Detail/ConvertTraits.h" -#include "StreamFormat/FMT/Detail/Prelude.h" -#include "StreamFormat/FMT/Detail/Specifiers.h" +#include "stream/fmt/detail/convert_traits.h" +#include "stream/fmt/detail/prelude.h" +#include "stream/fmt/detail/specifiers.h" -#include "StreamFormat/FMT/Buffer/BufferInfo.h" -#include "StreamFormat/FMT/Buffer/BufferManip.h" -#include "StreamFormat/FMT/Buffer/BufferTestManip.h" -#include "StreamFormat/FMT/Buffer/BufferReadManip.h" +#include "stream/fmt/buffer/buffer_info.h" +#include "stream/fmt/buffer/buffer_manip.h" +#include "stream/fmt/buffer/buffer_test_manip.h" +#include "stream/fmt/buffer/buffer_read_manip.h" -#include "BasicArgsInterface.h" +#include "basic_args_interface.h" -#include "ITextPropertiesExecutor.h" -#include "TextPropertiesManager.h" +#include "text_properties_executor.h" +#include "text_properties_manager.h" -namespace StreamFormat::FMT::Context +namespace stream::fmt::context { template class BasicContext; @@ -23,7 +23,7 @@ namespace StreamFormat::FMT::Context class ContextExecutor { public: - ContextExecutor(Detail::ITextPropertiesExecutor& textPropertiesExecutor) + ContextExecutor(detail::ITextPropertiesExecutor& textPropertiesExecutor) : Data{} , TextManager{textPropertiesExecutor} {} @@ -34,8 +34,8 @@ namespace StreamFormat::FMT::Context [[nodiscard]] virtual std::expected ExecRawString(std::basic_string_view) = 0; public: - Detail::FormatData Data; - Detail::TextPropertiesManager TextManager; + detail::FormatData Data; + detail::TextPropertiesManager TextManager; }; template @@ -47,16 +47,16 @@ namespace StreamFormat::FMT::Context public: BasicContext( ContextExecutor& executor, - Detail::BufferInfoView format, - Detail::BasicArgsInterface& argsInterface + detail::BufferInfoView format, + detail::BasicArgsInterface& argsInterface ); virtual ~BasicContext() = default; public: ContextExecutor& Executor; - Detail::BufferInfoView Format; - Detail::BasicArgsInterface& ArgsInterface; + detail::BufferInfoView Format; + detail::BasicArgsInterface& ArgsInterface; std::int32_t ValuesIndex; public: @@ -80,12 +80,12 @@ namespace StreamFormat::FMT::Context [[nodiscard]] std::expected ParseFormatDataBase(); [[nodiscard]] std::expected ParseFormatDataSpecial(); - [[nodiscard]] std::expected ParseFormatDataSpecial_ShiftType(const Detail::ShiftInfo::ShiftType type); + [[nodiscard]] std::expected ParseFormatDataSpecial_ShiftType(const detail::ShiftInfo::ShiftType type); [[nodiscard]] std::expected ParseFormatDataCustom(); [[nodiscard]] std::expected ParseFormatData(); [[nodiscard]] std::expected ParseVariable(std::int32_t formatIdx); - [[nodiscard]] std::expected Parse(); + [[nodiscard]] std::expected parse(); public: template @@ -93,7 +93,7 @@ namespace StreamFormat::FMT::Context { if (Executor.Data.NextOverride.size() == 0) return func(std::forward(args)...); - Detail::FormatData formatDataCopy = Executor.Data; + detail::FormatData formatDataCopy = Executor.Data; FormatDataApplyNextOverride(); func(std::forward(args)...); Executor.Data = formatDataCopy; @@ -101,13 +101,13 @@ namespace StreamFormat::FMT::Context }; } -namespace StreamFormat::FMT::Context +namespace stream::fmt::context { template BasicContext::BasicContext( ContextExecutor& executor, - Detail::BufferInfoView format, - Detail::BasicArgsInterface& argsInterface + detail::BufferInfoView format, + detail::BasicArgsInterface& argsInterface ) : Executor(executor) , Format{format} @@ -118,20 +118,20 @@ namespace StreamFormat::FMT::Context template [[nodiscard]] std::expected BasicContext::Run() { - while (!Detail::BufferAccess(Format).IsEndOfString()) + while (!detail::BufferAccess(Format).IsEndOfString()) { const TChar* beginContinousString = Format.CurrentPos; std::size_t sizeContinousString = 0; - while (Detail::BufferAccess(Format).IsEndOfString() == false && Detail::BufferTestAccess(Format).IsEqualTo('{') == false) + while (detail::BufferAccess(Format).IsEndOfString() == false && detail::BufferTestAccess(Format).IsEqualTo('{') == false) { ++sizeContinousString; - SF_TRY(Detail::BufferManip(Format).Forward()); + SF_TRY(detail::BufferManip(Format).Forward()); } SF_TRY(Executor.ExecRawString(std::basic_string_view(beginContinousString, sizeContinousString))); - if (Detail::BufferAccess(Format).IsEndOfString() == false && Detail::BufferTestAccess(Format).IsEqualTo('{')) + if (detail::BufferAccess(Format).IsEndOfString() == false && detail::BufferTestAccess(Format).IsEqualTo('{')) { - SF_TRY(Parse()); + SF_TRY(parse()); } } @@ -144,8 +144,8 @@ namespace StreamFormat::FMT::Context if (Executor.Data.NextOverride.size() == 0) { return; } - Detail::BufferInfoView overridePos(Executor.Data.NextOverride); - Detail::BufferInfoView formatPos = Format; + detail::BufferInfoView overridePos(Executor.Data.NextOverride); + detail::BufferInfoView formatPos = Format; Format = overridePos; ParseFormatData(); Format = formatPos; @@ -155,15 +155,15 @@ namespace StreamFormat::FMT::Context template [[nodiscard]] std::expected BasicContext::FormatReadParameter(const T& defaultValue) { - if (!Detail::BufferTestAccess(Format).IsEqualTo('{')) + if (!detail::BufferTestAccess(Format).IsEqualTo('{')) { T t; - SF_TRY(Detail::BufferReadManip(Format).FastReadInteger(t)); + SF_TRY(detail::BufferReadManip(Format).FastReadInteger(t)); return t; } // SubIndex - SF_TRY(Detail::BufferTestManip(Format).SkipOneOf('}')); + SF_TRY(detail::BufferTestManip(Format).SkipOneOf('}')); std::int32_t formatIdx = SF_TRY(GetFormatIndex()); if constexpr (std::is_convertible_v) return ArgsInterface.GetIntAt(formatIdx); diff --git a/src/StreamFormat/FMT/Context/BasicContext/BasicContextParse-impl.h b/src/stream/fmt/context/basic_context/basic_context_parse_impl.h similarity index 66% rename from src/StreamFormat/FMT/Context/BasicContext/BasicContextParse-impl.h rename to src/stream/fmt/context/basic_context/basic_context_parse_impl.h index 6c7d8a38..33b8b5b4 100644 --- a/src/StreamFormat/FMT/Context/BasicContext/BasicContextParse-impl.h +++ b/src/stream/fmt/context/basic_context/basic_context_parse_impl.h @@ -1,49 +1,49 @@ #pragma once -#include "BasicContext.h" +#include "basic_context.h" -#include "StreamFormat/FMT/Buffer/BufferManip.h" -#include "StreamFormat/FMT/Buffer/BufferTestManip.h" -#include "StreamFormat/FMT/Buffer/BufferWriteManip.h" -#include "StreamFormat/FMT/Buffer/BufferReadManip.h" -#include "StreamFormat/FMT/Buffer/FMTBufferOutManip.h" -#include "StreamFormat/FMT/Buffer/FMTBufferReadManip.h" +#include "stream/fmt/buffer/buffer_manip.h" +#include "stream/fmt/buffer/buffer_test_manip.h" +#include "stream/fmt/buffer/buffer_write_manip.h" +#include "stream/fmt/buffer/buffer_read_manip.h" +#include "stream/fmt/buffer/fmt_buffer_out_manip.h" +#include "stream/fmt/buffer/FMTBufferReadManip.h" -namespace StreamFormat::FMT::Context +namespace stream::fmt::context { template [[nodiscard]] std::expected, FMTResult> BasicContext::ParseNextOverrideFormatData() { // TODO: check that function - Detail::BufferTestAccess access(Format); - Detail::BufferTestManip manip(Format); + detail::BufferTestAccess access(Format); + detail::BufferTestManip manip(Format); manip.IgnoreEverySpaces(); - Detail::FMTBufferParamsManip(Format).ParamGoTo('{', '=', ':'); + detail::FMTBufferParamsManip(Format).ParamGoTo('{', '=', ':'); manip.IgnoreEverySpaces(); manip.IgnoreOneOf('=', ':'); manip.IgnoreEverySpaces(); - Detail::FMTBufferParamsManip(Format).ParamGoTo('{'); + detail::FMTBufferParamsManip(Format).ParamGoTo('{'); const TChar* begin = Format.CurrentPos; SF_TRY(manip.SkipOneOf('{')); int scopes = 0; - while (Detail::FMTBufferParamsManip(Format).IsEndOfParameter() == false || scopes > 0) + while (detail::FMTBufferParamsManip(Format).IsEndOfParameter() == false || scopes > 0) { manip.GoTo('\'', '}', '{'); if (access.IsEqualTo('\'')) { - SF_TRY(Detail::BufferManip(Format).Forward()); + SF_TRY(detail::BufferManip(Format).Forward()); manip.GoToForward('\''); } else if (access.IsEqualTo('{')) { - SF_TRY(Detail::BufferManip(Format).Forward()); + SF_TRY(detail::BufferManip(Format).Forward()); scopes++; } else if (scopes > 0 && access.IsEqualTo('}')) { - SF_TRY(Detail::BufferManip(Format).Forward()); + SF_TRY(detail::BufferManip(Format).Forward()); scopes--; } } @@ -55,33 +55,33 @@ namespace StreamFormat::FMT::Context template [[nodiscard]] std::expected BasicContext::ParseFormatDataBase() { - Detail::BufferTestAccess access(Format); + detail::BufferTestAccess access(Format); if (access.IsEqualTo('C')) { - SF_TRY(Detail::BufferManip(Format).Forward()); + SF_TRY(detail::BufferManip(Format).Forward()); SF_TRY(Executor.TextManager.ParseColor(*this)); } else if (access.IsEqualTo('S')) { - SF_TRY(Detail::BufferManip(Format).Forward()); + SF_TRY(detail::BufferManip(Format).Forward()); SF_TRY(Executor.TextManager.ParseStyle(*this)); } else if (access.IsEqualTo('F')) { - SF_TRY(Detail::BufferManip(Format).Forward()); + SF_TRY(detail::BufferManip(Format).Forward()); SF_TRY(Executor.TextManager.ParseFront(*this)); } else if (access.IsEqualTo('K')) { - SF_TRY(Detail::BufferManip(Format).Forward()); + SF_TRY(detail::BufferManip(Format).Forward()); Executor.Data.KeepNewStyle = true; } else if (access.IsEqualTo('N')) { - SF_TRY(Detail::BufferManip(Format).Forward()); + SF_TRY(detail::BufferManip(Format).Forward()); Executor.Data.NextOverride = SF_TRY(ParseNextOverrideFormatData()); } @@ -89,19 +89,19 @@ namespace StreamFormat::FMT::Context } template - [[nodiscard]] std::expected BasicContext::ParseFormatDataSpecial_ShiftType(const Detail::ShiftInfo::ShiftType type) + [[nodiscard]] std::expected BasicContext::ParseFormatDataSpecial_ShiftType(const detail::ShiftInfo::ShiftType type) { Executor.Data.Shift.Type = type; Executor.Data.Shift.Size = SF_TRY(FormatReadParameter(-1)); - if (Detail::BufferTestAccess(Format).IsEqualTo(':')) + if (detail::BufferTestAccess(Format).IsEqualTo(':')) { - SF_TRY(Detail::BufferManip(Format).Forward()); - Executor.Data.Shift.Print.Before = SF_TRY(Detail::BufferManip(Format).GetAndForward()); + SF_TRY(detail::BufferManip(Format).Forward()); + Executor.Data.Shift.Print.Before = SF_TRY(detail::BufferManip(Format).GetAndForward()); Executor.Data.Shift.Print.After = Executor.Data.Shift.Print.Before; - if (Detail::BufferTestAccess(Format).IsEqualTo('|')) + if (detail::BufferTestAccess(Format).IsEqualTo('|')) { - SF_TRY(Detail::BufferManip(Format).Forward()); - Executor.Data.Shift.Print.After = SF_TRY(Detail::BufferManip(Format).GetAndForward()); + SF_TRY(detail::BufferManip(Format).Forward()); + Executor.Data.Shift.Print.After = SF_TRY(detail::BufferManip(Format).GetAndForward()); } } return {}; @@ -110,22 +110,22 @@ namespace StreamFormat::FMT::Context template [[nodiscard]] std::expected BasicContext::ParseFormatDataSpecial() { - Detail::BufferTestAccess access(Format); - Detail::BufferTestManip manip(Format); + detail::BufferTestAccess access(Format); + detail::BufferTestManip manip(Format); if (access.IsEqualTo('{')) { - SF_TRY(Detail::BufferManip(Format).Forward()); + SF_TRY(detail::BufferManip(Format).Forward()); std::int32_t formatIndex = SF_TRY(GetFormatIndex()); bool ableToApply = false; - auto applyFormatData = SF_TRY(ArgsInterface.template GetTypeAt>(formatIndex)); + auto applyFormatData = SF_TRY(ArgsInterface.template GetTypeAt>(formatIndex)); ableToApply |= Executor.Data.TestApply(applyFormatData); - auto applyFormatSpecifier = SF_TRY(ArgsInterface.template GetTypeAt>(formatIndex)); + auto applyFormatSpecifier = SF_TRY(ArgsInterface.template GetTypeAt>(formatIndex)); ableToApply |= Executor.Data.TestApply(applyFormatSpecifier); - auto applyIntegerPrintBase = SF_TRY(ArgsInterface.template GetTypeAt(formatIndex)); + auto applyIntegerPrintBase = SF_TRY(ArgsInterface.template GetTypeAt(formatIndex)); ableToApply |= Executor.Data.TestApply(applyIntegerPrintBase); - auto applyShiftInfo = SF_TRY(ArgsInterface.template GetTypeAt(formatIndex)); + auto applyShiftInfo = SF_TRY(ArgsInterface.template GetTypeAt(formatIndex)); ableToApply |= Executor.Data.TestApply(applyShiftInfo); if (not ableToApply) @@ -135,44 +135,44 @@ namespace StreamFormat::FMT::Context else if (access.IsEqualTo('.')) { - SF_TRY(Detail::BufferManip(Format).Forward()); + SF_TRY(detail::BufferManip(Format).Forward()); Executor.Data.FloatPrecision = SF_TRY(FormatReadParameter(-1)); } else if (access.IsEqualTo('d', 'b', 'B', 'o', 'O', 'x', 'X')) { - auto get = SF_TRY(Detail::BufferManip(Format).GetAndForward()); - Executor.Data.IntegerPrint = static_cast(get); + auto get = SF_TRY(detail::BufferManip(Format).GetAndForward()); + Executor.Data.IntegerPrint = static_cast(get); } else if (access.IsEqualTo('#')) { - SF_TRY(Detail::BufferManip(Format).Forward()); + SF_TRY(detail::BufferManip(Format).Forward()); Executor.Data.PrefixSuffix = true; } else if (access.IsEqualTo('>')) { - SF_TRY(Detail::BufferManip(Format).Forward()); - SF_TRY(ParseFormatDataSpecial_ShiftType(Detail::ShiftInfo::ShiftType::Right)); + SF_TRY(detail::BufferManip(Format).Forward()); + SF_TRY(ParseFormatDataSpecial_ShiftType(detail::ShiftInfo::ShiftType::Right)); } else if (access.IsEqualTo('<')) { - SF_TRY(Detail::BufferManip(Format).Forward()); - SF_TRY(ParseFormatDataSpecial_ShiftType(Detail::ShiftInfo::ShiftType::Left)); + SF_TRY(detail::BufferManip(Format).Forward()); + SF_TRY(ParseFormatDataSpecial_ShiftType(detail::ShiftInfo::ShiftType::Left)); } else if (access.IsEqualTo('^')) { - SF_TRY(Detail::BufferManip(Format).Forward()); + SF_TRY(detail::BufferManip(Format).Forward()); if (access.IsEqualTo('<')) { - SF_TRY(Detail::BufferManip(Format).Forward()); - SF_TRY(ParseFormatDataSpecial_ShiftType(Detail::ShiftInfo::ShiftType::CenterLeft)); + SF_TRY(detail::BufferManip(Format).Forward()); + SF_TRY(ParseFormatDataSpecial_ShiftType(detail::ShiftInfo::ShiftType::CenterLeft)); } else { manip.IgnoreOneOf('>'); - SF_TRY(ParseFormatDataSpecial_ShiftType(Detail::ShiftInfo::ShiftType::CenterRight)); + SF_TRY(ParseFormatDataSpecial_ShiftType(detail::ShiftInfo::ShiftType::CenterRight)); } } @@ -182,39 +182,39 @@ namespace StreamFormat::FMT::Context template [[nodiscard]] std::expected BasicContext::ParseFormatDataCustom() { - Detail::BufferTestAccess access(Format); - Detail::BufferTestManip manip(Format); + detail::BufferTestAccess access(Format); + detail::BufferTestManip manip(Format); std::basic_string_view name = SF_TRY(manip.ViewExec( - [&] -> std::expected { Detail::FMTBufferParamsManip(Format).ParamGoTo(' ', '=', '\'', '{', ','); return {}; } + [&] -> std::expected { detail::FMTBufferParamsManip(Format).ParamGoTo(' ', '=', '\'', '{', ','); return {}; } )); - Detail::FMTBufferParamsManip(Format).ParamGoTo('=', '\'', '{', ','); + detail::FMTBufferParamsManip(Format).ParamGoTo('=', '\'', '{', ','); manip.IgnoreOneOf('='); manip.IgnoreEverySpaces(); if (access.IsEqualTo('\'')) { - SF_TRY(Detail::BufferManip(Format).Forward()); - std::basic_string_view value = SF_TRY(Detail::BufferTestManip(Format).ViewUntil('\'')); - SF_TRY(Executor.Data.Specifiers.Concat(Detail::FormatSpecifier{name, value})); + SF_TRY(detail::BufferManip(Format).Forward()); + std::basic_string_view value = SF_TRY(detail::BufferTestManip(Format).ViewUntil('\'')); + SF_TRY(Executor.Data.Specifiers.Concat(detail::FormatSpecifier{name, value})); } else if (access.IsADigit()) { std::int32_t value = 0; - SF_TRY(Detail::BufferReadManip(Format).FastReadInteger(value)); - SF_TRY(Executor.Data.Specifiers.Concat(Detail::FormatSpecifier{name, value})); + SF_TRY(detail::BufferReadManip(Format).FastReadInteger(value)); + SF_TRY(Executor.Data.Specifiers.Concat(detail::FormatSpecifier{name, value})); } else if (access.IsEqualTo('{')) { - SF_TRY(Detail::BufferManip(Format).Forward()); + SF_TRY(detail::BufferManip(Format).Forward()); std::int32_t idx = SF_TRY(GetFormatIndex()); // TODO / FIXME - // Executor.Data.Specifiers.Concat(Detail::FormatSpecifier{name, GetTypeAtIndexAuto(idx)}); + // Executor.Data.Specifiers.Concat(detail::FormatSpecifier{name, GetTypeAtIndexAuto(idx)}); SF_TRY(manip.SkipOneOf('}')); } else if (access.IsEqualTo(',', '}')) { - SF_TRY(Executor.Data.Specifiers.Concat(Detail::FormatSpecifier{name})); + SF_TRY(Executor.Data.Specifiers.Concat(detail::FormatSpecifier{name})); } return {}; @@ -224,11 +224,11 @@ namespace StreamFormat::FMT::Context template [[nodiscard]] std::expected BasicContext::ParseFormatData() { - Detail::BufferTestAccess access(Format); - Detail::BufferTestManip manip(Format); + detail::BufferTestAccess access(Format); + detail::BufferTestManip manip(Format); Executor.Data.HasSpec = true; - while (Detail::BufferAccess(Format).IsEndOfString() == false && Detail::FMTBufferParamsManip(Format).IsEndOfParameter() == false) + while (detail::BufferAccess(Format).IsEndOfString() == false && detail::FMTBufferParamsManip(Format).IsEndOfParameter() == false) { manip.IgnoreEverySpaces(); @@ -239,8 +239,8 @@ namespace StreamFormat::FMT::Context else { SF_TRY(ParseFormatDataCustom()); } - Detail::FMTBufferParamsManip(Format).ParamGoTo(','); - Detail::BufferTestManip(Format).IgnoreOneOf(','); + detail::FMTBufferParamsManip(Format).ParamGoTo(','); + detail::BufferTestManip(Format).IgnoreOneOf(','); } return {}; } @@ -250,9 +250,9 @@ namespace StreamFormat::FMT::Context [[nodiscard]] std::expected BasicContext::GetFormatIndex_Number() { std::int32_t index = -1; - SF_TRY(Detail::BufferReadManip(Format).FastReadInteger(index)); + SF_TRY(detail::BufferReadManip(Format).FastReadInteger(index)); - if (Detail::BufferTestAccess(Format).IsEqualTo(':') || Detail::BufferTestAccess(Format).IsEqualTo('}')) + if (detail::BufferTestAccess(Format).IsEqualTo(':') || detail::BufferTestAccess(Format).IsEqualTo('}')) { if (index >= 0 && index < ArgsInterface.Size()) { return index; } @@ -264,7 +264,7 @@ namespace StreamFormat::FMT::Context [[nodiscard]] std::expected BasicContext::GetFormatIndex_Name() { std::int32_t index = SF_TRY(ArgsInterface.GetIndexOfCurrentNamedArg(Format)); - if (Detail::BufferTestAccess(Format).IsEqualTo(':') || Detail::BufferTestAccess(Format).IsEqualTo('}')) + if (detail::BufferTestAccess(Format).IsEqualTo(':') || detail::BufferTestAccess(Format).IsEqualTo('}')) { if (index >= 0 && index < ArgsInterface.Size()) { return index; } @@ -275,16 +275,16 @@ namespace StreamFormat::FMT::Context template [[nodiscard]] std::expected BasicContext::GetFormatIndex_SubIndex() { - Detail::BufferTestAccess access(Format); - Detail::BufferTestManip manip(Format); + detail::BufferTestAccess access(Format); + detail::BufferTestManip manip(Format); if (access.IsEqualTo('{')) { - SF_TRY(Detail::BufferManip(Format).Forward()); + SF_TRY(detail::BufferManip(Format).Forward()); std::int32_t recIndex = SF_TRY(GetFormatIndex()); if (access.IsEqualTo('}') && recIndex >= 0 && recIndex < ArgsInterface.Size()) { - SF_TRY(Detail::BufferManip(Format).Forward()); + SF_TRY(detail::BufferManip(Format).Forward()); manip.IgnoreEverySpaces(); if (access.IsEqualTo(':', '}')) { @@ -300,7 +300,7 @@ namespace StreamFormat::FMT::Context template [[nodiscard]] std::expected BasicContext::GetFormatIndex() { - Detail::BufferTestAccess access(Format); + detail::BufferTestAccess access(Format); // I : if there is no number specified : ':' or '}' if (access.IsEqualTo(':') || access.IsEqualTo('}')) @@ -338,13 +338,13 @@ namespace StreamFormat::FMT::Context template [[nodiscard]] std::expected BasicContext::ParseVariable(std::int32_t formatIdx) { - Detail::FormatData saveFormatData = Executor.Data; - Executor.Data = Detail::FormatData{}; - Detail::TextProperties::Properties saveTextProperties = Executor.TextManager.Save(); + detail::FormatData saveFormatData = Executor.Data; + Executor.Data = detail::FormatData{}; + detail::TextProperties::Properties saveTextProperties = Executor.TextManager.Save(); - if (Detail::BufferTestAccess(Format).IsEqualTo(':', '{')) + if (detail::BufferTestAccess(Format).IsEqualTo(':', '{')) { - SF_TRY(Detail::BufferManip(Format).Forward()); + SF_TRY(detail::BufferManip(Format).Forward()); SF_TRY(ParseFormatData()); } @@ -359,14 +359,14 @@ namespace StreamFormat::FMT::Context } template - [[nodiscard]] std::expected BasicContext::Parse() + [[nodiscard]] std::expected BasicContext::parse() { - Detail::BufferManip(Format).Forward(); // Ignore { + detail::BufferManip(Format).Forward(); // Ignore { - if (Detail::BufferTestAccess(Format).IsUpperCase()) + if (detail::BufferTestAccess(Format).IsUpperCase()) { SF_TRY(ParseFormatData()); - return Detail::FMTBufferParamsManip(Format).ParamGoToForward(); // Ignore } + return detail::FMTBufferParamsManip(Format).ParamGoToForward(); // Ignore } } auto formatIdx = GetFormatIndex(); @@ -375,7 +375,7 @@ namespace StreamFormat::FMT::Context if (formatIdx.value() >= 0 && formatIdx.value() < ArgsInterface.Size()) { SF_TRY(ParseVariable(formatIdx.value())); - return Detail::FMTBufferParamsManip(Format).ParamGoToForward(); // Ignore } + return detail::FMTBufferParamsManip(Format).ParamGoToForward(); // Ignore } } } diff --git a/src/stream/fmt/context/basic_context/text_properties_executor.h b/src/stream/fmt/context/basic_context/text_properties_executor.h new file mode 100644 index 00000000..23976091 --- /dev/null +++ b/src/stream/fmt/context/basic_context/text_properties_executor.h @@ -0,0 +1,48 @@ +#pragma once + +#include "stream/fmt/detail/prelude.h" +#include "stream/fmt/text_properties/text_properties.h" + +namespace stream::fmt::detail +{ + class ITextPropertiesExecutor + { + public: + virtual ~ITextPropertiesExecutor() = default; + + public: + virtual void link_to_executor(void* executor) = 0; + + public: + [[nodiscard]] virtual std::expected all_properties_reset() = 0; + + public: + [[nodiscard]] virtual std::expected reset_color() = 0; + [[nodiscard]] virtual std::expected execute_color(const TextProperties::TextColor::BasicColorFG& t) = 0; + [[nodiscard]] virtual std::expected execute_color(const TextProperties::TextColor::BasicColorBG& t) = 0; + [[nodiscard]] virtual std::expected execute_color(const TextProperties::TextColor::BasicColor& t) = 0; + [[nodiscard]] virtual std::expected execute_color(const TextProperties::TextColor::Color24bFG& t) = 0; + [[nodiscard]] virtual std::expected execute_color(const TextProperties::TextColor::Color24bBG& t) = 0; + [[nodiscard]] virtual std::expected execute_color(const TextProperties::TextColor::Color24b& t) = 0; + [[nodiscard]] virtual std::expected execute_color(const TextProperties::TextColor::ColorCubeFG& t) = 0; + [[nodiscard]] virtual std::expected execute_color(const TextProperties::TextColor::ColorCubeBG& t) = 0; + [[nodiscard]] virtual std::expected execute_color(const TextProperties::TextColor::ColorCube& t) = 0; + + public: + [[nodiscard]] virtual std::expected reset_front() = 0; + [[nodiscard]] virtual std::expected ExecuteFront(const TextProperties::TextFront::FrontID& t) = 0; + + public: + [[nodiscard]] virtual std::expected ResetStyle() = 0; + [[nodiscard]] virtual std::expected execute_style(const TextProperties::TextStyle::Intensity& t) = 0; + [[nodiscard]] virtual std::expected execute_style(const TextProperties::TextStyle::Italic& t) = 0; + [[nodiscard]] virtual std::expected execute_style(const TextProperties::TextStyle::Underline& t) = 0; + [[nodiscard]] virtual std::expected execute_style(const TextProperties::TextStyle::UnderlineColor::Color& t) = 0; + [[nodiscard]] virtual std::expected execute_style(const TextProperties::TextStyle::UnderlineColor::ColorCube& t) = 0; + [[nodiscard]] virtual std::expected execute_style(const TextProperties::TextStyle::UnderlineColor::Color24b& t) = 0; + [[nodiscard]] virtual std::expected execute_style(const TextProperties::TextStyle::Blink& t) = 0; + [[nodiscard]] virtual std::expected execute_style(const TextProperties::TextStyle::Inverted& t) = 0; + [[nodiscard]] virtual std::expected execute_style(const TextProperties::TextStyle::Ideogram& t) = 0; + [[nodiscard]] virtual std::expected execute_style(const TextProperties::TextStyle::Script& t) = 0; + }; +} diff --git a/src/StreamFormat/FMT/Context/BasicContext/TextPropertiesManager.cpp b/src/stream/fmt/context/basic_context/text_properties_manager.cpp similarity index 73% rename from src/StreamFormat/FMT/Context/BasicContext/TextPropertiesManager.cpp rename to src/stream/fmt/context/basic_context/text_properties_manager.cpp index 7442c0b1..9aad21eb 100644 --- a/src/StreamFormat/FMT/Context/BasicContext/TextPropertiesManager.cpp +++ b/src/stream/fmt/context/basic_context/text_properties_manager.cpp @@ -1,10 +1,10 @@ -#include "TextPropertiesManager.h" +#include "text_properties_manager.h" -namespace StreamFormat::FMT::Detail +namespace stream::fmt::detail { [[nodiscard]] std::expected TextPropertiesApplyManager::ReloadColorFG(const TextProperties::TextColor::ColorFG& target) { - if (target.Type != m_CurrentContextProperties.Color.Fg.Type) + if (target.Type != m_CurrentContextProperties.color.Fg.Type) { switch (target.Type) { @@ -21,15 +21,15 @@ namespace StreamFormat::FMT::Detail switch (target.Type) { case TextProperties::TextColor::ColorType::BasicColor: - if (m_CurrentContextProperties.Color.Fg.Data.BasicColor != target.Data.BasicColor) + if (m_CurrentContextProperties.color.Fg.Data.BasicColor != target.Data.BasicColor) return ApplyColor(target.Data.BasicColor); break; case TextProperties::TextColor::ColorType::ColorCube: - if (m_CurrentContextProperties.Color.Fg.Data.ColorCube != target.Data.ColorCube) + if (m_CurrentContextProperties.color.Fg.Data.ColorCube != target.Data.ColorCube) return ApplyColor(target.Data.ColorCube); break; case TextProperties::TextColor::ColorType::Color24b: - if (m_CurrentContextProperties.Color.Fg.Data.Color24b != target.Data.Color24b) + if (m_CurrentContextProperties.color.Fg.Data.Color24b != target.Data.Color24b) return ApplyColor(target.Data.Color24b); break; } @@ -39,7 +39,7 @@ namespace StreamFormat::FMT::Detail [[nodiscard]] std::expected TextPropertiesApplyManager::ReloadColorBG(const TextProperties::TextColor::ColorBG& target) { - if (target.Type != m_CurrentContextProperties.Color.Bg.Type) + if (target.Type != m_CurrentContextProperties.color.Bg.Type) { switch (target.Type) { @@ -56,15 +56,15 @@ namespace StreamFormat::FMT::Detail switch (target.Type) { case TextProperties::TextColor::ColorType::BasicColor: - if (m_CurrentContextProperties.Color.Bg.Data.BasicColor != target.Data.BasicColor) + if (m_CurrentContextProperties.color.Bg.Data.BasicColor != target.Data.BasicColor) return ApplyColor(target.Data.BasicColor); break; case TextProperties::TextColor::ColorType::ColorCube: - if (m_CurrentContextProperties.Color.Bg.Data.ColorCube != target.Data.ColorCube) + if (m_CurrentContextProperties.color.Bg.Data.ColorCube != target.Data.ColorCube) return ApplyColor(target.Data.ColorCube); break; case TextProperties::TextColor::ColorType::Color24b: - if (m_CurrentContextProperties.Color.Bg.Data.Color24b != target.Data.Color24b) + if (m_CurrentContextProperties.color.Bg.Data.Color24b != target.Data.Color24b) return ApplyColor(target.Data.Color24b); break; } @@ -74,44 +74,44 @@ namespace StreamFormat::FMT::Detail [[nodiscard]] std::expected TextPropertiesApplyManager::ReloadStyle(const TextProperties::TextStyle::Style& target) { - if (target.Intensity != m_CurrentContextProperties.Style.Intensity) + if (target.Intensity != m_CurrentContextProperties.style.Intensity) { SF_TRY(ApplyStyle(target.Intensity)); - m_CurrentContextProperties.Style.Intensity = target.Intensity; + m_CurrentContextProperties.style.Intensity = target.Intensity; } - if (target.Italic != m_CurrentContextProperties.Style.Italic) + if (target.Italic != m_CurrentContextProperties.style.Italic) { SF_TRY(ApplyStyle(target.Italic)); - m_CurrentContextProperties.Style.Italic = target.Italic; + m_CurrentContextProperties.style.Italic = target.Italic; } - if (target.Blink != m_CurrentContextProperties.Style.Blink) + if (target.Blink != m_CurrentContextProperties.style.Blink) { SF_TRY(ApplyStyle(target.Blink)); - m_CurrentContextProperties.Style.Blink = target.Blink; + m_CurrentContextProperties.style.Blink = target.Blink; } - if (target.Inverted != m_CurrentContextProperties.Style.Inverted) + if (target.Inverted != m_CurrentContextProperties.style.Inverted) { SF_TRY(ApplyStyle(target.Inverted)); - m_CurrentContextProperties.Style.Inverted = target.Inverted; + m_CurrentContextProperties.style.Inverted = target.Inverted; } - if (target.Ideogram != m_CurrentContextProperties.Style.Ideogram) + if (target.Ideogram != m_CurrentContextProperties.style.Ideogram) { SF_TRY(ApplyStyle(target.Ideogram)); - m_CurrentContextProperties.Style.Ideogram = target.Ideogram; + m_CurrentContextProperties.style.Ideogram = target.Ideogram; } - if (target.Script != m_CurrentContextProperties.Style.Script) + if (target.Script != m_CurrentContextProperties.style.Script) { SF_TRY(ApplyStyle(target.Script)); - m_CurrentContextProperties.Style.Script = target.Script; + m_CurrentContextProperties.style.Script = target.Script; } - if (target.Underline != m_CurrentContextProperties.Style.Underline) + if (target.Underline != m_CurrentContextProperties.style.Underline) { SF_TRY(ApplyStyle(target.Underline)); - m_CurrentContextProperties.Style.Underline = target.Underline; + m_CurrentContextProperties.style.Underline = target.Underline; } - if (target.UnderlineColor.Type != m_CurrentContextProperties.Style.UnderlineColor.Type) + if (target.UnderlineColor.Type != m_CurrentContextProperties.style.UnderlineColor.Type) { switch (target.UnderlineColor.Type) { @@ -120,14 +120,14 @@ namespace StreamFormat::FMT::Detail break; case TextProperties::TextStyle::UnderlineColor::ColorType::ColorCube: SF_TRY(ApplyStyle(target.UnderlineColor.Data.ColorCube)); - m_CurrentContextProperties.Style.UnderlineColor.Data.ColorCube = target.UnderlineColor.Data.ColorCube; + m_CurrentContextProperties.style.UnderlineColor.Data.ColorCube = target.UnderlineColor.Data.ColorCube; break; case TextProperties::TextStyle::UnderlineColor::ColorType::Color24b: SF_TRY(ApplyStyle(target.UnderlineColor.Data.Color24b)); - m_CurrentContextProperties.Style.UnderlineColor.Data.Color24b = target.UnderlineColor.Data.Color24b; + m_CurrentContextProperties.style.UnderlineColor.Data.Color24b = target.UnderlineColor.Data.Color24b; break; } - m_CurrentContextProperties.Style.UnderlineColor.Type = target.UnderlineColor.Type; + m_CurrentContextProperties.style.UnderlineColor.Type = target.UnderlineColor.Type; } else { @@ -136,17 +136,17 @@ namespace StreamFormat::FMT::Detail case TextProperties::TextStyle::UnderlineColor::ColorType::Default: break; case TextProperties::TextStyle::UnderlineColor::ColorType::ColorCube: - if (m_CurrentContextProperties.Style.UnderlineColor.Data.ColorCube != target.UnderlineColor.Data.ColorCube) + if (m_CurrentContextProperties.style.UnderlineColor.Data.ColorCube != target.UnderlineColor.Data.ColorCube) { SF_TRY(ApplyStyle(target.UnderlineColor.Data.ColorCube)); - m_CurrentContextProperties.Style.UnderlineColor.Data.ColorCube = target.UnderlineColor.Data.ColorCube; + m_CurrentContextProperties.style.UnderlineColor.Data.ColorCube = target.UnderlineColor.Data.ColorCube; } break; case TextProperties::TextStyle::UnderlineColor::ColorType::Color24b: - if (m_CurrentContextProperties.Style.UnderlineColor.Data.Color24b != target.UnderlineColor.Data.Color24b) + if (m_CurrentContextProperties.style.UnderlineColor.Data.Color24b != target.UnderlineColor.Data.Color24b) { SF_TRY(ApplyStyle(target.UnderlineColor.Data.Color24b)); - m_CurrentContextProperties.Style.UnderlineColor.Data.Color24b = target.UnderlineColor.Data.Color24b; + m_CurrentContextProperties.style.UnderlineColor.Data.Color24b = target.UnderlineColor.Data.Color24b; } break; } @@ -156,11 +156,11 @@ namespace StreamFormat::FMT::Detail [[nodiscard]] std::expected TextPropertiesApplyManager::ReloadFront(const TextProperties::TextFront::Front& target) { - if (m_CurrentContextProperties.Front == target) + if (m_CurrentContextProperties.front == target) return {}; SF_TRY(ApplyFront(target.CurrentID)); - m_CurrentContextProperties.Front = target; + m_CurrentContextProperties.front = target; return {}; } } diff --git a/src/StreamFormat/FMT/Context/BasicContext/TextPropertiesManager.h b/src/stream/fmt/context/basic_context/text_properties_manager.h similarity index 65% rename from src/StreamFormat/FMT/Context/BasicContext/TextPropertiesManager.h rename to src/stream/fmt/context/basic_context/text_properties_manager.h index 53cbbccb..8f4371a6 100644 --- a/src/StreamFormat/FMT/Context/BasicContext/TextPropertiesManager.h +++ b/src/stream/fmt/context/basic_context/text_properties_manager.h @@ -1,13 +1,13 @@ #pragma once -#include "StreamFormat/FMT/Detail/Prelude.h" -#include "ITextPropertiesExecutor.h" -#include "BasicArgsInterface.h" -#include "StreamFormat/FMT/Buffer/BufferInfo.h" -#include "StreamFormat/FMT/Buffer/BufferTestManip.h" -#include "StreamFormat/FMT/Buffer/Utils/BufferUtils.h" - -namespace StreamFormat::FMT::Detail +#include "stream/fmt/detail/prelude.h" +#include "text_properties_executor.h" +#include "basic_args_interface.h" +#include "stream/fmt/buffer/buffer_info.h" +#include "stream/fmt/buffer/buffer_test_manip.h" +#include "stream/fmt/buffer/utils/buffer_utils.h" + +namespace stream::fmt::detail { class TextPropertiesApplyManager { @@ -21,28 +21,28 @@ namespace StreamFormat::FMT::Detail public: template - requires Detail::TextPropertiesColorCanApply + requires detail::TextPropertiesColorCanApply [[nodiscard]] std::expected ApplyColor(const T& modif) { - m_CurrentContextProperties.Color.Apply(modif); - return m_TextPropertiesExecutor.ExecuteColor(modif); + m_CurrentContextProperties.color.Apply(modif); + return m_TextPropertiesExecutor.execute_color(modif); } template - requires Detail::TextPropertiesStyleCanApply + requires detail::TextPropertiesStyleCanApply [[nodiscard]] std::expected ApplyStyle(const T& modif) { - m_CurrentContextProperties.Style.Apply(modif); - return m_TextPropertiesExecutor.ExecuteStyle(modif); + m_CurrentContextProperties.style.Apply(modif); + return m_TextPropertiesExecutor.execute_style(modif); } template - requires Detail::TextPropertiesFrontCanApply + requires detail::TextPropertiesFrontCanApply [[nodiscard]] std::expected ApplyFront(const T& modif) { - m_CurrentContextProperties.Front.Apply(modif); + m_CurrentContextProperties.front.Apply(modif); return m_TextPropertiesExecutor.ExecuteFront(modif); } - [[nodiscard]] std::expected AllPropertiesReset() + [[nodiscard]] std::expected all_properties_reset() { SF_TRY(ApplyColorReset()); SF_TRY(ApplyStyleReset()); @@ -50,22 +50,22 @@ namespace StreamFormat::FMT::Detail } [[nodiscard]] std::expected ApplyColorReset() { - m_CurrentContextProperties.Color.ModifyReset(); - return m_TextPropertiesExecutor.ResetColor(); + m_CurrentContextProperties.color.ModifyReset(); + return m_TextPropertiesExecutor.reset_color(); } [[nodiscard]] std::expected ApplyStyleReset() { - m_CurrentContextProperties.Style.ModifyReset(); + m_CurrentContextProperties.style.ModifyReset(); return m_TextPropertiesExecutor.ResetStyle(); } [[nodiscard]] std::expected ApplyFrontReset() { - m_CurrentContextProperties.Front.ModifyReset(); - return m_TextPropertiesExecutor.ResetFront(); + m_CurrentContextProperties.front.ModifyReset(); + return m_TextPropertiesExecutor.reset_front(); } public: - Detail::TextProperties::Properties Save() { return m_CurrentContextProperties; } + detail::TextProperties::Properties Save() { return m_CurrentContextProperties; } public: [[nodiscard]] std::expected ReloadDefault() @@ -79,107 +79,107 @@ namespace StreamFormat::FMT::Detail SF_TRY(ReloadDefaultColorFG()); return ReloadDefaultColorBG(); } - [[nodiscard]] std::expected ReloadDefaultColorFG() { return ReloadColorFG(Detail::TextProperties::TextColor::ColorFG{}); } - [[nodiscard]] std::expected ReloadDefaultColorBG() { return ReloadColorBG(Detail::TextProperties::TextColor::ColorBG{}); } - [[nodiscard]] std::expected ReloadDefaultStyle() { return ReloadStyle(Detail::TextProperties::TextStyle::Style{}); } - [[nodiscard]] std::expected ReloadDefaultFront() { return ReloadFront(Detail::TextProperties::TextFront::Front{}); } + [[nodiscard]] std::expected ReloadDefaultColorFG() { return ReloadColorFG(detail::TextProperties::TextColor::ColorFG{}); } + [[nodiscard]] std::expected ReloadDefaultColorBG() { return ReloadColorBG(detail::TextProperties::TextColor::ColorBG{}); } + [[nodiscard]] std::expected ReloadDefaultStyle() { return ReloadStyle(detail::TextProperties::TextStyle::Style{}); } + [[nodiscard]] std::expected ReloadDefaultFront() { return ReloadFront(detail::TextProperties::TextFront::Front{}); } - [[nodiscard]] std::expected Reload(const Detail::TextProperties::Properties& target) + [[nodiscard]] std::expected Reload(const detail::TextProperties::Properties& target) { - SF_TRY(ReloadColor(target.Color)); - SF_TRY(ReloadStyle(target.Style)); - return ReloadFront(target.Front); + SF_TRY(ReloadColor(target.color)); + SF_TRY(ReloadStyle(target.style)); + return ReloadFront(target.front); } - [[nodiscard]] std::expected ReloadColor(const Detail::TextProperties::TextColor::Color& target) + [[nodiscard]] std::expected ReloadColor(const detail::TextProperties::TextColor::Color& target) { SF_TRY(ReloadColorFG(target.Fg)); return ReloadColorBG(target.Bg); } - [[nodiscard]] std::expected ReloadColorFG(const Detail::TextProperties::TextColor::ColorFG& target); - [[nodiscard]] std::expected ReloadColorBG(const Detail::TextProperties::TextColor::ColorBG& target); - [[nodiscard]] std::expected ReloadStyle(const Detail::TextProperties::TextStyle::Style& target); - [[nodiscard]] std::expected ReloadFront(const Detail::TextProperties::TextFront::Front& target); + [[nodiscard]] std::expected ReloadColorFG(const detail::TextProperties::TextColor::ColorFG& target); + [[nodiscard]] std::expected ReloadColorBG(const detail::TextProperties::TextColor::ColorBG& target); + [[nodiscard]] std::expected ReloadStyle(const detail::TextProperties::TextStyle::Style& target); + [[nodiscard]] std::expected ReloadFront(const detail::TextProperties::TextFront::Front& target); public: ITextPropertiesExecutor& GetTextPropertiesExecutor() { return m_TextPropertiesExecutor; } - Detail::TextProperties::Properties& GetCurrentContextProperties() { return m_CurrentContextProperties; } + detail::TextProperties::Properties& GetCurrentContextProperties() { return m_CurrentContextProperties; } protected: ITextPropertiesExecutor& m_TextPropertiesExecutor; - Detail::TextProperties::Properties m_CurrentContextProperties; + detail::TextProperties::Properties m_CurrentContextProperties; public: template - requires Detail::TextPropertiesColorCanApply + requires detail::TextPropertiesColorCanApply [[nodiscard]] inline std::expected AskApplyColor(const T& modif) { - if (m_CurrentContextProperties.Color.NeedModif(modif)) + if (m_CurrentContextProperties.color.NeedModif(modif)) return ApplyColor(modif); return {}; } template - requires Detail::TextPropertiesStyleCanApply + requires detail::TextPropertiesStyleCanApply [[nodiscard]] inline std::expected AskApplyStyle(const T& modif) { - if (m_CurrentContextProperties.Style.NeedModif(modif)) + if (m_CurrentContextProperties.style.NeedModif(modif)) return ApplyStyle(modif); return {}; } template - requires Detail::TextPropertiesFrontCanApply + requires detail::TextPropertiesFrontCanApply [[nodiscard]] inline std::expected AskApplyFront(const T& modif) { - if (m_CurrentContextProperties.Front.NeedModif(modif)) + if (m_CurrentContextProperties.front.NeedModif(modif)) return ApplyFront(modif); return {}; } - [[nodiscard]] std::expected AskApplyColor(const Detail::TextProperties::TextColor::BasicColor& modif) + [[nodiscard]] std::expected AskApplyColor(const detail::TextProperties::TextColor::BasicColor& modif) { - if (m_CurrentContextProperties.Color.NeedModif(modif.Fg)) + if (m_CurrentContextProperties.color.NeedModif(modif.Fg)) { - if (m_CurrentContextProperties.Color.NeedModif(modif.Bg)) + if (m_CurrentContextProperties.color.NeedModif(modif.Bg)) return ApplyColor(modif); return ApplyColor(modif.Fg); } - if (m_CurrentContextProperties.Color.NeedModif(modif.Fg)) + if (m_CurrentContextProperties.color.NeedModif(modif.Fg)) return ApplyColor(modif.Bg); return {}; } - [[nodiscard]] std::expected AskApplyColor(const Detail::TextProperties::TextColor::ColorCube& modif) + [[nodiscard]] std::expected AskApplyColor(const detail::TextProperties::TextColor::ColorCube& modif) { - if (m_CurrentContextProperties.Color.NeedModif(modif.Fg)) + if (m_CurrentContextProperties.color.NeedModif(modif.Fg)) { - if (m_CurrentContextProperties.Color.NeedModif(modif)) + if (m_CurrentContextProperties.color.NeedModif(modif)) return ApplyColor(modif); return ApplyColor(modif.Fg); } - if (m_CurrentContextProperties.Color.NeedModif(modif.Fg)) + if (m_CurrentContextProperties.color.NeedModif(modif.Fg)) return ApplyColor(modif.Bg); return {}; } - [[nodiscard]] std::expected AskApplyColor(const Detail::TextProperties::TextColor::Color24b& modif) + [[nodiscard]] std::expected AskApplyColor(const detail::TextProperties::TextColor::Color24b& modif) { - if (m_CurrentContextProperties.Color.NeedModif(modif.Fg)) + if (m_CurrentContextProperties.color.NeedModif(modif.Fg)) { - if (m_CurrentContextProperties.Color.NeedModif(modif)) + if (m_CurrentContextProperties.color.NeedModif(modif)) return ApplyColor(modif); return ApplyColor(modif.Fg); } - if (m_CurrentContextProperties.Color.NeedModif(modif.Fg)) + if (m_CurrentContextProperties.color.NeedModif(modif.Fg)) return ApplyColor(modif.Bg); return {}; } - [[nodiscard]] std::expected AskApplyColor(const Detail::TextProperties::TextColor::ColorFG& modif) { return ReloadColorFG(modif); } - [[nodiscard]] std::expected AskApplyColor(const Detail::TextProperties::TextColor::ColorBG& modif) { return ReloadColorBG(modif); } - [[nodiscard]] std::expected AskApplyColor(const Detail::TextProperties::TextColor::Color& modif) { return ReloadColor(modif); } + [[nodiscard]] std::expected AskApplyColor(const detail::TextProperties::TextColor::ColorFG& modif) { return ReloadColorFG(modif); } + [[nodiscard]] std::expected AskApplyColor(const detail::TextProperties::TextColor::ColorBG& modif) { return ReloadColorBG(modif); } + [[nodiscard]] std::expected AskApplyColor(const detail::TextProperties::TextColor::Color& modif) { return ReloadColor(modif); } }; template @@ -208,17 +208,17 @@ namespace StreamFormat::FMT::Detail }; } -namespace StreamFormat::FMT::Detail +namespace stream::fmt::detail { template template - [[nodiscard]] std::expected Detail::TextPropertiesManager::GetColorCode(BufferInfoView& format) + [[nodiscard]] std::expected detail::TextPropertiesManager::GetColorCode(BufferInfoView& format) { static constexpr std::string_view colorCode[] = {"black", "red", "green", "yellow", "blue", "magenta", "cyan", "white", " ", "default"}; bool bright = SF_TRY(BufferTestManip(format).IsEqualToForward('+')); std::uint8_t step = static_cast(bright ? T::BaseBStep : T::BaseStep); - std::uint8_t code = (std::uint8_t)SF_TRY(BufferUtilsManip(format).GetWordFromList(colorCode));; + std::uint8_t code = (std::uint8_t)SF_TRY(BufferUtilsManip(format).get_word_from_list(colorCode));; return static_cast(code + step); } } diff --git a/src/StreamFormat/FMT/Context/BasicContext/TextPropertiesManager-impl.h b/src/stream/fmt/context/basic_context/text_properties_manager_impl.h similarity index 60% rename from src/StreamFormat/FMT/Context/BasicContext/TextPropertiesManager-impl.h rename to src/stream/fmt/context/basic_context/text_properties_manager_impl.h index e0175029..5d9629cf 100644 --- a/src/StreamFormat/FMT/Context/BasicContext/TextPropertiesManager-impl.h +++ b/src/stream/fmt/context/basic_context/text_properties_manager_impl.h @@ -1,74 +1,74 @@ #pragma once -#include "TextPropertiesManager.h" +#include "text_properties_manager.h" -#include "StreamFormat/FMT/Buffer/BufferManip.h" -#include "StreamFormat/FMT/Buffer/BufferOutManip.h" -#include "StreamFormat/FMT/Buffer/BufferTestManip.h" -#include "StreamFormat/FMT/Buffer/FMTBufferOutManip.h" -#include "StreamFormat/FMT/Buffer/Utils/BufferUtils.h" +#include "stream/fmt/buffer/buffer_manip.h" +#include "stream/fmt/buffer/buffer_out_manip.h" +#include "stream/fmt/buffer/buffer_test_manip.h" +#include "stream/fmt/buffer/fmt_buffer_out_manip.h" +#include "stream/fmt/buffer/utils/buffer_utils.h" -namespace StreamFormat::FMT::Detail +namespace stream::fmt::detail { template - [[nodiscard]] std::expected Detail::TextPropertiesManager::ApplyColorOnIndex(Context::BasicContext& context, std::int32_t index) + [[nodiscard]] std::expected detail::TextPropertiesManager::ApplyColorOnIndex(Context::BasicContext& context, std::int32_t index) { - SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextColor::Color& data) -> std::expected { this->ReloadColor(data); return {}; })); - SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextColor::BasicColorFG& data) -> std::expected { this->AskApplyColor(data); return {}; })); - SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextColor::BasicColorBG& data) -> std::expected { this->AskApplyColor(data); return {}; })); - SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextColor::ColorCubeFG& data) -> std::expected { this->AskApplyColor(data); return {}; })); - SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextColor::ColorCubeBG& data) -> std::expected { this->AskApplyColor(data); return {}; })); - SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextColor::Color24bFG& data) -> std::expected { this->AskApplyColor(data); return {}; })); - SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextColor::Color24bBG& data) -> std::expected { this->AskApplyColor(data); return {}; })); + SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( + index, [this](const detail::TextProperties::TextColor::Color& data) -> std::expected { this->ReloadColor(data); return {}; })); + SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( + index, [this](const detail::TextProperties::TextColor::BasicColorFG& data) -> std::expected { this->AskApplyColor(data); return {}; })); + SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( + index, [this](const detail::TextProperties::TextColor::BasicColorBG& data) -> std::expected { this->AskApplyColor(data); return {}; })); + SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( + index, [this](const detail::TextProperties::TextColor::ColorCubeFG& data) -> std::expected { this->AskApplyColor(data); return {}; })); + SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( + index, [this](const detail::TextProperties::TextColor::ColorCubeBG& data) -> std::expected { this->AskApplyColor(data); return {}; })); + SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( + index, [this](const detail::TextProperties::TextColor::Color24bFG& data) -> std::expected { this->AskApplyColor(data); return {}; })); + SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( + index, [this](const detail::TextProperties::TextColor::Color24bBG& data) -> std::expected { this->AskApplyColor(data); return {}; })); return {}; } template - [[nodiscard]] std::expected Detail::TextPropertiesManager::ApplyFrontOnIndex(Context::BasicContext& context, std::int32_t index) + [[nodiscard]] std::expected detail::TextPropertiesManager::ApplyFrontOnIndex(Context::BasicContext& context, std::int32_t index) { - SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextFront::Front& data) -> std::expected { this->ReloadFront(data); return {}; })); - SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextFront::FrontID& data) -> std::expected { this->AskApplyFront(data); return {}; })); + SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( + index, [this](const detail::TextProperties::TextFront::Front& data) -> std::expected { this->ReloadFront(data); return {}; })); + SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( + index, [this](const detail::TextProperties::TextFront::FrontID& data) -> std::expected { this->AskApplyFront(data); return {}; })); return {}; } template - [[nodiscard]] std::expected Detail::TextPropertiesManager::ApplyStyleOnIndex(Context::BasicContext& context, std::int32_t index) + [[nodiscard]] std::expected detail::TextPropertiesManager::ApplyStyleOnIndex(Context::BasicContext& context, std::int32_t index) { - SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextStyle::Style& data) -> std::expected { return this->ReloadStyle(data); return {}; })); - SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextStyle::Intensity& data) -> std::expected { return this->AskApplyStyle(data); return {}; })); - SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextStyle::Italic& data) -> std::expected { return this->AskApplyStyle(data); return {}; })); - SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextStyle::Underline& data) -> std::expected { return this->AskApplyStyle(data); return {}; })); - SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextStyle::Blink& data) -> std::expected { return this->AskApplyStyle(data); return {}; })); - SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextStyle::Inverted& data) -> std::expected { return this->AskApplyStyle(data); return {}; })); - SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextStyle::Ideogram& data) -> std::expected { return this->AskApplyStyle(data); return {}; })); - SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextStyle::Script& data) -> std::expected { return this->AskApplyStyle(data); return {}; })); - - SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextStyle::UnderlineColor::ColorCube& data) -> std::expected { this->AskApplyStyle(data); return {}; })); - SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const Detail::TextProperties::TextStyle::UnderlineColor::Color24b& data) -> std::expected { this->AskApplyStyle(data); return {}; })); + SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( + index, [this](const detail::TextProperties::TextStyle::Style& data) -> std::expected { return this->ReloadStyle(data); return {}; })); + SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( + index, [this](const detail::TextProperties::TextStyle::Intensity& data) -> std::expected { return this->AskApplyStyle(data); return {}; })); + SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( + index, [this](const detail::TextProperties::TextStyle::Italic& data) -> std::expected { return this->AskApplyStyle(data); return {}; })); + SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( + index, [this](const detail::TextProperties::TextStyle::Underline& data) -> std::expected { return this->AskApplyStyle(data); return {}; })); + SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( + index, [this](const detail::TextProperties::TextStyle::Blink& data) -> std::expected { return this->AskApplyStyle(data); return {}; })); + SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( + index, [this](const detail::TextProperties::TextStyle::Inverted& data) -> std::expected { return this->AskApplyStyle(data); return {}; })); + SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( + index, [this](const detail::TextProperties::TextStyle::Ideogram& data) -> std::expected { return this->AskApplyStyle(data); return {}; })); + SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( + index, [this](const detail::TextProperties::TextStyle::Script& data) -> std::expected { return this->AskApplyStyle(data); return {}; })); + + SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( + index, [this](const detail::TextProperties::TextStyle::UnderlineColor::ColorCube& data) -> std::expected { this->AskApplyStyle(data); return {}; })); + SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( + index, [this](const detail::TextProperties::TextStyle::UnderlineColor::Color24b& data) -> std::expected { this->AskApplyStyle(data); return {}; })); return {}; } template - [[nodiscard]] std::expected Detail::TextPropertiesManager::ParseColor(Context::BasicContext& context) + [[nodiscard]] std::expected detail::TextPropertiesManager::ParseColor(Context::BasicContext& context) { if (BufferTestAccess(context.Format).IsEqualTo(':')) { @@ -91,7 +91,7 @@ namespace StreamFormat::FMT::Detail BufferTestManip(context.Format).IgnoreEverySpaces(); auto colorBg = GetColorCode(context.Format); if (colorBg.has_value() && colorFg.has_value()) - { return AskApplyColor(Detail::TextProperties::TextColor::BasicColor{colorFg.value(), colorBg.value()}); } + { return AskApplyColor(detail::TextProperties::TextColor::BasicColor{colorFg.value(), colorBg.value()}); } else { return ReloadDefaultColor(); } } @@ -110,7 +110,7 @@ namespace StreamFormat::FMT::Detail } template - [[nodiscard]] std::expected Detail::TextPropertiesManager::ParseStyle(Context::BasicContext& context) + [[nodiscard]] std::expected detail::TextPropertiesManager::ParseStyle(Context::BasicContext& context) { if (BufferTestAccess(context.Format).IsEqualTo(':')) { @@ -146,70 +146,70 @@ namespace StreamFormat::FMT::Detail } template - [[nodiscard]] std::expected Detail::TextPropertiesManager::ParseStyleNamed(BufferInfoView& format) + [[nodiscard]] std::expected detail::TextPropertiesManager::ParseStyleNamed(BufferInfoView& format) { - Detail::BufferUtilsManip utils(format); + detail::BufferUtilsManip utils(format); - static constexpr std::pair, Detail::TextProperties::TextStyle::Intensity> styleIntensity[] = { - {"bold", Detail::TextProperties::TextStyle::Intensity::Bold}, - {"dim", Detail::TextProperties::TextStyle::Intensity::Dim}, - {"n-intensity", Detail::TextProperties::TextStyle::Intensity::Normal} + static constexpr std::pair, detail::TextProperties::TextStyle::Intensity> styleIntensity[] = { + {"bold", detail::TextProperties::TextStyle::Intensity::Bold}, + {"dim", detail::TextProperties::TextStyle::Intensity::Dim}, + {"n-intensity", detail::TextProperties::TextStyle::Intensity::Normal} }; - static constexpr std::pair, Detail::TextProperties::TextStyle::Italic> styleItalic[] = { - {"italic", Detail::TextProperties::TextStyle::Italic::Enable}, - {"n-italic", Detail::TextProperties::TextStyle::Italic::Disable} + static constexpr std::pair, detail::TextProperties::TextStyle::Italic> styleItalic[] = { + {"italic", detail::TextProperties::TextStyle::Italic::Enable}, + {"n-italic", detail::TextProperties::TextStyle::Italic::Disable} }; // TODO: magic values - static constexpr typename std::pair, Detail::TextProperties::TextStyle::Underline> styleUnderline[] = { - {"underlined", Detail::TextProperties::TextStyle::Underline::Underlined}, - {"d-underlined", Detail::TextProperties::TextStyle::Underline::DoubleUnerlined}, - {"n-underlined", Detail::TextProperties::TextStyle::Underline::Disable}, - {"c-underlined", Detail::TextProperties::TextStyle::Underline::SelectUnderlinedColor}}; - - static constexpr typename std::pair, Detail::TextProperties::TextStyle::Blink> styleBlink[] = {{"slowblink", Detail::TextProperties::TextStyle::Blink::SlowBlink}, - {"fastblink", Detail::TextProperties::TextStyle::Blink::FastBlink}, - {"n-blink", Detail::TextProperties::TextStyle::Blink::Disable}}; - - static constexpr typename std::pair, Detail::TextProperties::TextStyle::Inverted> styleInverted[] = { - {"inverted", Detail::TextProperties::TextStyle::Inverted::Enable}, - {"n-inverted", Detail::TextProperties::TextStyle::Inverted::Disable}, + static constexpr typename std::pair, detail::TextProperties::TextStyle::Underline> styleUnderline[] = { + {"underlined", detail::TextProperties::TextStyle::Underline::Underlined}, + {"d-underlined", detail::TextProperties::TextStyle::Underline::DoubleUnerlined}, + {"n-underlined", detail::TextProperties::TextStyle::Underline::Disable}, + {"c-underlined", detail::TextProperties::TextStyle::Underline::SelectUnderlinedColor}}; + + static constexpr typename std::pair, detail::TextProperties::TextStyle::Blink> styleBlink[] = {{"slowblink", detail::TextProperties::TextStyle::Blink::SlowBlink}, + {"fastblink", detail::TextProperties::TextStyle::Blink::FastBlink}, + {"n-blink", detail::TextProperties::TextStyle::Blink::Disable}}; + + static constexpr typename std::pair, detail::TextProperties::TextStyle::Inverted> styleInverted[] = { + {"inverted", detail::TextProperties::TextStyle::Inverted::Enable}, + {"n-inverted", detail::TextProperties::TextStyle::Inverted::Disable}, }; - static constexpr typename std::pair, Detail::TextProperties::TextStyle::Ideogram> styleIdeogram[] = { - {"i-underlined", Detail::TextProperties::TextStyle::Ideogram::Underlined}, {"i-d-underlined", Detail::TextProperties::TextStyle::Ideogram::DoubleUnderlined}, - {"i-overlined", Detail::TextProperties::TextStyle::Ideogram::Overlined}, {"i-d-overlined", Detail::TextProperties::TextStyle::Ideogram::DoubleOverlined}, - {"i-stress", Detail::TextProperties::TextStyle::Ideogram::StressMarking}, {"n-i", Detail::TextProperties::TextStyle::Ideogram::AllDisable}, + static constexpr typename std::pair, detail::TextProperties::TextStyle::Ideogram> styleIdeogram[] = { + {"i-underlined", detail::TextProperties::TextStyle::Ideogram::Underlined}, {"i-d-underlined", detail::TextProperties::TextStyle::Ideogram::DoubleUnderlined}, + {"i-overlined", detail::TextProperties::TextStyle::Ideogram::Overlined}, {"i-d-overlined", detail::TextProperties::TextStyle::Ideogram::DoubleOverlined}, + {"i-stress", detail::TextProperties::TextStyle::Ideogram::StressMarking}, {"n-i", detail::TextProperties::TextStyle::Ideogram::AllDisable}, }; - static constexpr typename std::pair, Detail::TextProperties::TextStyle::Script> styleScript[] = { - {"superscript", Detail::TextProperties::TextStyle::Script::Superscript}, - {"subscript", Detail::TextProperties::TextStyle::Script::Subscript}, - {"n-script", Detail::TextProperties::TextStyle::Script::AllDisable}}; - - std::uint8_t code = (std::uint8_t)SF_TRY(BufferUtilsManip(format).GetWordFromDictPairs(styleIntensity)); - if (code != 255) return ApplyStyle(Detail::TextProperties::TextStyle::Intensity{code}); - code = (std::uint8_t)SF_TRY(BufferUtilsManip(format).GetWordFromDictPairs(styleItalic)); - if (code != 255) return ApplyStyle(Detail::TextProperties::TextStyle::Italic{code}); - code = (std::uint8_t)SF_TRY(BufferUtilsManip(format).GetWordFromDictPairs(styleBlink)); - if (code != 255) return ApplyStyle(Detail::TextProperties::TextStyle::Blink{code}); - code = (std::uint8_t)SF_TRY(BufferUtilsManip(format).GetWordFromDictPairs(styleInverted)); - if (code != 255) return ApplyStyle(Detail::TextProperties::TextStyle::Inverted{code}); - code = (std::uint8_t)SF_TRY(BufferUtilsManip(format).GetWordFromDictPairs(styleIdeogram)); - if (code != 255) return ApplyStyle(Detail::TextProperties::TextStyle::Ideogram{code}); - code = (std::uint8_t)SF_TRY(BufferUtilsManip(format).GetWordFromDictPairs(styleScript)); - if (code != 255) return ApplyStyle(Detail::TextProperties::TextStyle::Script{code}); - - code = (std::uint8_t)SF_TRY(BufferUtilsManip(format).GetWordFromDictPairs(styleUnderline)); + static constexpr typename std::pair, detail::TextProperties::TextStyle::Script> styleScript[] = { + {"superscript", detail::TextProperties::TextStyle::Script::Superscript}, + {"subscript", detail::TextProperties::TextStyle::Script::Subscript}, + {"n-script", detail::TextProperties::TextStyle::Script::AllDisable}}; + + std::uint8_t code = (std::uint8_t)SF_TRY(BufferUtilsManip(format).get_word_from_dict_pairs(styleIntensity)); + if (code != 255) return ApplyStyle(detail::TextProperties::TextStyle::Intensity{code}); + code = (std::uint8_t)SF_TRY(BufferUtilsManip(format).get_word_from_dict_pairs(styleItalic)); + if (code != 255) return ApplyStyle(detail::TextProperties::TextStyle::Italic{code}); + code = (std::uint8_t)SF_TRY(BufferUtilsManip(format).get_word_from_dict_pairs(styleBlink)); + if (code != 255) return ApplyStyle(detail::TextProperties::TextStyle::Blink{code}); + code = (std::uint8_t)SF_TRY(BufferUtilsManip(format).get_word_from_dict_pairs(styleInverted)); + if (code != 255) return ApplyStyle(detail::TextProperties::TextStyle::Inverted{code}); + code = (std::uint8_t)SF_TRY(BufferUtilsManip(format).get_word_from_dict_pairs(styleIdeogram)); + if (code != 255) return ApplyStyle(detail::TextProperties::TextStyle::Ideogram{code}); + code = (std::uint8_t)SF_TRY(BufferUtilsManip(format).get_word_from_dict_pairs(styleScript)); + if (code != 255) return ApplyStyle(detail::TextProperties::TextStyle::Script{code}); + + code = (std::uint8_t)SF_TRY(BufferUtilsManip(format).get_word_from_dict_pairs(styleUnderline)); if (code != 255) { - if (code == (std::uint8_t)Detail::TextProperties::TextStyle::Underline::SelectUnderlinedColor) + if (code == (std::uint8_t)detail::TextProperties::TextStyle::Underline::SelectUnderlinedColor) { - Detail::TextProperties::TextStyle::UnderlineColor::ColorCube underlineColor = SF_TRY(SelectUnderlinedColorStyle(format)); + detail::TextProperties::TextStyle::UnderlineColor::ColorCube underlineColor = SF_TRY(SelectUnderlinedColorStyle(format)); return ApplyStyle(underlineColor); } - return ApplyStyle(Detail::TextProperties::TextStyle::Underline{code}); + return ApplyStyle(detail::TextProperties::TextStyle::Underline{code}); } return {}; } @@ -223,7 +223,7 @@ namespace StreamFormat::FMT::Detail } template - [[nodiscard]] std::expected Detail::TextPropertiesManager::ParseFront(Context::BasicContext& context) + [[nodiscard]] std::expected detail::TextPropertiesManager::ParseFront(Context::BasicContext& context) { static constexpr std::string_view frontCode[] = {"default", "front0", "front1", "front2", "front3", "front4", "front5", "front6", "front7", "front8", "front9"}; @@ -232,7 +232,7 @@ namespace StreamFormat::FMT::Detail SF_TRY(BufferManip(context.Format).Forward()); BufferTestManip(context.Format).IgnoreEverySpaces(); - Detail::TextProperties::TextFront::FrontID frontID = (std::uint8_t)SF_TRY(BufferUtilsManip(context.Format).GetWordFromList(frontCode)); + detail::TextProperties::TextFront::FrontID frontID = (std::uint8_t)SF_TRY(BufferUtilsManip(context.Format).get_word_from_list(frontCode)); return ApplyFront(frontID); } else diff --git a/src/StreamFormat/FMT/Context/FormatterExecutor/BasicFormatterExecutor.h b/src/stream/fmt/context/formatter_executor/basic_formatter_executor.h similarity index 69% rename from src/StreamFormat/FMT/Context/FormatterExecutor/BasicFormatterExecutor.h rename to src/stream/fmt/context/formatter_executor/basic_formatter_executor.h index a43f5acc..d9c557dc 100644 --- a/src/StreamFormat/FMT/Context/FormatterExecutor/BasicFormatterExecutor.h +++ b/src/stream/fmt/context/formatter_executor/basic_formatter_executor.h @@ -1,18 +1,18 @@ #pragma once -#include "StreamFormat/FMT/Context/BasicContext/BasicContext.h" +#include "stream/fmt/context/basic_context/basic_context.h" -#include "StreamFormat/FMT/Buffer/FMTBufferOutManip.h" -#include "StreamFormat/FMT/Buffer/BufferWriteManip.h" +#include "stream/fmt/buffer/fmt_buffer_out_manip.h" +#include "stream/fmt/buffer/buffer_write_manip.h" -#include "FormatterType.h" -#include "IndexArgs.h" -#include "NamedArgs.h" -#include "STDEnumerable.h" +#include "formatter_type.h" +#include "index_args.h" +#include "named_args.h" +#include "std_enumerable.h" -#include "FormatterArgs.h" +#include "formatter_args.h" -namespace StreamFormat::FMT::Context +namespace stream::fmt::context { enum class EndOfStringCharMode { @@ -29,13 +29,13 @@ namespace StreamFormat::FMT::Context using M_Type = BasicFormatterExecutor; public: - BasicFormatterExecutor(Detail::FMTBufferOutInfo& bufferOut, Detail::ITextPropertiesExecutor& textPropertiesExecutor); + BasicFormatterExecutor(detail::FMTBufferOutInfo& bufferOut, detail::ITextPropertiesExecutor& textPropertiesExecutor); ~BasicFormatterExecutor() override = default; [[nodiscard]] std::expected Terminate(); public: - Detail::FMTBufferOutInfo& BufferOut; + detail::FMTBufferOutInfo& BufferOut; EndOfStringCharMode EndOfStringChar = EndOfStringCharMode::Optional; using ContextExecutor::Data; @@ -44,13 +44,13 @@ namespace StreamFormat::FMT::Context protected: [[nodiscard]] std::expected ExecRawString(std::basic_string_view sv) override { - return Detail::BufferWriteManip(BufferOut).FastWriteString(sv); + return detail::BufferWriteManip(BufferOut).FastWriteString(sv); } [[nodiscard]] std::expected ExecSettings() override; public: template - [[nodiscard]] std::expected Run_(Detail::BufferInfoView format, Args&&... args); + [[nodiscard]] std::expected Run_(detail::BufferInfoView format, Args&&... args); template [[nodiscard]] std::expected Run(Format&& format, Args&&... args); @@ -58,7 +58,7 @@ namespace StreamFormat::FMT::Context template [[nodiscard]] inline std::expected WriteType(Type&& type, Rest&&... rest) { - auto&& formatErr = FormatterType>::Type, M_Type>::Format(std::forward(type), *this); + auto&& formatErr = FormatterType>::Type, M_Type>::format(std::forward(type), *this); SF_TRY(formatErr); if constexpr (sizeof...(rest) > 0) { SF_TRY(WriteType(std::forward(rest)...)); } @@ -67,23 +67,23 @@ namespace StreamFormat::FMT::Context }; } -namespace StreamFormat::FMT::Context +namespace stream::fmt::context { template - BasicFormatterExecutor::BasicFormatterExecutor(Detail::FMTBufferOutInfo& bufferOut, Detail::ITextPropertiesExecutor& textPropertiesExecutor) + BasicFormatterExecutor::BasicFormatterExecutor(detail::FMTBufferOutInfo& bufferOut, detail::ITextPropertiesExecutor& textPropertiesExecutor) : ContextExecutor(textPropertiesExecutor) , BufferOut(bufferOut) { - textPropertiesExecutor.LinkToExecutor(this); + textPropertiesExecutor.link_to_executor(this); } template [[nodiscard]] std::expected BasicFormatterExecutor::Terminate() { - Detail::BufferOutManip(BufferOut).ComputeGeneratedSize(); + detail::BufferOutManip(BufferOut).ComputeGeneratedSize(); // End char not included in buffer manager context to deduce size correctly - auto res = Detail::BufferOutManip(BufferOut).Pushback('\0'); + auto res = detail::BufferOutManip(BufferOut).Pushback('\0'); if (EndOfStringChar == EndOfStringCharMode::Forced) { SF_TRY(res); } @@ -102,11 +102,11 @@ namespace StreamFormat::FMT::Context template template - [[nodiscard]] std::expected BasicFormatterExecutor::Run_(Detail::BufferInfoView format, Args&&... args) + [[nodiscard]] std::expected BasicFormatterExecutor::Run_(detail::BufferInfoView format, Args&&... args) { - auto argsInterface = Detail::FormatterArgsInterface, Args...>(*this, std::forward(args)...); + auto argsInterface = detail::FormatterArgsInterface, Args...>(*this, std::forward(args)...); - Detail::TextProperties::Properties saveTextProperties = TextManager.Save(); + detail::TextProperties::Properties saveTextProperties = TextManager.Save(); Context::BasicContext context(*this, format, argsInterface); SF_TRY(context.Run()); return TextManager.Reload(saveTextProperties); @@ -116,7 +116,7 @@ namespace StreamFormat::FMT::Context template [[nodiscard]] std::expected BasicFormatterExecutor::Run(Format&& formatInput, Args&&... args) { - return Run_(Detail::BufferInfoView{formatInput}, std::forward(args)...); + return Run_(detail::BufferInfoView{formatInput}, std::forward(args)...); } } diff --git a/src/StreamFormat/FMT/Context/FormatterExecutor/FormatBasics-impl.h b/src/stream/fmt/context/formatter_executor/format_basics_impl.h similarity index 63% rename from src/StreamFormat/FMT/Context/FormatterExecutor/FormatBasics-impl.h rename to src/stream/fmt/context/formatter_executor/format_basics_impl.h index 6183c36d..14717047 100644 --- a/src/StreamFormat/FMT/Context/FormatterExecutor/FormatBasics-impl.h +++ b/src/stream/fmt/context/formatter_executor/format_basics_impl.h @@ -1,19 +1,19 @@ #pragma once -#include "BasicFormatterExecutor.h" +#include "basic_formatter_executor.h" -#include "StreamFormat/FMT/Buffer/FMTBufferWriteManip.h" +#include "stream/fmt/buffer/FMTBufferWriteManip.h" -namespace StreamFormat::FMT +namespace stream::fmt { //---------------------------------------------// //----------------- Internals -----------------// //---------------------------------------------// template - struct FormatterType, FormatterExecutor> + struct FormatterType, FormatterExecutor> { - [[nodiscard]] static std::expected Format(const typename FormatterExecutor::Detail::template FormatSpecifier& specifier, FormatterExecutor& executor) + [[nodiscard]] static std::expected format(const typename FormatterExecutor::detail::template FormatSpecifier& specifier, FormatterExecutor& executor) { if (specifier.ValueIsText) { SF_TRY(executor.Run("{ '{}', '{}' }", specifier.Name, specifier.AsText)); } @@ -27,7 +27,7 @@ namespace StreamFormat::FMT //----------------- Forwarders -----------------// //----------------------------------------------// - namespace Detail::Forwarders + namespace detail::Forwarders { template [[nodiscard]] std::expected FormatObjectArray(const T* const buffer, std::size_t totalsize, FormatterExecutor& executor) @@ -41,7 +41,7 @@ namespace StreamFormat::FMT if (size == std::numeric_limits::max()) { return std::unexpected(FMTResult::GivenArgs_UnableToDeduceSize); } - SF_TRY(Detail::BufferWriteManip(executor.BufferOut).FastWriteString(executor.Data.Specifiers.GetAsText("begin", STDEnumerableUtility::DefaultBegin))); + SF_TRY(detail::BufferWriteManip(executor.buffer_out).FastWriteString(executor.Data.Specifiers.GetAsText("begin", STDEnumerableUtility::DefaultBegin))); std::basic_string_view join = executor.Data.Specifiers.GetAsText("join", STDEnumerableUtility::DefaultJoin); @@ -54,11 +54,11 @@ namespace StreamFormat::FMT if (first) { first = false; } else - { SF_TRY(Detail::FMTBufferWriteManip(executor.BufferOut).WriteIndentString(join)); } + { SF_TRY(detail::FMTBufferWriteManip(executor.buffer_out).WriteIndentString(join)); } SF_TRY(executor.WriteType(*itbegin++)); } - return Detail::BufferWriteManip(executor.BufferOut).FastWriteString(executor.Data.Specifiers.GetAsText("end", STDEnumerableUtility::DefaultEnd)); + return detail::BufferWriteManip(executor.buffer_out).FastWriteString(executor.Data.Specifiers.GetAsText("end", STDEnumerableUtility::DefaultEnd)); } template @@ -77,18 +77,18 @@ namespace StreamFormat::FMT // TODO: current indent ignore shift if (executor.Data.Specifiers.Has("indent")) - return Detail::FMTBufferWriteManip(executor.BufferOut).WriteIndentCharPtr(begin, size); + return detail::FMTBufferWriteManip(executor.buffer_out).WriteIndentCharPtr(begin, size); if (executor.Data.PrefixSuffix) - { SF_TRY(Detail::BufferOutManip(executor.BufferOut).Pushback('\"')); } + { SF_TRY(detail::BufferOutManip(executor.buffer_out).Pushback('\"')); } if (executor.Data.HasSpec == false) - { SF_TRY(Detail::BufferWriteManip(executor.BufferOut).FastWriteCharArray(begin, size)); } + { SF_TRY(detail::BufferWriteManip(executor.buffer_out).FastWriteCharArray(begin, size)); } else - { SF_TRY(Detail::FMTBufferWriteManip(executor.BufferOut).WriteCharPtr(begin, size, executor.Data.Shift)); } + { SF_TRY(detail::FMTBufferWriteManip(executor.buffer_out).WriteCharPtr(begin, size, executor.Data.Shift)); } if (executor.Data.PrefixSuffix) - { SF_TRY(Detail::BufferOutManip(executor.BufferOut).Pushback('\"')); } + { SF_TRY(detail::BufferOutManip(executor.buffer_out).Pushback('\"')); } return {}; } @@ -102,21 +102,21 @@ namespace StreamFormat::FMT template struct FormatterType { - [[nodiscard]] static std::expected Format(const bool t, FormatterExecutor& executor) + [[nodiscard]] static std::expected format(const bool t, FormatterExecutor& executor) { if (executor.Data.PrefixSuffix) { if (t == true) - return Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("True"); + return detail::BufferWriteManip(executor.buffer_out).FastWriteStringLitteral("True"); else - return Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("False"); + return detail::BufferWriteManip(executor.buffer_out).FastWriteStringLitteral("False"); } else { if (t == true) - return Detail::BufferOutManip(executor.BufferOut).Pushback('1'); + return detail::BufferOutManip(executor.buffer_out).Pushback('1'); else - return Detail::BufferOutManip(executor.BufferOut).Pushback('0'); + return detail::BufferOutManip(executor.buffer_out).Pushback('0'); } return {}; @@ -124,27 +124,27 @@ namespace StreamFormat::FMT }; template - requires (std::is_integral_v && !std::is_floating_point_v && !Detail::IsCharType::Value) + requires (std::is_integral_v && !std::is_floating_point_v && !detail::IsCharType::Value) struct FormatterType { - [[nodiscard]] static inline std::expected Format(const T t, FormatterExecutor& executor) - { return Detail::FMTBufferWriteManip(executor.BufferOut).WriteIntegerFormatData(t, executor.Data); } + [[nodiscard]] static inline std::expected format(const T t, FormatterExecutor& executor) + { return detail::FMTBufferWriteManip(executor.buffer_out).WriteIntegerFormatData(t, executor.Data); } }; template requires std::is_floating_point_v struct FormatterType { - [[nodiscard]] static inline std::expected Format(const T t, FormatterExecutor& executor) - { return Detail::FMTBufferWriteManip(executor.BufferOut).WriteFloatFormatData(t, executor.Data); } + [[nodiscard]] static inline std::expected format(const T t, FormatterExecutor& executor) + { return detail::FMTBufferWriteManip(executor.buffer_out).WriteFloatFormatData(t, executor.Data); } }; template - requires Detail::IsCharType::Value + requires detail::IsCharType::Value struct FormatterType { - [[nodiscard]] static inline std::expected Format(const T t, FormatterExecutor& executor) - { return Detail::BufferOutManip(executor.BufferOut).Pushback(t); } + [[nodiscard]] static inline std::expected format(const T t, FormatterExecutor& executor) + { return detail::BufferOutManip(executor.buffer_out).Pushback(t); } }; //-------------------------------------------------------// @@ -154,26 +154,26 @@ namespace StreamFormat::FMT template struct FormatterType { - [[nodiscard]] static inline std::expected Format(const void* const t, FormatterExecutor& executor) + [[nodiscard]] static inline std::expected format(const void* const t, FormatterExecutor& executor) { if (t == nullptr) - return Detail::BufferOutManip(executor.BufferOut).FastWriteString(executor.Data.GetAsText("null", "nullptr")); - return Detail::BufferWriteManip(executor.BufferOut).FastWriteInteger(std::size_t(t)); + return detail::BufferOutManip(executor.buffer_out).FastWriteString(executor.Data.GetAsText("null", "nullptr")); + return detail::BufferWriteManip(executor.buffer_out).FastWriteInteger(std::size_t(t)); } }; template struct FormatterType { - [[nodiscard]] static inline std::expected Format(const T* const t, FormatterExecutor& executor) + [[nodiscard]] static inline std::expected format(const T* const t, FormatterExecutor& executor) { if (t == nullptr) - { return Detail::BufferWriteManip(executor.BufferOut).FastWriteString(executor.Data.Specifiers.GetAsText("null", "nullptr")); } + { return detail::BufferWriteManip(executor.buffer_out).FastWriteString(executor.Data.Specifiers.GetAsText("null", "nullptr")); } - if constexpr (Detail::IsCharType::Value) - { return Detail::Forwarders::FormatString(t, std::numeric_limits::max(), executor); } + if constexpr (detail::IsCharType::Value) + { return detail::Forwarders::FormatString(t, std::numeric_limits::max(), executor); } else - { Detail::Forwarders::FormatObjectArray(t, std::numeric_limits::max(), executor); } + { detail::Forwarders::FormatObjectArray(t, std::numeric_limits::max(), executor); } return {}; } @@ -182,17 +182,17 @@ namespace StreamFormat::FMT template struct FormatterType { - [[nodiscard]] static inline std::expected Format(T const (&t)[SIZE], FormatterExecutor& executor) + [[nodiscard]] static inline std::expected format(T const (&t)[SIZE], FormatterExecutor& executor) { - if constexpr (Detail::IsCharType::Value) + if constexpr (detail::IsCharType::Value) { std::size_t size = SIZE; while (t[size - 1] == '\0') --size; - return Detail::Forwarders::FormatString(t, size, executor); + return detail::Forwarders::FormatString(t, size, executor); } else { - return Detail::Forwarders::FormatObjectArray(t, SIZE, executor); + return detail::Forwarders::FormatObjectArray(t, SIZE, executor); } return {}; diff --git a/src/StreamFormat/FMT/Context/FormatterExecutor/FormatTextProperties-impl.h b/src/stream/fmt/context/formatter_executor/format_text_properties_impl.h similarity index 54% rename from src/StreamFormat/FMT/Context/FormatterExecutor/FormatTextProperties-impl.h rename to src/stream/fmt/context/formatter_executor/format_text_properties_impl.h index 9b2e8b75..e4bd20ca 100644 --- a/src/StreamFormat/FMT/Context/FormatterExecutor/FormatTextProperties-impl.h +++ b/src/stream/fmt/context/formatter_executor/format_text_properties_impl.h @@ -1,44 +1,44 @@ #pragma once -#include "BasicFormatterExecutor.h" +#include "basic_formatter_executor.h" -namespace StreamFormat::FMT +namespace stream::fmt { //------------------------------------------// //----------------- Resets -----------------// //------------------------------------------// template - struct FormatterType + struct FormatterType { - [[nodiscard]] static std::expected Format(const Detail::TextProperties::ResetProperties, FormatterExecutor& executor) + [[nodiscard]] static std::expected format(const detail::TextProperties::ResetProperties, FormatterExecutor& executor) { - return executor.TextManager.AllPropertiesReset(); + return executor.TextManager.all_properties_reset(); } }; template - struct FormatterType + struct FormatterType { - [[nodiscard]] static std::expected Format(const Detail::TextProperties::TextColor::ResetColor, FormatterExecutor& executor) + [[nodiscard]] static std::expected format(const detail::TextProperties::TextColor::reset_color, FormatterExecutor& executor) { return executor.TextManager.ApplyColorReset(); } }; template - struct FormatterType + struct FormatterType { - [[nodiscard]] static std::expected Format(const Detail::TextProperties::TextStyle::ResetStyle, FormatterExecutor& executor) + [[nodiscard]] static std::expected format(const detail::TextProperties::TextStyle::ResetStyle, FormatterExecutor& executor) { return executor.TextManager.ApplyStyleReset(); } }; template - struct FormatterType + struct FormatterType { - [[nodiscard]] static std::expected Format(const Detail::TextProperties::TextFront::ResetFront, FormatterExecutor& executor) + [[nodiscard]] static std::expected format(const detail::TextProperties::TextFront::reset_front, FormatterExecutor& executor) { return executor.TextManager.ApplyFrontReset(); } @@ -49,30 +49,30 @@ namespace StreamFormat::FMT //---------------------------------------// template - requires Detail::TextPropertiesColorIsApply + requires detail::TextPropertiesColorIsApply struct FormatterType { - [[nodiscard]] static std::expected Format(const T& t, FormatterExecutor& executor) + [[nodiscard]] static std::expected format(const T& t, FormatterExecutor& executor) { return executor.TextManager.AskApplyColor(t); } }; template - requires Detail::TextPropertiesStyleIsApply + requires detail::TextPropertiesStyleIsApply struct FormatterType { - [[nodiscard]] static std::expected Format(const T& t, FormatterExecutor& executor) + [[nodiscard]] static std::expected format(const T& t, FormatterExecutor& executor) { return executor.TextManager.AskApplyStyle(t); } }; template - requires Detail::TextPropertiesFrontIsApply + requires detail::TextPropertiesFrontIsApply struct FormatterType { - [[nodiscard]] static std::expected Format(const T& t, FormatterExecutor& executor) + [[nodiscard]] static std::expected format(const T& t, FormatterExecutor& executor) { return executor.TextManager.AskApplyFront(t); } diff --git a/src/StreamFormat/FMT/Context/FormatterExecutor/FormatterArgs.h b/src/stream/fmt/context/formatter_executor/formatter_args.h similarity index 94% rename from src/StreamFormat/FMT/Context/FormatterExecutor/FormatterArgs.h rename to src/stream/fmt/context/formatter_executor/formatter_args.h index 2c9f0bad..e783c62f 100644 --- a/src/StreamFormat/FMT/Context/FormatterExecutor/FormatterArgs.h +++ b/src/stream/fmt/context/formatter_executor/formatter_args.h @@ -1,12 +1,12 @@ #pragma once -#include "StreamFormat/FMT/Context/BasicContext/BasicArgsInterface.h" -#include "StreamFormat/FMT/Detail/Prelude.h" +#include "stream/fmt/context/basic_context/basic_args_interface.h" +#include "stream/fmt/detail/prelude.h" -#include "FormatterType.h" +#include "formatter_type.h" -namespace StreamFormat::FMT::Detail +namespace stream::fmt::detail { /****************************/ /******** Args tuple ********/ @@ -75,9 +75,9 @@ namespace StreamFormat::FMT::Detail template [[nodiscard]] inline std::expected GetIndexOfCurrentNamedArg(BufferInfoView& format, std::int32_t beginSearchIndex) { - if constexpr (Detail::IsANamedArgs>::value) + if constexpr (detail::IsANamedArgs>::value) { - bool currentIsANamedArg = SF_TRY(Detail::FMTBufferParamsManip(format).NextIsNamedArgs(m_Value.GetName())); + bool currentIsANamedArg = SF_TRY(detail::FMTBufferParamsManip(format).NextIsNamedArgs(m_Value.GetName())); if (currentIsANamedArg) return beginSearchIndex; } diff --git a/src/stream/fmt/context/formatter_executor/formatter_text_properties_executor/formatter_text_properties_executor.h b/src/stream/fmt/context/formatter_executor/formatter_text_properties_executor/formatter_text_properties_executor.h new file mode 100644 index 00000000..68fc1e3b --- /dev/null +++ b/src/stream/fmt/context/formatter_executor/formatter_text_properties_executor/formatter_text_properties_executor.h @@ -0,0 +1,66 @@ +#pragma once + +#include "stream/fmt/context/basic_context/text_properties_executor.h" +#include "stream/fmt/buffer/fmt_buffer_out_manip.h" +#include "stream/fmt/context/formatter_executor/basic_formatter_executor.h" + +namespace stream::fmt::detail +{ + template + class IFormatterTextPropertiesExecutor : public ITextPropertiesExecutor + { + public: + ~IFormatterTextPropertiesExecutor() override = default; + + void link_to_executor(void* executor) override + { + Buffer = &reinterpret_cast*>(executor)->BufferOut; + } + + protected: + detail::FMTBufferOutInfo* Buffer{nullptr}; + }; +} + +namespace stream::fmt::detail +{ + template + class FormatterNOTextPropertiesExecutor final : public IFormatterTextPropertiesExecutor + { + public: + FormatterNOTextPropertiesExecutor() = default; + ~FormatterNOTextPropertiesExecutor() override = default; + + public: + [[nodiscard]] std::expected all_properties_reset() override {} + + public: + [[nodiscard]] std::expected reset_color() override {} + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::BasicColorFG&) override {} + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::BasicColorBG&) override {} + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::BasicColor&) override {} + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::Color24bFG&) override {} + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::Color24bBG&) override {} + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::Color24b&) override {} + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::ColorCubeFG&) override {} + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::ColorCubeBG&) override {} + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::ColorCube&) override {} + + public: + [[nodiscard]] std::expected reset_front() override {} + [[nodiscard]] std::expected ExecuteFront(const detail::TextProperties::TextFront::FrontID&) override {} + + public: + [[nodiscard]] std::expected ResetStyle() override {} + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Intensity&) override {} + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Italic&) override {} + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Underline&) override {} + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::UnderlineColor::Color&) override {} + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::UnderlineColor::ColorCube&) override {} + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::UnderlineColor::Color24b&) override {} + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Blink&) override {} + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Inverted&) override {} + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Ideogram&) override {} + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Script&) override {} + }; +} diff --git a/src/StreamFormat/FMT/Context/FormatterExecutor/FormatterTextPropertiesExecutor/FormatterANSITextPropertiesExecutor.h b/src/stream/fmt/context/formatter_executor/formatter_text_properties_executor/formatter_text_properties_executor_ansi.h similarity index 61% rename from src/StreamFormat/FMT/Context/FormatterExecutor/FormatterTextPropertiesExecutor/FormatterANSITextPropertiesExecutor.h rename to src/stream/fmt/context/formatter_executor/formatter_text_properties_executor/formatter_text_properties_executor_ansi.h index eabfe8ff..3d9de111 100644 --- a/src/StreamFormat/FMT/Context/FormatterExecutor/FormatterTextPropertiesExecutor/FormatterANSITextPropertiesExecutor.h +++ b/src/stream/fmt/context/formatter_executor/formatter_text_properties_executor/formatter_text_properties_executor_ansi.h @@ -1,9 +1,9 @@ #pragma once #include "FormatterTextPropertiesExecutor.h" -#include "StreamFormat/FMT/Detail/IndentHandlers.h" +#include "stream/fmt/detail/IndentHandlers.h" -namespace StreamFormat::FMT::Detail +namespace stream::fmt::detail { template class FormatterANSITextPropertiesExecutor final : public IFormatterTextPropertiesExecutor @@ -15,71 +15,71 @@ namespace StreamFormat::FMT::Detail using IFormatterTextPropertiesExecutor::Buffer; public: - [[nodiscard]] std::expected AllPropertiesReset() override + [[nodiscard]] std::expected all_properties_reset() override { NoStrideFunction noStride(*Buffer); return BufferWriteManip(*Buffer).FastWriteStringLitteral("\033[0m"); } public: - [[nodiscard]] std::expected ResetColor() override + [[nodiscard]] std::expected reset_color() override { NoStrideFunction noStride(*Buffer); return BufferWriteManip(*Buffer).FastWriteStringLitteral("\033[39;49m"); } - [[nodiscard]] std::expected ExecuteColor(const TextProperties::TextColor::BasicColorFG& t) + [[nodiscard]] std::expected execute_color(const TextProperties::TextColor::BasicColorFG& t) { NoStrideFunction noStride(*Buffer); return BufferWriteManip(*Buffer).BasicWriteType("\033[", static_cast(t), "m"); } - [[nodiscard]] std::expected ExecuteColor(const TextProperties::TextColor::BasicColorBG& t) + [[nodiscard]] std::expected execute_color(const TextProperties::TextColor::BasicColorBG& t) { NoStrideFunction noStride(*Buffer); return BufferWriteManip(*Buffer).BasicWriteType("\033[", static_cast(t), "m"); } - [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::BasicColor& t) override + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::BasicColor& t) override { NoStrideFunction noStride(*Buffer); return BufferWriteManip(*Buffer).BasicWriteType("\033[", static_cast(t.Fg), ";", static_cast(t.Bg), "m"); } - [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::Color24bFG& t) override + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::Color24bFG& t) override { NoStrideFunction noStride(*Buffer); return BufferWriteManip(*Buffer).BasicWriteType("\033[38;2;", t.R, ";", t.G, ";", t.B, "m"); } - [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::Color24bBG& t) override + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::Color24bBG& t) override { NoStrideFunction noStride(*Buffer); return BufferWriteManip(*Buffer).BasicWriteType("\033[48;2;", t.R, ";", t.G, ";", t.B, "m"); } - [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::Color24b& t) override + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::Color24b& t) override { NoStrideFunction noStride(*Buffer); return BufferWriteManip(*Buffer).BasicWriteType("\033[38;2;", t.Fg.R, ";", t.Fg.G, ";", t.Fg.B, "; 48; 2;", t.Bg.R, ";", t.Bg.G, ";", t.Bg.B, "m"); } - [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::ColorCubeFG& t) override + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::ColorCubeFG& t) override { NoStrideFunction noStride(*Buffer); return BufferWriteManip(*Buffer).BasicWriteType("\033[38;5;", t.GetColorRef(), "m"); } - [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::ColorCubeBG& t) override + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::ColorCubeBG& t) override { NoStrideFunction noStride(*Buffer); return BufferWriteManip(*Buffer).BasicWriteType("\033[48;5;", t.GetColorRef(), "m"); } - [[nodiscard]] std::expected ExecuteColor(const Detail::TextProperties::TextColor::ColorCube& t) override + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::ColorCube& t) override { NoStrideFunction noStride(*Buffer); return BufferWriteManip(*Buffer).BasicWriteType("\033[48;5;", t.Fg.GetColorRef(), ";48;5;", t.Bg.GetColorRef(), "m"); } public: - [[nodiscard]] std::expected ResetFront() override + [[nodiscard]] std::expected reset_front() override { NoStrideFunction noStride(*Buffer); - return BufferWriteManip(*Buffer).BasicWriteType("\033[", Detail::TextProperties::TextFront::FrontID::DefaultFrontID, "m"); + return BufferWriteManip(*Buffer).BasicWriteType("\033[", detail::TextProperties::TextFront::FrontID::DefaultFrontID, "m"); } - [[nodiscard]] std::expected ExecuteFront(const Detail::TextProperties::TextFront::FrontID& t) override + [[nodiscard]] std::expected ExecuteFront(const detail::TextProperties::TextFront::FrontID& t) override { NoStrideFunction noStride(*Buffer); return BufferWriteManip(*Buffer).BasicWriteType("\033[", t.ID, "m"); @@ -91,52 +91,52 @@ namespace StreamFormat::FMT::Detail NoStrideFunction noStride(*Buffer); return BufferWriteManip(*Buffer).FastWriteStringLitteral("\033[0m"); } - [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Intensity& t) override + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Intensity& t) override { NoStrideFunction noStride(*Buffer); return BufferWriteManip(*Buffer).BasicWriteType("\033[", static_cast(t), "m"); } - [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Italic& t) override + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Italic& t) override { NoStrideFunction noStride(*Buffer); return BufferWriteManip(*Buffer).BasicWriteType("\033[", static_cast(t), "m"); } - [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Underline& t) override + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Underline& t) override { NoStrideFunction noStride(*Buffer); return BufferWriteManip(*Buffer).BasicWriteType("\033[", static_cast(t), "m"); } - [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::UnderlineColor::Color&) override + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::UnderlineColor::Color&) override { NoStrideFunction noStride(*Buffer); return BufferWriteManip(*Buffer).BasicWriteType("\033[59m"); } - [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::UnderlineColor::ColorCube& t) override + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::UnderlineColor::ColorCube& t) override { NoStrideFunction noStride(*Buffer); return BufferWriteManip(*Buffer).BasicWriteType("\033[58;5;", t.GetColorRef(), "m"); } - [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::UnderlineColor::Color24b& t) override + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::UnderlineColor::Color24b& t) override { NoStrideFunction noStride(*Buffer); return BufferWriteManip(*Buffer).BasicWriteType("\033[58;2;", t.R, ";", t.G, ";", t.B, "m"); } - [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Blink& t) override + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Blink& t) override { NoStrideFunction noStride(*Buffer); return BufferWriteManip(*Buffer).BasicWriteType("\033[", static_cast(t), "m"); } - [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Inverted& t) override + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Inverted& t) override { NoStrideFunction noStride(*Buffer); return BufferWriteManip(*Buffer).BasicWriteType("\033[", static_cast(t), "m"); } - [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Ideogram& t) override + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Ideogram& t) override { NoStrideFunction noStride(*Buffer); return BufferWriteManip(*Buffer).BasicWriteType("\033[", static_cast(t), "m"); } - [[nodiscard]] std::expected ExecuteStyle(const Detail::TextProperties::TextStyle::Script& t) override + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Script& t) override { NoStrideFunction noStride(*Buffer); return BufferWriteManip(*Buffer).BasicWriteType("\033[", static_cast(t), "m"); diff --git a/src/StreamFormat/FMT/Context/FormatterExecutor/FormatterType.h b/src/stream/fmt/context/formatter_executor/formatter_type.h similarity index 73% rename from src/StreamFormat/FMT/Context/FormatterExecutor/FormatterType.h rename to src/stream/fmt/context/formatter_executor/formatter_type.h index e141643e..d6caf1ab 100644 --- a/src/StreamFormat/FMT/Context/FormatterExecutor/FormatterType.h +++ b/src/stream/fmt/context/formatter_executor/formatter_type.h @@ -1,14 +1,14 @@ #pragma once -#include "StreamFormat/FMT/Detail/Prelude.h" +#include "stream/fmt/detail/prelude.h" #define STREAMFORMAT_FORMATTER_DECLARED -namespace StreamFormat::FMT +namespace stream::fmt { template struct FormatterType { - [[nodiscard]] static std::expected Format(const T&, FormatterExecutor& executor) + [[nodiscard]] static std::expected format(const T&, FormatterExecutor& executor) { #ifdef UNKOWN_TYPE_MESSAGE executor.Run("({C:red}FMT unknow type: {})", typeid(T).name()); @@ -26,14 +26,14 @@ namespace StreamFormat::FMT #define STREAMFORMAT_AUTO_FORMATTER(Type, fmt, ...) \ template \ - struct StreamFormat::FMT::FormatterType \ + struct stream::fmt::FormatterType \ { \ - [[nodiscard]] static std::expected Format(const Type& value, FormatterExecutor& executor) { return executor.Run(fmt, __VA_ARGS__); } \ + [[nodiscard]] static std::expected format(const Type& value, FormatterExecutor& executor) { return executor.Run(fmt, __VA_ARGS__); } \ }; #define STREAMFORMAT_AUTO_FORMATTER_T(Type, fmt, ...) \ template \ - struct StreamFormat::FMT::FormatterType \ + struct stream::fmt::FormatterType \ { \ - [[nodiscard]] static std::expected Format(const Type&, FormatterExecutor& executor) { return executor.Run(fmt, __VA_ARGS__); } \ + [[nodiscard]] static std::expected format(const Type&, FormatterExecutor& executor) { return executor.Run(fmt, __VA_ARGS__); } \ }; diff --git a/src/StreamFormat/FMT/Context/FormatterExecutor/IndexArgs.h b/src/stream/fmt/context/formatter_executor/index_args.h similarity index 87% rename from src/StreamFormat/FMT/Context/FormatterExecutor/IndexArgs.h rename to src/stream/fmt/context/formatter_executor/index_args.h index 9420aefb..d7589985 100644 --- a/src/StreamFormat/FMT/Context/FormatterExecutor/IndexArgs.h +++ b/src/stream/fmt/context/formatter_executor/index_args.h @@ -1,8 +1,8 @@ #pragma once -#include "FormatterType.h" +#include "formatter_type.h" -namespace StreamFormat::FMT +namespace stream::fmt { template struct FCIndexArgs @@ -28,7 +28,7 @@ namespace StreamFormat::FMT struct FormatterType, FormatterExecutor> { template - [[nodiscard]] static inline std::expected Format(const FCIndexArgs& t, FormatterExecutor& executor) + [[nodiscard]] static inline std::expected format(const FCIndexArgs& t, FormatterExecutor& executor) { return executor.WriteType(t.GetValue()); } diff --git a/src/StreamFormat/FMT/Context/FormatterExecutor/NamedArgs.h b/src/stream/fmt/context/formatter_executor/named_args.h similarity index 88% rename from src/StreamFormat/FMT/Context/FormatterExecutor/NamedArgs.h rename to src/stream/fmt/context/formatter_executor/named_args.h index 9355bc10..9fb23b2d 100644 --- a/src/StreamFormat/FMT/Context/FormatterExecutor/NamedArgs.h +++ b/src/stream/fmt/context/formatter_executor/named_args.h @@ -1,8 +1,8 @@ #pragma once -#include "FormatterType.h" +#include "formatter_type.h" -namespace StreamFormat::FMT +namespace stream::fmt { /////---------- string_view NamedArgs Do not allocate memory (Best) ----------///// template @@ -33,7 +33,7 @@ namespace StreamFormat::FMT template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static inline std::expected Format(const StringViewNamedArgs& t, FormatterExecutor& executor) + [[nodiscard]] static inline std::expected format(const StringViewNamedArgs& t, FormatterExecutor& executor) { return executor.WriteType(t.GetValue()); } @@ -67,7 +67,7 @@ namespace StreamFormat::FMT template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static inline std::expected Format(const StringNamedArgs& t, FormatterExecutor& executor) + [[nodiscard]] static inline std::expected format(const StringNamedArgs& t, FormatterExecutor& executor) { return executor.WriteType(t.GetValue()); } @@ -105,6 +105,6 @@ namespace StreamFormat::FMT } } -#define FORMAT(value) StreamFormat::FMT::StringViewNamedArgs(#value, value) -#define FORMAT_SV(name, value) StreamFormat::FMT::StringViewNamedArgs(name, value) -#define FORMAT_STR(name, value) StreamFormat::FMT::StringNamedArgs(name, value) +#define FORMAT(value) stream::fmt::StringViewNamedArgs(#value, value) +#define FORMAT_SV(name, value) stream::fmt::StringViewNamedArgs(name, value) +#define FORMAT_STR(name, value) stream::fmt::StringNamedArgs(name, value) diff --git a/src/StreamFormat/FMT/Context/FormatterExecutor/STDEnumerable.h b/src/stream/fmt/context/formatter_executor/std_enumerable.h similarity index 81% rename from src/StreamFormat/FMT/Context/FormatterExecutor/STDEnumerable.h rename to src/stream/fmt/context/formatter_executor/std_enumerable.h index d6abeea6..c0da04e2 100644 --- a/src/StreamFormat/FMT/Context/FormatterExecutor/STDEnumerable.h +++ b/src/stream/fmt/context/formatter_executor/std_enumerable.h @@ -1,13 +1,13 @@ #pragma once -#include "FormatterType.h" -#include "StreamFormat/FMT/Context/Utils/ContextFunctions.h" -#include "StreamFormat/FMT/Detail/Prelude.h" +#include "formatter_type.h" +#include "stream/fmt/context/utils/ContextFunctions.h" +#include "stream/fmt/detail/prelude.h" #include #include -namespace StreamFormat::FMT +namespace stream::fmt { class STDEnumerableUtility { @@ -55,28 +55,28 @@ namespace StreamFormat::FMT template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static std::expected Format(const STDEnumerable& enumerable, FormatterExecutor& executor) + [[nodiscard]] static std::expected format(const STDEnumerable& enumerable, FormatterExecutor& executor) { - SF_TRY(executor.BufferOut.WriteIndentStringView(enumerable.GetStrBegin())); - SF_TRY(executor.BufferOut.AddIndent(enumerable.GetStrBegin().size())); + SF_TRY(executor.buffer_out.WriteIndentStringView(enumerable.GetStrBegin())); + SF_TRY(executor.buffer_out.AddIndent(enumerable.GetStrBegin().size())); { // TODO: Why ? ... - Detail::FunctionApplyNextOverride applyNextOverride(executor); + detail::FunctionApplyNextOverride applyNextOverride(executor); bool first = true; std::for_each_n(enumerable.GetValue().cbegin() + enumerable.GetBeginIdx(), enumerable.GetSize(), [&](const auto& element) { if (first) { first = false; } else - { SF_TRY(executor.BufferOut.WriteIndentStringView(enumerable.GetStrJoin())); } + { SF_TRY(executor.buffer_out.WriteIndentStringView(enumerable.GetStrJoin())); } SF_TRY(executor.WriteType(element)); }); } - executor.BufferOut.RemoveIndent(enumerable.GetStrBegin().size()); - SF_TRY(executor.BufferOut.WriteIndentStringView(enumerable.GetStrEnd())); + executor.buffer_out.RemoveIndent(enumerable.GetStrBegin().size()); + SF_TRY(executor.buffer_out.WriteIndentStringView(enumerable.GetStrEnd())); } }; @@ -88,7 +88,7 @@ namespace StreamFormat::FMT template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static inline std::expected Format(const T& container, FormatterExecutor& executor) + [[nodiscard]] static inline std::expected format(const T& container, FormatterExecutor& executor) { STDEnumerable enumerable(container, executor.Data.GetAsText("join", STDEnumerableUtility::DefaultJoin), executor.Data.GetAsText("begin", STDEnumerableUtility::DefaultBegin), diff --git a/src/StreamFormat/FMT/Context/FormatterExecutor/UtilityFunctions.h b/src/stream/fmt/context/formatter_executor/utility_functions.h similarity index 54% rename from src/StreamFormat/FMT/Context/FormatterExecutor/UtilityFunctions.h rename to src/stream/fmt/context/formatter_executor/utility_functions.h index e982843e..ae28886b 100644 --- a/src/StreamFormat/FMT/Context/FormatterExecutor/UtilityFunctions.h +++ b/src/stream/fmt/context/formatter_executor/utility_functions.h @@ -1,16 +1,16 @@ #pragma once -#include "BasicFormatterExecutor.h" +#include "basic_formatter_executor.h" -#include "StreamFormat/FMT/Buffer/BufferOutManager/DynamicBufferOutManager.h" -#include "StreamFormat/FMT/Buffer/BufferOutManager/GivenBufferOutManager.h" -#include "StreamFormat/FMT/Buffer/BufferOutManager/StaticBufferOutManager.h" +#include "stream/fmt/buffer/buffer_out_manager/dynamic_buffer_out_manager.h" +#include "stream/fmt/buffer/buffer_out_manager/given_buffer_out_manager.h" +#include "stream/fmt/buffer/buffer_out_manager/static_buffer_out_manager.h" #include "FormatterTextPropertiesExecutor/FormatterANSITextPropertiesExecutor.h" #include -namespace StreamFormat::FMT +namespace stream::fmt { /////---------- Impl with as Format ----------////// namespace Detail @@ -18,7 +18,7 @@ namespace StreamFormat::FMT template requires(IsCharType::Value) [[nodiscard]] std::expected FormatInManager( - Detail::BasicBufferOutManager& bufferOutManager, + detail::BasicBufferOutManager& bufferOutManager, bool newline, BufferInfoView format, Args&&... args @@ -26,8 +26,8 @@ namespace StreamFormat::FMT { using TCharResolved = std::remove_const_t; - Detail::FormatterANSITextPropertiesExecutor textPropertiesExecutor; - Detail::FMTBufferOutInfo bufferOut = SF_TRY(Detail::FMTBufferOutInfo::Create(bufferOutManager)); + detail::FormatterANSITextPropertiesExecutor textPropertiesExecutor; + detail::FMTBufferOutInfo bufferOut = SF_TRY(detail::FMTBufferOutInfo::Create(bufferOutManager)); Context::BasicFormatterExecutor executor(bufferOut, textPropertiesExecutor); SF_TRY(executor.Run(format, std::forward(args)...)); if (newline) SF_TRY(BufferOutManip(bufferOut).Pushback('\n')); @@ -36,12 +36,12 @@ namespace StreamFormat::FMT template requires(IsCharType::Value) - [[nodiscard]] std::expected FormatInManager(Detail::BasicBufferOutManager& bufferOutManager, bool newline, T&& t) + [[nodiscard]] std::expected FormatInManager(detail::BasicBufferOutManager& bufferOutManager, bool newline, T&& t) { using TCharResolved = std::remove_const_t; - Detail::FormatterANSITextPropertiesExecutor textPropertiesExecutor; - Detail::FMTBufferOutInfo bufferOut = SF_TRY(Detail::FMTBufferOutInfo::Create(bufferOutManager)); + detail::FormatterANSITextPropertiesExecutor textPropertiesExecutor; + detail::FMTBufferOutInfo bufferOut = SF_TRY(detail::FMTBufferOutInfo::Create(bufferOutManager)); Context::BasicFormatterExecutor executor(bufferOut, textPropertiesExecutor); SF_TRY(executor.WriteType(std::forward(t))); if (newline) SF_TRY(BufferOutManip(bufferOut).Pushback('\n')); @@ -50,27 +50,27 @@ namespace StreamFormat::FMT } template - requires(Detail::IsCharType::Value && Detail::ConvertibleToBufferInfoView) + requires(detail::IsCharType::Value && detail::ConvertibleToBufferInfoView) [[nodiscard]] std::expected FormatInChar(TChar (&buffer)[BUFFER_SIZE], Format&& formatInput, Args&&... args) { - Detail::GivenBufferOutManager bufferOutManager(buffer); - return Detail::FormatInManager(bufferOutManager, false, Detail::BufferInfoView{formatInput}, std::forward(args)...); + detail::GivenBufferOutManager bufferOutManager(buffer); + return detail::FormatInManager(bufferOutManager, false, detail::BufferInfoView{formatInput}, std::forward(args)...); } template - requires(Detail::IsCharType::Value && Detail::ConvertibleToBufferInfoView) + requires(detail::IsCharType::Value && detail::ConvertibleToBufferInfoView) [[nodiscard]] std::expected FormatInChar(TChar* const buffer, const std::size_t bufferSize, Format&& formatInput, Args&&... args) { - Detail::GivenBufferOutManager bufferOutManager(buffer, bufferSize); - return Detail::FormatInManager(bufferOutManager, false, Detail::BufferInfoView{formatInput}, std::forward(args)...); + detail::GivenBufferOutManager bufferOutManager(buffer, bufferSize); + return detail::FormatInManager(bufferOutManager, false, detail::BufferInfoView{formatInput}, std::forward(args)...); } template - requires(Detail::IsCharType::Value && Detail::ConvertibleToBufferInfoView) + requires(detail::IsCharType::Value && detail::ConvertibleToBufferInfoView) [[nodiscard]] std::expected CFilePrint(FILE* stream, Format&& formatInput, Args&&... args) { - Detail::DynamicBufferOutManager bufferOutManager(256); - SF_TRY(Detail::FormatInManager(bufferOutManager, false, Detail::BufferInfoView{formatInput}, std::forward(args)...)); + detail::DynamicBufferOutManager bufferOutManager(256); + SF_TRY(detail::FormatInManager(bufferOutManager, false, detail::BufferInfoView{formatInput}, std::forward(args)...)); std::fwrite(bufferOutManager.GetBuffer(), bufferOutManager.GetLastGeneratedDataSize(), 1, stream); std::fflush(stream); @@ -78,11 +78,11 @@ namespace StreamFormat::FMT } template - requires(Detail::IsCharType::Value && Detail::ConvertibleToBufferInfoView) + requires(detail::IsCharType::Value && detail::ConvertibleToBufferInfoView) [[nodiscard]] std::expected CFilePrintLn(FILE* stream, Format&& formatInput, Args&&... args) { - Detail::DynamicBufferOutManager bufferOutManager(256); - SF_TRY(Detail::FormatInManager(bufferOutManager, true, Detail::BufferInfoView{formatInput}, std::forward(args)...)); + detail::DynamicBufferOutManager bufferOutManager(256); + SF_TRY(detail::FormatInManager(bufferOutManager, true, detail::BufferInfoView{formatInput}, std::forward(args)...)); std::fwrite(bufferOutManager.GetBuffer(), bufferOutManager.GetLastGeneratedDataSize(), 1, stream); std::fflush(stream); @@ -90,11 +90,11 @@ namespace StreamFormat::FMT } template - requires(Detail::IsCharType::Value && Detail::ConvertibleToBufferInfoView) + requires(detail::IsCharType::Value && detail::ConvertibleToBufferInfoView) [[nodiscard]] std::expected FilePrint(std::basic_ostream& stream, Format&& formatInput, Args&&... args) { - Detail::DynamicBufferOutManager bufferOutManager(256); - SF_TRY(Detail::FormatInManager(bufferOutManager, false, Detail::BufferInfoView{formatInput}, std::forward(args)...)); + detail::DynamicBufferOutManager bufferOutManager(256); + SF_TRY(detail::FormatInManager(bufferOutManager, false, detail::BufferInfoView{formatInput}, std::forward(args)...)); stream.write(bufferOutManager.GetBuffer(), bufferOutManager.GetLastGeneratedDataSize()); stream.flush(); @@ -102,11 +102,11 @@ namespace StreamFormat::FMT } template - requires(Detail::IsCharType::Value && Detail::ConvertibleToBufferInfoView) + requires(detail::IsCharType::Value && detail::ConvertibleToBufferInfoView) [[nodiscard]] std::expected FilePrintLn(std::basic_ostream& stream, Format&& formatInput, Args&&... args) { - Detail::DynamicBufferOutManager bufferOutManager(256); - SF_TRY(Detail::FormatInManager(bufferOutManager, true, Detail::BufferInfoView{formatInput}, std::forward(args)...)); + detail::DynamicBufferOutManager bufferOutManager(256); + SF_TRY(detail::FormatInManager(bufferOutManager, true, detail::BufferInfoView{formatInput}, std::forward(args)...)); stream.write(bufferOutManager.GetBuffer(), bufferOutManager.GetLastGeneratedDataSize()); stream.flush(); @@ -114,48 +114,48 @@ namespace StreamFormat::FMT } template - requires(Detail::IsCharType::Value && Detail::ConvertibleToBufferInfoView) + requires(detail::IsCharType::Value && detail::ConvertibleToBufferInfoView) [[nodiscard]] std::expected FormatInString(std::basic_string& str, Format&& formatInput, Args&&... args) { - Detail::DynamicBufferOutManager bufferOutManager(256); - SF_TRY(Detail::FormatInManager(bufferOutManager, false, Detail::BufferInfoView{formatInput}, std::forward(args)...)); + detail::DynamicBufferOutManager bufferOutManager(256); + SF_TRY(detail::FormatInManager(bufferOutManager, false, detail::BufferInfoView{formatInput}, std::forward(args)...)); str = bufferOutManager.GetLastGeneratedString(); return {}; } template - requires(Detail::IsCharType::Value && Detail::ConvertibleToBufferInfoView) + requires(detail::IsCharType::Value && detail::ConvertibleToBufferInfoView) [[nodiscard]] inline std::expected, FMTResult> FormatString(Format&& formatInput, Args&&... args) { - Detail::DynamicBufferOutManager bufferOutManager(256); - SF_TRY(Detail::FormatInManager(bufferOutManager, false, Detail::BufferInfoView{formatInput}, std::forward(args)...)); + detail::DynamicBufferOutManager bufferOutManager(256); + SF_TRY(detail::FormatInManager(bufferOutManager, false, detail::BufferInfoView{formatInput}, std::forward(args)...)); return bufferOutManager.GetLastGeneratedString(); } /////---------- NO-FORMAT Impl except for string which are formatted to avoid {} ----------////// template - requires(Detail::IsCharType::Value) + requires(detail::IsCharType::Value) [[nodiscard]] std::expected FormatInChar(TChar (&buffer)[BUFFER_SIZE], T&& t) { - Detail::GivenBufferOutManager bufferOutManager(buffer, BUFFER_SIZE); - return Detail::FormatInManager(bufferOutManager, false, std::forward(t)); + detail::GivenBufferOutManager bufferOutManager(buffer, BUFFER_SIZE); + return detail::FormatInManager(bufferOutManager, false, std::forward(t)); } template - requires(Detail::IsCharType::Value) + requires(detail::IsCharType::Value) [[nodiscard]] std::expected FormatInChar(TChar* const buffer, const std::size_t bufferSize, T&& t) { - Detail::GivenBufferOutManager bufferOutManager(buffer, bufferSize); - return Detail::FormatInManager(bufferOutManager, false, std::forward(t)); + detail::GivenBufferOutManager bufferOutManager(buffer, bufferSize); + return detail::FormatInManager(bufferOutManager, false, std::forward(t)); } template - requires(Detail::IsCharType::Value) + requires(detail::IsCharType::Value) [[nodiscard]] std::expected CFilePrint(FILE* stream, T&& t) { - Detail::DynamicBufferOutManager bufferOutManager(32); - SF_TRY(Detail::FormatInManager(bufferOutManager, false, std::forward(t))); + detail::DynamicBufferOutManager bufferOutManager(32); + SF_TRY(detail::FormatInManager(bufferOutManager, false, std::forward(t))); std::fwrite(bufferOutManager.GetBuffer(), static_cast(bufferOutManager.GetLastGeneratedDataSize()), 1, stream); std::fflush(stream); @@ -163,11 +163,11 @@ namespace StreamFormat::FMT } template - requires(Detail::IsCharType::Value) + requires(detail::IsCharType::Value) [[nodiscard]] std::expected CFilePrintLn(FILE* stream, T&& t) { - Detail::DynamicBufferOutManager bufferOutManager(32); - SF_TRY(Detail::FormatInManager(bufferOutManager, true, std::forward(t))); + detail::DynamicBufferOutManager bufferOutManager(32); + SF_TRY(detail::FormatInManager(bufferOutManager, true, std::forward(t))); std::fwrite(bufferOutManager.GetBuffer(), static_cast(bufferOutManager.GetLastGeneratedDataSize()), 1, stream); std::fflush(stream); @@ -175,11 +175,11 @@ namespace StreamFormat::FMT } template - requires(Detail::IsCharType::Value) + requires(detail::IsCharType::Value) [[nodiscard]] std::expected FilePrint(std::basic_ostream& stream, T&& t) { - Detail::DynamicBufferOutManager bufferOutManager(32); - SF_TRY(Detail::FormatInManager(bufferOutManager, false, std::forward(t))); + detail::DynamicBufferOutManager bufferOutManager(32); + SF_TRY(detail::FormatInManager(bufferOutManager, false, std::forward(t))); stream.write(bufferOutManager.GetBuffer(), static_cast(bufferOutManager.GetLastGeneratedDataSize())); stream.flush(); @@ -187,11 +187,11 @@ namespace StreamFormat::FMT } template - requires(Detail::IsCharType::Value) + requires(detail::IsCharType::Value) [[nodiscard]] std::expected FilePrintLn(std::basic_ostream& stream, T&& t) { - Detail::DynamicBufferOutManager bufferOutManager(32); - SF_TRY(Detail::FormatInManager(bufferOutManager, true, std::forward(t))); + detail::DynamicBufferOutManager bufferOutManager(32); + SF_TRY(detail::FormatInManager(bufferOutManager, true, std::forward(t))); stream.write(bufferOutManager.GetBuffer(), static_cast(bufferOutManager.GetLastGeneratedDataSize())); stream.flush(); @@ -199,76 +199,76 @@ namespace StreamFormat::FMT } template - requires(Detail::IsCharType::Value) + requires(detail::IsCharType::Value) [[nodiscard]] std::expected FormatInString(std::basic_string& str, T&& t) { - Detail::DynamicBufferOutManager bufferOutManager(32); - SF_TRY(Detail::FormatInManager(bufferOutManager, false, std::forward(t))); + detail::DynamicBufferOutManager bufferOutManager(32); + SF_TRY(detail::FormatInManager(bufferOutManager, false, std::forward(t))); str = bufferOutManager.GetLastGeneratedString(); return {}; } template - requires(Detail::IsCharType::Value) + requires(detail::IsCharType::Value) [[nodiscard]] inline std::expected, FMTResult> FormatString(T&& t) { - Detail::DynamicBufferOutManager bufferOutManager(32); - SF_TRY(Detail::FormatInManager(bufferOutManager, false, std::forward(t))); + detail::DynamicBufferOutManager bufferOutManager(32); + SF_TRY(detail::FormatInManager(bufferOutManager, false, std::forward(t))); return bufferOutManager.GetLastGeneratedString(); } } -namespace StreamFormat::FMT +namespace stream::fmt { template struct FormatterType { - [[nodiscard]] static std::expected Format(FMTResult result, FormatterExecutor& executor) + [[nodiscard]] static std::expected format(FMTResult result, FormatterExecutor& executor) { switch(result) { case FMTResult::FunctionNotImpl: - return Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("FunctionNotImpl"); + return detail::BufferWriteManip(executor.buffer_out).FastWriteStringLitteral("FunctionNotImpl"); case FMTResult::Buffer_NonValid: - return Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("Buffer_NonValid"); + return detail::BufferWriteManip(executor.buffer_out).FastWriteStringLitteral("Buffer_NonValid"); case FMTResult::Buffer_OutOfBoundAccess: - return Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("Buffer_OutOfBoundAccess"); + return detail::BufferWriteManip(executor.buffer_out).FastWriteStringLitteral("Buffer_OutOfBoundAccess"); case FMTResult::Buffer_UnableToReserveMemory: - return Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("Buffer_UnableToReserveMemory"); + return detail::BufferWriteManip(executor.buffer_out).FastWriteStringLitteral("Buffer_UnableToReserveMemory"); case FMTResult::Parse_NonValidDigit: - return Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("Parse_NonValidDigit"); + return detail::BufferWriteManip(executor.buffer_out).FastWriteStringLitteral("Parse_NonValidDigit"); case FMTResult::Parse_TokenNotExpected: - return Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("Parse_TokenNotExpected"); + return detail::BufferWriteManip(executor.buffer_out).FastWriteStringLitteral("Parse_TokenNotExpected"); case FMTResult::ArgsInterface_Unavaible: - return Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("ArgsInterface_Unavaible"); + return detail::BufferWriteManip(executor.buffer_out).FastWriteStringLitteral("ArgsInterface_Unavaible"); case FMTResult::ArgsInterface_InvalidTypeID: - return Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("ArgsInterface_InvalidTypeID"); + return detail::BufferWriteManip(executor.buffer_out).FastWriteStringLitteral("ArgsInterface_InvalidTypeID"); case FMTResult::ArgsInterface_InvalidConversion: - return Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("ArgsInterface_InvalidConversion"); + return detail::BufferWriteManip(executor.buffer_out).FastWriteStringLitteral("ArgsInterface_InvalidConversion"); case FMTResult::ArgsInterface_CantMatchNamedArgs: - return Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("ArgsInterface_CantMatchNamedArgs"); + return detail::BufferWriteManip(executor.buffer_out).FastWriteStringLitteral("ArgsInterface_CantMatchNamedArgs"); case FMTResult::ArgsInterface_IndexOutOfBounds: - return Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("ArgsInterface_IndexOutOfBounds"); + return detail::BufferWriteManip(executor.buffer_out).FastWriteStringLitteral("ArgsInterface_IndexOutOfBounds"); case FMTResult::Specifers_Full: - return Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("Specifers_Full"); + return detail::BufferWriteManip(executor.buffer_out).FastWriteStringLitteral("Specifers_Full"); case FMTResult::Specifers_Invalid: - return Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("Specifers_Invalid"); + return detail::BufferWriteManip(executor.buffer_out).FastWriteStringLitteral("Specifers_Invalid"); case FMTResult::Specifers_DoesNotExist: - return Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("Specifers_DoesNotExist"); + return detail::BufferWriteManip(executor.buffer_out).FastWriteStringLitteral("Specifers_DoesNotExist"); case FMTResult::Context_ParsingFormat: - return Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("Context_ParsingFormat"); + return detail::BufferWriteManip(executor.buffer_out).FastWriteStringLitteral("Context_ParsingFormat"); case FMTResult::Context_ArgumentIndexResolution: - return Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("Context_ArgumentIndexResolution"); + return detail::BufferWriteManip(executor.buffer_out).FastWriteStringLitteral("Context_ArgumentIndexResolution"); case FMTResult::Context_ArgumentIndexExpected: - return Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("Context_ArgumentIndexExpected"); + return detail::BufferWriteManip(executor.buffer_out).FastWriteStringLitteral("Context_ArgumentIndexExpected"); case FMTResult::Context_CannotApplyType: - return Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("Context_CannotApplyType"); + return detail::BufferWriteManip(executor.buffer_out).FastWriteStringLitteral("Context_CannotApplyType"); case FMTResult::GivenArgs_UnableToDeduceSize: - return Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("GivenArgs_UnableToDeduceSize"); + return detail::BufferWriteManip(executor.buffer_out).FastWriteStringLitteral("GivenArgs_UnableToDeduceSize"); case FMTResult::Manager_StaticMemory: - return Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("Manager_StaticMemory"); + return detail::BufferWriteManip(executor.buffer_out).FastWriteStringLitteral("Manager_StaticMemory"); case FMTResult::Manager_AllocationFailed: - return Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("Manager_AllocationFailed"); + return detail::BufferWriteManip(executor.buffer_out).FastWriteStringLitteral("Manager_AllocationFailed"); } } }; diff --git a/src/StreamFormat/FMT/Context/ParserExecutor/BasicParserExecutor.h b/src/stream/fmt/context/parser_executor/basic_parser_executor.h similarity index 67% rename from src/StreamFormat/FMT/Context/ParserExecutor/BasicParserExecutor.h rename to src/stream/fmt/context/parser_executor/basic_parser_executor.h index 3113ac97..071bb3ba 100644 --- a/src/StreamFormat/FMT/Context/ParserExecutor/BasicParserExecutor.h +++ b/src/stream/fmt/context/parser_executor/basic_parser_executor.h @@ -1,10 +1,10 @@ #pragma once -#include "StreamFormat/FMT/Buffer/BufferInfo.h" -#include "StreamFormat/FMT/Buffer/BufferManip.h" -#include "StreamFormat/FMT/Buffer/BufferTestManip.h" +#include "stream/fmt/buffer/buffer_info.h" +#include "stream/fmt/buffer/buffer_manip.h" +#include "stream/fmt/buffer/buffer_test_manip.h" -#include "StreamFormat/FMT/Context/BasicContext/BasicContext.h" +#include "stream/fmt/context/basic_context/basic_context.h" #include "ParserType.h" @@ -12,7 +12,7 @@ #include "ParserTextPropertiesExecutor/ParserTextPropertiesExecutor.h" -namespace StreamFormat::FMT::Context +namespace stream::fmt::context { template class BasicParserExecutor : public ContextExecutor @@ -23,13 +23,13 @@ namespace StreamFormat::FMT::Context using M_Type = BasicParserExecutor; public: - BasicParserExecutor(Detail::BufferInfoView& bufferIn, Detail::ITextPropertiesExecutor& textPropertiesExecutor); + BasicParserExecutor(detail::BufferInfoView& bufferIn, detail::ITextPropertiesExecutor& textPropertiesExecutor); ~BasicParserExecutor() override = default; [[nodiscard]] std::expected Terminate(); public: - Detail::BufferInfoView& BufferIn; + detail::BufferInfoView& BufferIn; using ContextExecutor::Data; using ContextExecutor::TextManager; @@ -37,14 +37,14 @@ namespace StreamFormat::FMT::Context protected: [[nodiscard]] std::expected ExecRawString(std::basic_string_view sv) override { - SF_TRY(Detail::BufferTestManip(BufferIn).IsSameForward(sv.data(), sv.size())); + SF_TRY(detail::BufferTestManip(BufferIn).is_same_forward(sv.data(), sv.size())); return {}; } [[nodiscard]] std::expected ExecSettings() override { return {}; }; public: template - [[nodiscard]] std::expected Run_(Detail::BufferInfoView format, Args&&... args); + [[nodiscard]] std::expected Run_(detail::BufferInfoView format, Args&&... args); template [[nodiscard]] std::expected Run(Format&& format, Args&&... args); @@ -52,7 +52,7 @@ namespace StreamFormat::FMT::Context template [[nodiscard]] inline std::expected ReadType(Type& type, Rest&... rest) { - auto&& parseErr = ParserType>::Type, M_Type>::Parse(type, *this); + auto&& parseErr = ParserType>::Type, M_Type>::parse(type, *this); SF_TRY(parseErr); if constexpr (sizeof...(rest) > 0) SF_TRY(ReadType(std::forward(rest)...)); @@ -61,14 +61,14 @@ namespace StreamFormat::FMT::Context }; } -namespace StreamFormat::FMT::Context +namespace stream::fmt::context { template - BasicParserExecutor::BasicParserExecutor(Detail::BufferInfoView& bufferIn, Detail::ITextPropertiesExecutor& textPropertiesExecutor) + BasicParserExecutor::BasicParserExecutor(detail::BufferInfoView& bufferIn, detail::ITextPropertiesExecutor& textPropertiesExecutor) : ContextExecutor(textPropertiesExecutor) , BufferIn{bufferIn} { - textPropertiesExecutor.LinkToExecutor(this); + textPropertiesExecutor.link_to_executor(this); } template @@ -79,11 +79,11 @@ namespace StreamFormat::FMT::Context template template - [[nodiscard]] std::expected BasicParserExecutor::Run_(Detail::BufferInfoView format, Args&&... args) + [[nodiscard]] std::expected BasicParserExecutor::Run_(detail::BufferInfoView format, Args&&... args) { - auto argsInterface = Detail::ParserArgsInterface, Args...>(*this, std::forward(args)...); + auto argsInterface = detail::ParserArgsInterface, Args...>(*this, std::forward(args)...); - Detail::TextProperties::Properties saveTextProperties = TextManager.Save(); + detail::TextProperties::Properties saveTextProperties = TextManager.Save(); Context::BasicContext context(*this, format, argsInterface); SF_TRY(context.Run()); return TextManager.Reload(saveTextProperties); @@ -93,7 +93,7 @@ namespace StreamFormat::FMT::Context template [[nodiscard]] std::expected BasicParserExecutor::Run(Format&& formatInput, Args&&... args) { - return Run_(Detail::BufferInfoView{formatInput}, std::forward(args)...); + return Run_(detail::BufferInfoView{formatInput}, std::forward(args)...); } } diff --git a/src/StreamFormat/FMT/Context/ParserExecutor/ParseBasics-impl.h b/src/stream/fmt/context/parser_executor/parse_basics_impl.h similarity index 69% rename from src/StreamFormat/FMT/Context/ParserExecutor/ParseBasics-impl.h rename to src/stream/fmt/context/parser_executor/parse_basics_impl.h index 6ce903c7..57a0b571 100644 --- a/src/StreamFormat/FMT/Context/ParserExecutor/ParseBasics-impl.h +++ b/src/stream/fmt/context/parser_executor/parse_basics_impl.h @@ -1,9 +1,9 @@ #pragma once #include "BasicParserExecutor.h" -#include "StreamFormat/FMT/Buffer/FMTBufferReadManip.h" +#include "stream/fmt/buffer/FMTBufferReadManip.h" -namespace StreamFormat::FMT +namespace stream::fmt { //----------------------------------------------// //----------------- Forwarders -----------------// @@ -16,39 +16,39 @@ namespace StreamFormat::FMT template struct ParserType { - [[nodiscard]] static std::expected Parse(bool& t, ParserExecutor& executor) + [[nodiscard]] static std::expected parse(bool& t, ParserExecutor& executor) { if (!executor.Data.PrefixSuffix) { - if (Detail::BufferTestAccess(executor.BufferIn).IsEqualTo('t', 'T')) + if (detail::BufferTestAccess(executor.BufferIn).IsEqualTo('t', 'T')) { - SF_TRY(Detail::BufferManip(executor.BufferIn).Forward()); - if (Detail::BufferTestAccess(executor.BufferIn).IsSame("rue")) + SF_TRY(detail::BufferManip(executor.BufferIn).Forward()); + if (detail::BufferTestAccess(executor.BufferIn).IsSame("rue")) { - SF_TRY(Detail::BufferManip(executor.BufferIn).Forward()); + SF_TRY(detail::BufferManip(executor.BufferIn).Forward()); t = true; } } - else if (Detail::BufferTestAccess(executor.BufferIn).IsEqualTo('f', 'F')) + else if (detail::BufferTestAccess(executor.BufferIn).IsEqualTo('f', 'F')) { - SF_TRY(Detail::BufferManip(executor.BufferIn).Forward()); - if (Detail::BufferTestAccess(executor.BufferIn).IsSame("alse")) + SF_TRY(detail::BufferManip(executor.BufferIn).Forward()); + if (detail::BufferTestAccess(executor.BufferIn).IsSame("alse")) { - SF_TRY(Detail::BufferManip(executor.BufferIn).Forward()); + SF_TRY(detail::BufferManip(executor.BufferIn).Forward()); t = false; } } } else { - if (Detail::BufferTestAccess(executor.BufferIn).IsEqualTo('1')) + if (detail::BufferTestAccess(executor.BufferIn).IsEqualTo('1')) { - SF_TRY(Detail::BufferManip(executor.BufferIn).Forward()); + SF_TRY(detail::BufferManip(executor.BufferIn).Forward()); t = true; } - else if (Detail::BufferTestAccess(executor.BufferIn).IsEqualTo('0')) + else if (detail::BufferTestAccess(executor.BufferIn).IsEqualTo('0')) { - SF_TRY(Detail::BufferManip(executor.BufferIn).Forward()); + SF_TRY(detail::BufferManip(executor.BufferIn).Forward()); t = false; } } @@ -57,19 +57,19 @@ namespace StreamFormat::FMT }; template - requires (std::is_integral_v && !std::is_floating_point_v && !Detail::IsCharType::Value) + requires (std::is_integral_v && !std::is_floating_point_v && !detail::IsCharType::Value) struct ParserType { - [[nodiscard]] static inline std::expected Parse(T& t, ParserExecutor& executor) - { return Detail::FMTBufferReadManip(executor.BufferIn).ReadIntegerFormatData(t, executor.Data); } + [[nodiscard]] static inline std::expected parse(T& t, ParserExecutor& executor) + { return detail::FMTBufferReadManip(executor.BufferIn).ReadIntegerFormatData(t, executor.Data); } }; template requires std::is_floating_point_v struct ParserType { - [[nodiscard]] static inline std::expected Parse(T& t, ParserExecutor& executor) - { return Detail::FMTBufferReadManip(executor.BufferIn).ReadFloatFormatData(t, executor.Data); } + [[nodiscard]] static inline std::expected parse(T& t, ParserExecutor& executor) + { return detail::FMTBufferReadManip(executor.BufferIn).ReadFloatFormatData(t, executor.Data); } }; //-------------------------------------------------------// @@ -79,7 +79,7 @@ namespace StreamFormat::FMT template struct ParserType { - [[nodiscard]] static inline std::expected Parse(void*&, ParserExecutor&) + [[nodiscard]] static inline std::expected parse(void*&, ParserExecutor&) { // FIXME // TODO @@ -90,7 +90,7 @@ namespace StreamFormat::FMT template struct ParserType { - [[nodiscard]] static inline std::expected Parse(T*&, ParserExecutor&) + [[nodiscard]] static inline std::expected parse(T*&, ParserExecutor&) { // FIXME // TODO @@ -101,7 +101,7 @@ namespace StreamFormat::FMT template struct ParserType { - [[nodiscard]] static inline std::expected Parse(T (&)[SIZE], ParserExecutor&) + [[nodiscard]] static inline std::expected parse(T (&)[SIZE], ParserExecutor&) { // FIXME // TODO diff --git a/src/StreamFormat/FMT/Context/ParserExecutor/ParseTextProperties-impl.h b/src/stream/fmt/context/parser_executor/parse_text_properties_impl.h similarity index 66% rename from src/StreamFormat/FMT/Context/ParserExecutor/ParseTextProperties-impl.h rename to src/stream/fmt/context/parser_executor/parse_text_properties_impl.h index 20f305ce..0d773946 100644 --- a/src/StreamFormat/FMT/Context/ParserExecutor/ParseTextProperties-impl.h +++ b/src/stream/fmt/context/parser_executor/parse_text_properties_impl.h @@ -2,43 +2,43 @@ #include "BasicParserExecutor.h" -namespace StreamFormat::FMT +namespace stream::fmt { //------------------------------------------// //----------------- Resets -----------------// //------------------------------------------// template - struct ParserType + struct ParserType { - [[nodiscard]] static inline std::expected Parse(Detail::TextProperties::ResetProperties, ParserExecutor& executor) + [[nodiscard]] static inline std::expected parse(detail::TextProperties::ResetProperties, ParserExecutor& executor) { - return executor.TextManager.AllPropertiesReset(); + return executor.TextManager.all_properties_reset(); } }; template - struct ParserType + struct ParserType { - [[nodiscard]] static inline std::expected Parse(Detail::TextProperties::TextColor::ResetColor, ParserExecutor& executor) + [[nodiscard]] static inline std::expected parse(detail::TextProperties::TextColor::reset_color, ParserExecutor& executor) { return executor.TextManager.ApplyColorReset(); } }; template - struct ParserType + struct ParserType { - [[nodiscard]] static inline std::expected Parse(Detail::TextProperties::TextStyle::ResetStyle, ParserExecutor& executor) + [[nodiscard]] static inline std::expected parse(detail::TextProperties::TextStyle::ResetStyle, ParserExecutor& executor) { return executor.TextManager.ApplyStyleReset(); } }; template - struct ParserType + struct ParserType { - [[nodiscard]] static inline std::expected Parse(Detail::TextProperties::TextFront::ResetFront, ParserExecutor& executor) + [[nodiscard]] static inline std::expected parse(detail::TextProperties::TextFront::reset_front, ParserExecutor& executor) { return executor.TextManager.ApplyFrontReset(); } @@ -49,30 +49,30 @@ namespace StreamFormat::FMT //---------------------------------------// template - requires Detail::TextPropertiesColorIsApply + requires detail::TextPropertiesColorIsApply struct ParserType { - [[nodiscard]] static inline std::expected Parse(T& t, ParserExecutor& executor) + [[nodiscard]] static inline std::expected parse(T& t, ParserExecutor& executor) { return executor.TextManager.AskApplyColor(t); } }; template - requires Detail::TextPropertiesStyleIsApply + requires detail::TextPropertiesStyleIsApply struct ParserType { - [[nodiscard]] static inline std::expected Parse(T& t, ParserExecutor& executor) + [[nodiscard]] static inline std::expected parse(T& t, ParserExecutor& executor) { return executor.TextManager.AskApplyStyle(t); } }; template - requires Detail::TextPropertiesFrontIsApply + requires detail::TextPropertiesFrontIsApply struct ParserType { - [[nodiscard]] static inline std::expected Parse(T& t, ParserExecutor& executor) + [[nodiscard]] static inline std::expected parse(T& t, ParserExecutor& executor) { return executor.TextManager.AskApplyFront(t); } diff --git a/src/StreamFormat/FMT/Context/ParserExecutor/ParserArgs.h b/src/stream/fmt/context/parser_executor/parser_args.h similarity index 95% rename from src/StreamFormat/FMT/Context/ParserExecutor/ParserArgs.h rename to src/stream/fmt/context/parser_executor/parser_args.h index cf7e36ba..5de27197 100644 --- a/src/StreamFormat/FMT/Context/ParserExecutor/ParserArgs.h +++ b/src/stream/fmt/context/parser_executor/parser_args.h @@ -1,9 +1,9 @@ #pragma once -#include "StreamFormat/FMT/Context/BasicContext/BasicArgsInterface.h" -#include "StreamFormat/FMT/Detail/Prelude.h" +#include "stream/fmt/context/basic_context/basic_args_interface.h" +#include "stream/fmt/detail/prelude.h" -namespace StreamFormat::FMT::Detail +namespace stream::fmt::detail { /****************************/ /******** Args tuple ********/ @@ -75,9 +75,9 @@ namespace StreamFormat::FMT::Detail template [[nodiscard]] inline std::expected GetIndexOfCurrentNamedArg(BufferInfoView& format, std::int32_t beginSearchIndex) { - if constexpr (Detail::IsANamedArgs>::value) + if constexpr (detail::IsANamedArgs>::value) { - bool currentIsANamedArg = SF_TRY(Detail::FMTBufferParamsManip(format).NextIsNamedArgs(m_Value.GetName())); + bool currentIsANamedArg = SF_TRY(detail::FMTBufferParamsManip(format).NextIsNamedArgs(m_Value.GetName())); if (currentIsANamedArg) return beginSearchIndex; } diff --git a/src/stream/fmt/context/parser_executor/parser_text_properties_executor/parser_text_properties_executor.h b/src/stream/fmt/context/parser_executor/parser_text_properties_executor/parser_text_properties_executor.h new file mode 100644 index 00000000..5ed25490 --- /dev/null +++ b/src/stream/fmt/context/parser_executor/parser_text_properties_executor/parser_text_properties_executor.h @@ -0,0 +1,69 @@ +#pragma once + +#include "stream/fmt/context/basic_context/text_properties_executor.h" +#include "stream/fmt/detail/prelude.h" +#include "stream/fmt/context/ParserExecutor/BasicParserExecutor.h" + +namespace stream::fmt::detail +{ + template + class IParserTextPropertiesExecutor : public ITextPropertiesExecutor + { + public: + IParserTextPropertiesExecutor() = default; + ~IParserTextPropertiesExecutor() override = default; + + void link_to_executor(void* executor) override + { + Buffer = &reinterpret_cast*>(executor)->BufferIn; + } + + protected: + BufferInfoView* Buffer{nullptr}; + }; +} + +namespace stream::fmt::detail +{ + template + class ParserNOTextPropertiesExecutor : public IParserTextPropertiesExecutor + { + public: + ParserNOTextPropertiesExecutor() = default; + ~ParserNOTextPropertiesExecutor() override = default; + + using IParserTextPropertiesExecutor::Buffer; + + public: + [[nodiscard]] std::expected all_properties_reset() override { return {}; } + + public: + [[nodiscard]] std::expected reset_color() override {} + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::BasicColorFG&) override { return {}; } + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::BasicColorBG&) override { return {}; } + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::BasicColor&) override { return {}; } + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::Color24bFG&) override { return {}; } + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::Color24bBG&) override { return {}; } + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::Color24b&) override { return {}; } + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::ColorCubeFG&) override { return {}; } + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::ColorCubeBG&) override { return {}; } + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::ColorCube&) override { return {}; } + + public: + [[nodiscard]] std::expected reset_front() override { return {}; } + [[nodiscard]] std::expected ExecuteFront(const detail::TextProperties::TextFront::FrontID&) override { return {}; } + + public: + [[nodiscard]] std::expected ResetStyle() override { return {}; } + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Intensity&) override { return {}; } + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Italic&) override { return {}; } + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Underline&) override { return {}; } + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::UnderlineColor::Color&) override { return {}; } + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::UnderlineColor::ColorCube&) override { return {}; } + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::UnderlineColor::Color24b&) override { return {}; } + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Blink&) override { return {}; } + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Inverted&) override { return {}; } + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Ideogram&) override { return {}; } + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Script&) override { return {}; } + }; +} diff --git a/src/stream/fmt/context/parser_executor/parser_text_properties_executor/parser_text_properties_executor_ansi.h b/src/stream/fmt/context/parser_executor/parser_text_properties_executor/parser_text_properties_executor_ansi.h new file mode 100644 index 00000000..6c408ee8 --- /dev/null +++ b/src/stream/fmt/context/parser_executor/parser_text_properties_executor/parser_text_properties_executor_ansi.h @@ -0,0 +1,144 @@ +#pragma once + +#include "ParserTextPropertiesExecutor.h" + +namespace stream::fmt::detail +{ + template + class ParserANSITextPropertiesExecutor : public IParserTextPropertiesExecutor + { + public: + ParserANSITextPropertiesExecutor() = default; + ~ParserANSITextPropertiesExecutor() override = default; + + using IParserTextPropertiesExecutor::Buffer; + + public: + [[nodiscard]] std::expected all_properties_reset() override + { + return std::unexpected(FMTResult::FunctionNotImpl); + /*BufferReadManip(buffer).BasicReadType('\033', '[', 0, 'm');*/ + } + + public: + [[nodiscard]] std::expected reset_color() override + { + return std::unexpected(FMTResult::FunctionNotImpl); + /*BufferReadManip(buffer).BasicReadType('\033', '[', 39, ';', 49, 'm');*/ + } + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::BasicColorFG&) override + { + return std::unexpected(FMTResult::FunctionNotImpl); + /*BufferReadManip(buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ + } + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::BasicColorBG&) override + { + return std::unexpected(FMTResult::FunctionNotImpl); + /*BufferReadManip(buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ + } + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::BasicColor&) override + { + return std::unexpected(FMTResult::FunctionNotImpl); + /*BufferReadManip(buffer).BasicReadType('\033', '[', static_cast(t.Fg) , ';', static_cast(t.Bg), 'm');*/ + } + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::Color24bFG&) override + { + return std::unexpected(FMTResult::FunctionNotImpl); + /*BufferReadManip(buffer).BasicReadType("\033[38;2;", t.R, ';', t.G, ';', t.B, 'm');*/ + } + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::Color24bBG&) override + { + return std::unexpected(FMTResult::FunctionNotImpl); + /*BufferReadManip(buffer).BasicReadType("\033[48;2;", t.R, ';', t.G, ';', t.B, 'm');*/ + } + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::Color24b&) override + { + return std::unexpected(FMTResult::FunctionNotImpl); + /*BufferReadManip(buffer).BasicReadType("\033[38;2;", t.Fg.R, ';', t.Fg.G, ';', t.Fg.B, "; 48; 2;", t.Bg.R, ';', t.Bg.G, ';', t.Bg.B, 'm');*/ + } + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::ColorCubeFG&) override + { + return std::unexpected(FMTResult::FunctionNotImpl); + /*BufferReadManip(buffer).BasicReadType("\033[38;5;", t.GetColorRef(), 'm');*/ + } + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::ColorCubeBG&) override + { + return std::unexpected(FMTResult::FunctionNotImpl); + /*BufferReadManip(buffer).BasicReadType("\033[48;5;", t.GetColorRef(), 'm');*/ + } + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::ColorCube&) override + { + return std::unexpected(FMTResult::FunctionNotImpl); + /*BufferReadManip(buffer).BasicReadType("\033[48;5;", t.Fg.GetColorRef(), ";48;5;", t.Bg.GetColorRef(), 'm');*/ + } + + public: + [[nodiscard]] std::expected reset_front() override + { + return std::unexpected(FMTResult::FunctionNotImpl); + /*BufferReadManip(buffer).BasicReadType('\033', '[', detail::TextProperties::TextFront::FrontID::DefaultFrontID, 'm');*/ + } + [[nodiscard]] std::expected ExecuteFront(const detail::TextProperties::TextFront::FrontID&) override + { + return std::unexpected(FMTResult::FunctionNotImpl); + /*BufferReadManip(buffer).BasicReadType('\033', '[', t.ID, 'm');*/ + } + + public: + [[nodiscard]] std::expected ResetStyle() override + { + return std::unexpected(FMTResult::FunctionNotImpl); + /*BufferReadManip(buffer).BasicReadType('\033', '[', 0, 'm');*/ + } + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Intensity&) override + { + return std::unexpected(FMTResult::FunctionNotImpl); + /*BufferReadManip(buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ + } + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Italic&) override + { + return std::unexpected(FMTResult::FunctionNotImpl); + /*BufferReadManip(buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ + } + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Underline&) override + { + return std::unexpected(FMTResult::FunctionNotImpl); + /*BufferReadManip(buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ + } + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::UnderlineColor::Color&) override + { + return std::unexpected(FMTResult::FunctionNotImpl); + /*BufferReadManip(buffer).BasicReadType("\033[59m");*/ + } + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::UnderlineColor::ColorCube&) override + { + return std::unexpected(FMTResult::FunctionNotImpl); + /*BufferReadManip(buffer).BasicReadType("\033[58;5;", t.GetColorRef(), 'm');*/ + } + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::UnderlineColor::Color24b&) override + { + return std::unexpected(FMTResult::FunctionNotImpl); + /*BufferReadManip(buffer).BasicReadType("\033[58;2;", t.R, ';', t.G, ';', t.B, 'm');*/ + } + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Blink&) override + { + return std::unexpected(FMTResult::FunctionNotImpl); + /*BufferReadManip(buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ + } + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Inverted&) override + { + return std::unexpected(FMTResult::FunctionNotImpl); + /*BufferReadManip(buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ + } + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Ideogram&) override + { + return std::unexpected(FMTResult::FunctionNotImpl); + /*BufferReadManip(buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ + } + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Script&) override + { + return std::unexpected(FMTResult::FunctionNotImpl); + /*BufferReadManip(buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ + } + }; +} diff --git a/src/StreamFormat/FMT/Context/ParserExecutor/ParserType.h b/src/stream/fmt/context/parser_executor/parser_type.h similarity index 74% rename from src/StreamFormat/FMT/Context/ParserExecutor/ParserType.h rename to src/stream/fmt/context/parser_executor/parser_type.h index 0e6bfb46..1350763c 100644 --- a/src/StreamFormat/FMT/Context/ParserExecutor/ParserType.h +++ b/src/stream/fmt/context/parser_executor/parser_type.h @@ -1,14 +1,14 @@ #pragma once -#include "StreamFormat/FMT/Detail/Prelude.h" +#include "stream/fmt/detail/prelude.h" #define STREAMFORMAT_PARSER_DECLARED -namespace StreamFormat::FMT +namespace stream::fmt { template > struct ParserType { - static inline bool Parse(T&, ParserExecutor&) + static inline bool parse(T&, ParserExecutor&) { #ifdef UNKOWN_TYPE_MESSAGE // FIXME @@ -29,7 +29,7 @@ namespace StreamFormat::FMT #define STREAMFORMAT_AUTO_PARSER(Type, fmt, ...) \ template \ - struct StreamFormat::FMT::ParserType \ + struct stream::fmt::ParserType \ { \ - static bool Parse(Type& value, ParserExecutor& executor) { return executor.Run(fmt, __VA_ARGS__); } \ + static bool parse(Type& value, ParserExecutor& executor) { return executor.Run(fmt, __VA_ARGS__); } \ }; diff --git a/src/StreamFormat/FMT/Context/ParserExecutor/UtilityFunctions.h b/src/stream/fmt/context/parser_executor/utility_functions.h similarity index 57% rename from src/StreamFormat/FMT/Context/ParserExecutor/UtilityFunctions.h rename to src/stream/fmt/context/parser_executor/utility_functions.h index 0f982c7f..b1686316 100644 --- a/src/StreamFormat/FMT/Context/ParserExecutor/UtilityFunctions.h +++ b/src/stream/fmt/context/parser_executor/utility_functions.h @@ -2,21 +2,21 @@ #include "BasicParserExecutor.h" -#include "StreamFormat/FMT/Buffer/BufferOutManager/GivenBufferOutManager.h" -#include "StreamFormat/FMT/Buffer/BufferOutManager/StaticBufferOutManager.h" +#include "stream/fmt/buffer/buffer_out_manager/given_buffer_out_manager.h" +#include "stream/fmt/buffer/buffer_out_manager/static_buffer_out_manager.h" #include "ParserTextPropertiesExecutor/ParserANSITextPropertiesExecutor.h" -namespace StreamFormat::FMT +namespace stream::fmt { template - [[nodiscard]] std::expected Parse(Buffer&& bufferInput, Format&& formatInput, Args&&... args) + [[nodiscard]] std::expected parse(Buffer&& bufferInput, Format&& formatInput, Args&&... args) { - Detail::BufferInfoView buffer{bufferInput}; - Detail::BufferInfoView format{formatInput}; + detail::BufferInfoView buffer{bufferInput}; + detail::BufferInfoView format{formatInput}; using TChar = typename decltype(format)::TChar; - Detail::ParserNOTextPropertiesExecutor> textPropertiesExecutor; + detail::ParserNOTextPropertiesExecutor> textPropertiesExecutor; Context::BasicParserExecutor> executor(buffer, textPropertiesExecutor); SF_TRY(executor.Run(format, std::forward(args)...)); return executor.Terminate(); diff --git a/src/StreamFormat/FMT/Context/Utils/ContextFunctions.h b/src/stream/fmt/context/utils/context_functions.h similarity index 75% rename from src/StreamFormat/FMT/Context/Utils/ContextFunctions.h rename to src/stream/fmt/context/utils/context_functions.h index d514d24d..d5404e7d 100644 --- a/src/StreamFormat/FMT/Context/Utils/ContextFunctions.h +++ b/src/stream/fmt/context/utils/context_functions.h @@ -1,8 +1,8 @@ #pragma once -#include "StreamFormat/FMT/Detail/Specifiers.h" +#include "stream/fmt/detail/specifiers.h" -namespace StreamFormat::FMT::Detail +namespace stream::fmt::detail { template struct FunctionApplyNextOverride @@ -17,6 +17,6 @@ namespace StreamFormat::FMT::Detail inline ~FunctionApplyNextOverride() { Executor.Data = FormatData; } FormatterExecutor& Executor; - Detail::FormatData FormatData; + detail::FormatData FormatData; }; } diff --git a/src/StreamFormat/FMT/Detail/ConvertTraits.h b/src/stream/fmt/detail/convert_traits.h similarity index 93% rename from src/StreamFormat/FMT/Detail/ConvertTraits.h rename to src/stream/fmt/detail/convert_traits.h index 59185934..85efc0d6 100644 --- a/src/StreamFormat/FMT/Detail/ConvertTraits.h +++ b/src/stream/fmt/detail/convert_traits.h @@ -1,8 +1,8 @@ #pragma once -#include "Prelude.h" +#include "prelude.h" -namespace StreamFormat::FMT::Detail +namespace stream::fmt::detail { template struct FormatTypeForwardAs @@ -47,7 +47,7 @@ namespace StreamFormat::FMT::Detail }; template - requires(std::is_same_v, Detail::GetBaseType>) struct FMTContextSame + requires(std::is_same_v, detail::GetBaseType>) struct FMTContextSame { static constexpr bool SameAs = true; }; diff --git a/src/StreamFormat/FMT/Detail/FMTResult.h b/src/stream/fmt/detail/fmt_result.h similarity index 75% rename from src/StreamFormat/FMT/Detail/FMTResult.h rename to src/stream/fmt/detail/fmt_result.h index 5b580c50..80c4e916 100644 --- a/src/StreamFormat/FMT/Detail/FMTResult.h +++ b/src/stream/fmt/detail/fmt_result.h @@ -1,8 +1,8 @@ #pragma once -#include "StreamFormat/Core/Prelude.h" +#include "stream/core/prelude.h" -namespace StreamFormat::FMT +namespace stream::fmt { enum class FMTResult { @@ -36,14 +36,14 @@ namespace StreamFormat::FMT }; } -namespace StreamFormat::Detail +namespace stream::detail { template<> - inline FMT::FMTResult forward_error(FMT::FMTResult t) + inline fmt::FMTResult forward_error(fmt::FMTResult t) { - if (t == FMT::FMTResult::ArgsInterface_CantMatchNamedArgs) + if (t == fmt::FMTResult::ArgsInterface_CantMatchNamedArgs) return t; - if (t == FMT::FMTResult::Manager_StaticMemory) + if (t == fmt::FMTResult::Manager_StaticMemory) return t; return t; } diff --git a/src/StreamFormat/FMT/Detail/IndentHandlers.h b/src/stream/fmt/detail/indent_handlers.h similarity index 57% rename from src/StreamFormat/FMT/Detail/IndentHandlers.h rename to src/stream/fmt/detail/indent_handlers.h index ee102aad..cb1e5171 100644 --- a/src/StreamFormat/FMT/Detail/IndentHandlers.h +++ b/src/stream/fmt/detail/indent_handlers.h @@ -1,9 +1,9 @@ #pragma once -#include "StreamFormat/FMT/Detail/Prelude.h" -#include "StreamFormat/FMT/Buffer/FMTBufferOutManip.h" +#include "stream/fmt/detail/prelude.h" +#include "stream/fmt/buffer/fmt_buffer_out_manip.h" -namespace StreamFormat::FMT::Detail +namespace stream::fmt::detail { template struct NoStrideFunction @@ -13,7 +13,7 @@ namespace StreamFormat::FMT::Detail , SizeBuffer(BufferAccess(buffer).GetBufferCurrentSize()) {} - ~NoStrideFunction() { FMTBufferOutManip(Buffer).AddNoStride(BufferAccess(Buffer).GetBufferCurrentSize() - SizeBuffer); } + ~NoStrideFunction() { FMTBufferOutManip(buffer).AddNoStride(BufferAccess(buffer).GetBufferCurrentSize() - SizeBuffer); } FMTBufferOutInfo& Buffer; std::size_t SizeBuffer; diff --git a/src/StreamFormat/FMT/Detail/Prelude.h b/src/stream/fmt/detail/prelude.h similarity index 82% rename from src/StreamFormat/FMT/Detail/Prelude.h rename to src/stream/fmt/detail/prelude.h index 09b12642..cae33a7a 100644 --- a/src/StreamFormat/FMT/Detail/Prelude.h +++ b/src/stream/fmt/detail/prelude.h @@ -1,8 +1,8 @@ #pragma once -#include "StreamFormat/Core/Prelude.h" -#include "TypesTraits.h" -#include "FMTResult.h" +#include "stream/core/prelude.h" +#include "types_traits.h" +#include "fmt_result.h" #define UNKOWN_TYPE_MESSAGE @@ -24,7 +24,7 @@ // End writing all writer and reader (string / char pt) // -namespace StreamFormat::FMT::Context +namespace stream::fmt::context { template class BasicContext; diff --git a/src/StreamFormat/FMT/Detail/Specifiers.h b/src/stream/fmt/detail/specifiers.h similarity index 98% rename from src/StreamFormat/FMT/Detail/Specifiers.h rename to src/stream/fmt/detail/specifiers.h index 8a170cbc..216e6bb0 100644 --- a/src/StreamFormat/FMT/Detail/Specifiers.h +++ b/src/stream/fmt/detail/specifiers.h @@ -1,13 +1,13 @@ #pragma once -#include "StreamFormat/Core/Prelude.h" -#include "StreamFormat/Core/Prelude.h" +#include "stream/core/prelude.h" +#include "stream/core/prelude.h" #include #include #include -namespace StreamFormat::FMT::Detail +namespace stream::fmt::detail { enum class IntegerPrintBase : char { @@ -66,7 +66,7 @@ namespace StreamFormat::FMT::Detail }; } -namespace StreamFormat::FMT::Detail +namespace stream::fmt::detail { template struct FormatSpecifier diff --git a/src/StreamFormat/FMT/Detail/TypesTraits.h b/src/stream/fmt/detail/types_traits.h similarity index 87% rename from src/StreamFormat/FMT/Detail/TypesTraits.h rename to src/stream/fmt/detail/types_traits.h index e36bd63e..ffcba64e 100644 --- a/src/StreamFormat/FMT/Detail/TypesTraits.h +++ b/src/stream/fmt/detail/types_traits.h @@ -1,10 +1,10 @@ #pragma once -#include "StreamFormat/Core/Prelude.h" +#include "stream/core/prelude.h" #include -namespace StreamFormat::FMT::Detail +namespace stream::fmt::detail { template using GetBaseType = std::remove_cv_t>; diff --git a/src/StreamFormat/FMT/Serializers/CompilationData.h b/src/stream/fmt/serializers/compilation_data.h similarity index 70% rename from src/StreamFormat/FMT/Serializers/CompilationData.h rename to src/stream/fmt/serializers/compilation_data.h index 1cd53a9b..d3a6bd83 100644 --- a/src/StreamFormat/FMT/Serializers/CompilationData.h +++ b/src/stream/fmt/serializers/compilation_data.h @@ -1,9 +1,9 @@ #pragma once -#include "StreamFormat/Core/Prelude.h" -#include "StreamFormat/FLog.h" +#include "stream/core/prelude.h" +#include "stream/flog.h" -namespace StreamFormat::FMT::Detail +namespace stream::fmt::detail { struct FileLocation { @@ -40,29 +40,29 @@ namespace StreamFormat::FMT::Detail }; } -#define STREAMFORMAT_FMT_FILE_LOCATION() StreamFormat::FMT::Detail::FileLocation(__FILE__, __LINE__) -#define STREAMFORMAT_FMT_FUNCTION_PROPERTIES() StreamFormat::FMT::Detail::FunctionProperties(STREAMFORMAT_FMT_FILE_LOCATION(), __FUNCTION__, __FUNCSIG__, __FUNCDNAME__) +#define STREAMFORMAT_FMT_FILE_LOCATION() stream::fmt::detail::FileLocation(__FILE__, __LINE__) +#define STREAMFORMAT_FMT_FUNCTION_PROPERTIES() stream::fmt::detail::FunctionProperties(STREAMFORMAT_FMT_FILE_LOCATION(), __FUNCTION__, __FUNCSIG__, __FUNCDNAME__) -namespace StreamFormat::FMT +namespace stream::fmt { template - struct FormatterType + struct FormatterType { - [[nodiscard]] static inline std::expected Format(const Detail::FileLocation& t, FormatterExecutor& executor) + [[nodiscard]] static inline std::expected format(const detail::FileLocation& t, FormatterExecutor& executor) { SF_TRY(executor.WriteType(t.FileName)); - SF_TRY(executor.BufferOut.Pushback(':')); + SF_TRY(executor.buffer_out.Pushback(':')); return executor.WriteType(t.FileLine); } }; template - struct FormatterType + struct FormatterType { - [[nodiscard]] static inline std::expected Format(const Detail::FunctionProperties& t, FormatterExecutor& executor) + [[nodiscard]] static inline std::expected format(const detail::FunctionProperties& t, FormatterExecutor& executor) { SF_TRY(executor.WriteType(t.Location)); - SF_TRY(executor.BufferOut.WriteCharArray(" @ ")); + SF_TRY(executor.buffer_out.WriteCharArray(" @ ")); return executor.WriteType(t.FunctionName); } }; diff --git a/src/StreamFormat/FMT/Serializers/FormatChrono.h b/src/stream/fmt/serializers/format_chrono.h similarity index 81% rename from src/StreamFormat/FMT/Serializers/FormatChrono.h rename to src/stream/fmt/serializers/format_chrono.h index 20c028c4..da39e39e 100644 --- a/src/StreamFormat/FMT/Serializers/FormatChrono.h +++ b/src/stream/fmt/serializers/format_chrono.h @@ -1,15 +1,15 @@ #pragma once -#include "StreamFormat/FMT/Buffer/BufferTestManip.h" -#include "StreamFormat/FMT/Buffer/BufferWriteManip.h" -#include "StreamFormat/FMT/Buffer/BufferReadManip.h" -#include "StreamFormat/FMT/Buffer/FMTBufferWriteManip.h" +#include "stream/fmt/buffer/buffer_test_manip.h" +#include "stream/fmt/buffer/buffer_write_manip.h" +#include "stream/fmt/buffer/buffer_read_manip.h" +#include "stream/fmt/buffer/FMTBufferWriteManip.h" -#include "StreamFormat/FMT/Context/FormatterExecutor/BasicFormatterExecutor.h" +#include "stream/fmt/context/formatter_executor/basic_formatter_executor.h" #include -namespace StreamFormat::FMT::Detail +namespace stream::fmt::detail { enum class TimePrintMode : std::uint8_t { @@ -22,8 +22,8 @@ namespace StreamFormat::FMT::Detail [[nodiscard]] std::expected WriteSubTime_(const std::chrono::time_point& value, BufferInfoView& pattern, FMTBufferOutInfo& buffer, TimePrintMode mode) { ShiftInfo shift; - shift.Type = Detail::ShiftInfo::ShiftType::Right; - shift.Print = Detail::ShiftInfo::ShiftPrint('0', ' '); + shift.Type = detail::ShiftInfo::ShiftType::Right; + shift.Print = detail::ShiftInfo::ShiftPrint('0', ' '); shift.Size = 0; (void)BufferReadManip(pattern).FastReadInteger(shift.Size); @@ -119,44 +119,44 @@ namespace StreamFormat::FMT::Detail } } -namespace StreamFormat::FMT +namespace stream::fmt { template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static inline std::expected Format(const std::chrono::time_point& t, FormatterExecutor& executor) + [[nodiscard]] static inline std::expected format(const std::chrono::time_point& t, FormatterExecutor& executor) { - return Detail::WriteTime(t, Detail::BufferInfoView(executor.Data.Specifiers.GetAsText("pattern", "%h:%m:%s.%ms")), executor.BufferOut); + return detail::WriteTime(t, detail::BufferInfoView(executor.Data.Specifiers.GetAsText("pattern", "%h:%m:%s.%ms")), executor.buffer_out); } }; template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static inline std::expected Format(const std::chrono::duration& t, FormatterExecutor& executor) + [[nodiscard]] static inline std::expected format(const std::chrono::duration& t, FormatterExecutor& executor) { if (executor.Data.Specifiers.Has("pattern")) { - return Detail::WriteTime( + return detail::WriteTime( std::chrono::time_point>(t), - Detail::BufferInfoView(executor.Data.Specifiers.GetAsText("pattern", "%h:%m:%s.%ms")), - executor.BufferOut + detail::BufferInfoView(executor.Data.Specifiers.GetAsText("pattern", "%h:%m:%s.%ms")), + executor.buffer_out ); } - SF_TRY(Detail::BufferWriteManip(executor.BufferOut).FastWriteInteger(t.count())); + SF_TRY(detail::BufferWriteManip(executor.buffer_out).FastWriteInteger(t.count())); if constexpr (std::is_same_v, std::chrono::seconds>) - { SF_TRY(Detail::BufferOutManip(executor.BufferOut).Pushback('s')); } + { SF_TRY(detail::BufferOutManip(executor.buffer_out).Pushback('s')); } else if constexpr (std::is_same_v, std::chrono::minutes>) - { SF_TRY(Detail::BufferOutManip(executor.BufferOut).Pushback('m')); } + { SF_TRY(detail::BufferOutManip(executor.buffer_out).Pushback('m')); } else if constexpr (std::is_same_v, std::chrono::hours>) - { SF_TRY(Detail::BufferOutManip(executor.BufferOut).Pushback('h')); } + { SF_TRY(detail::BufferOutManip(executor.buffer_out).Pushback('h')); } else if constexpr (std::is_same_v, std::chrono::milliseconds>) - { SF_TRY(Detail::BufferOutManip(executor.BufferOut).Pushback('m', 's')); } + { SF_TRY(detail::BufferOutManip(executor.buffer_out).Pushback('m', 's')); } else if constexpr (std::is_same_v, std::chrono::microseconds>) - { SF_TRY(Detail::BufferOutManip(executor.BufferOut).Pushback('u', 's')); } + { SF_TRY(detail::BufferOutManip(executor.buffer_out).Pushback('u', 's')); } else if constexpr (std::is_same_v, std::chrono::nanoseconds>) - { SF_TRY(Detail::BufferOutManip(executor.BufferOut).Pushback('n', 's')); } + { SF_TRY(detail::BufferOutManip(executor.buffer_out).Pushback('n', 's')); } return {}; } diff --git a/src/StreamFormat/FMT/Serializers/FormatSTDLib.h b/src/stream/fmt/serializers/format_stdlib.h similarity index 65% rename from src/StreamFormat/FMT/Serializers/FormatSTDLib.h rename to src/stream/fmt/serializers/format_stdlib.h index ce7abfe9..4ba622f0 100644 --- a/src/StreamFormat/FMT/Serializers/FormatSTDLib.h +++ b/src/stream/fmt/serializers/format_stdlib.h @@ -1,13 +1,13 @@ #pragma once -#include "StreamFormat/FMT/Context/FormatterExecutor/BasicFormatterExecutor.h" +#include "stream/fmt/context/formatter_executor/basic_formatter_executor.h" #include #include #include #include -namespace StreamFormat::FMT +namespace stream::fmt { //------------------------------------------// //----------------- String -----------------// @@ -16,22 +16,22 @@ namespace StreamFormat::FMT template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static inline std::expected Format(const std::basic_string& t, FormatterExecutor& executor) - { return Detail::BufferWriteManip(executor.BufferOut).FastWriteString(t); } + [[nodiscard]] static inline std::expected format(const std::basic_string& t, FormatterExecutor& executor) + { return detail::BufferWriteManip(executor.buffer_out).FastWriteString(t); } }; template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static inline std::expected Format(std::basic_string_view t, FormatterExecutor& executor) - { return Detail::BufferWriteManip(executor.BufferOut).FastWriteString(t); } + [[nodiscard]] static inline std::expected format(std::basic_string_view t, FormatterExecutor& executor) + { return detail::BufferWriteManip(executor.buffer_out).FastWriteString(t); } }; template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static inline std::expected Format(const std::basic_stringstream& t, FormatterExecutor& executor) - { return Detail::BufferWriteManip(executor.BufferOut).FastWriteCharArray(t.str(), t.size()); } + [[nodiscard]] static inline std::expected format(const std::basic_stringstream& t, FormatterExecutor& executor) + { return detail::BufferWriteManip(executor.buffer_out).FastWriteCharArray(t.str(), t.size()); } }; //------------------------------------------// @@ -42,12 +42,12 @@ namespace StreamFormat::FMT template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static inline std::expected Format(const std::unique_ptr& t, FormatterExecutor& executor) + [[nodiscard]] static inline std::expected format(const std::unique_ptr& t, FormatterExecutor& executor) { if (executor.Data.TrueValue) - return FormatterType::Format(t.get(), executor); + return FormatterType::format(t.get(), executor); else - return FormatterType::Format(*t, executor); + return FormatterType::format(*t, executor); return {}; } @@ -57,12 +57,12 @@ namespace StreamFormat::FMT template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static inline std::expected Format(const std::shared_ptr& t, FormatterExecutor& executor) + [[nodiscard]] static inline std::expected format(const std::shared_ptr& t, FormatterExecutor& executor) { if (executor.Data.TrueValue) - return FormatterType::Format(t.get(), executor); + return FormatterType::format(t.get(), executor); else - return FormatterType::Format(*t, executor); + return FormatterType::format(*t, executor); return {}; } @@ -72,7 +72,7 @@ namespace StreamFormat::FMT template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static inline std::expected Format(const std::weak_ptr& t, FormatterExecutor& executor) - { return FormatterType, FormatterExecutor>::Format(t.lock(), executor); } + [[nodiscard]] static inline std::expected format(const std::weak_ptr& t, FormatterExecutor& executor) + { return FormatterType, FormatterExecutor>::format(t.lock(), executor); } }; } diff --git a/src/stream/fmt/serializers/parse_chrono.h b/src/stream/fmt/serializers/parse_chrono.h new file mode 100644 index 00000000..964e2d3f --- /dev/null +++ b/src/stream/fmt/serializers/parse_chrono.h @@ -0,0 +1,14 @@ +#pragma once + +#include +#include "stream/fmt/context/ParserExecutor/BasicParserExecutor.h" + +namespace stream::fmt::detail +{ + +} + +namespace stream::fmt +{ + +} diff --git a/src/stream/fmt/serializers/parse_stdlib.h b/src/stream/fmt/serializers/parse_stdlib.h new file mode 100644 index 00000000..55907913 --- /dev/null +++ b/src/stream/fmt/serializers/parse_stdlib.h @@ -0,0 +1,12 @@ +#pragma once + +#include "stream/fmt/context/ParserExecutor/BasicParserExecutor.h" + +#include +#include +#include + +namespace stream::fmt +{ + // TODO: +} diff --git a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_array.h b/src/stream/fmt/serializers/std_container/FMT_array.h similarity index 60% rename from src/StreamFormat/FMT/Serializers/STDContainer/FMT_array.h rename to src/stream/fmt/serializers/std_container/FMT_array.h index f7466c74..a3183f2a 100644 --- a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_array.h +++ b/src/stream/fmt/serializers/std_container/FMT_array.h @@ -1,16 +1,16 @@ #pragma once #include -#include "StreamFormat/FMT/Context/FormatterExecutor/FormatterType.h" +#include "stream/fmt/context/formatter_executor/formatter_type.h" -namespace StreamFormat::FMT +namespace stream::fmt { template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static inline std::expected Format(const std::array& t, FormatterExecutor& executor) + [[nodiscard]] static inline std::expected format(const std::array& t, FormatterExecutor& executor) { - return FormatterType>, FormatterExecutor>::Format(t, executor); + return FormatterType>, FormatterExecutor>::format(t, executor); } }; } diff --git a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_deque.h b/src/stream/fmt/serializers/std_container/FMT_deque.h similarity index 57% rename from src/StreamFormat/FMT/Serializers/STDContainer/FMT_deque.h rename to src/stream/fmt/serializers/std_container/FMT_deque.h index 715d7f1f..6f59ef21 100644 --- a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_deque.h +++ b/src/stream/fmt/serializers/std_container/FMT_deque.h @@ -1,14 +1,14 @@ #pragma once #include -#include "StreamFormat/FMT/Context/FormatterExecutor/FormatterType.h" +#include "stream/fmt/context/formatter_executor/formatter_type.h" -namespace StreamFormat::FMT +namespace stream::fmt { template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static inline std::expected Format(const std::deque& t, FormatterExecutor& executor) - { return FormatterType>, FormatterExecutor>::Format(t, executor); } + [[nodiscard]] static inline std::expected format(const std::deque& t, FormatterExecutor& executor) + { return FormatterType>, FormatterExecutor>::format(t, executor); } }; } diff --git a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_forward_list.h b/src/stream/fmt/serializers/std_container/FMT_forward_list.h similarity index 60% rename from src/StreamFormat/FMT/Serializers/STDContainer/FMT_forward_list.h rename to src/stream/fmt/serializers/std_container/FMT_forward_list.h index 6214bc06..ef7a5992 100644 --- a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_forward_list.h +++ b/src/stream/fmt/serializers/std_container/FMT_forward_list.h @@ -1,16 +1,16 @@ #pragma once #include -#include "StreamFormat/FMT/Context/FormatterExecutor/FormatterType.h" +#include "stream/fmt/context/formatter_executor/formatter_type.h" -namespace StreamFormat::FMT +namespace stream::fmt { template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static inline std::expected Format(const std::forward_list& t, FormatterExecutor& executor) + [[nodiscard]] static inline std::expected format(const std::forward_list& t, FormatterExecutor& executor) { - return FormatterType>, FormatterExecutor>::Format(t, executor); + return FormatterType>, FormatterExecutor>::format(t, executor); } }; } diff --git a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_list.h b/src/stream/fmt/serializers/std_container/FMT_list.h similarity index 57% rename from src/StreamFormat/FMT/Serializers/STDContainer/FMT_list.h rename to src/stream/fmt/serializers/std_container/FMT_list.h index b4a166af..60878f3f 100644 --- a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_list.h +++ b/src/stream/fmt/serializers/std_container/FMT_list.h @@ -1,14 +1,14 @@ #pragma once #include -#include "StreamFormat/FMT/Context/FormatterExecutor/FormatterType.h" +#include "stream/fmt/context/formatter_executor/formatter_type.h" -namespace StreamFormat::FMT +namespace stream::fmt { template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static inline std::expected Format(const std::list& t, FormatterExecutor& executor) - { return FormatterType>, FormatterExecutor>::Format(t, executor); } + [[nodiscard]] static inline std::expected format(const std::list& t, FormatterExecutor& executor) + { return FormatterType>, FormatterExecutor>::format(t, executor); } }; } diff --git a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_map.h b/src/stream/fmt/serializers/std_container/FMT_map.h similarity index 66% rename from src/StreamFormat/FMT/Serializers/STDContainer/FMT_map.h rename to src/stream/fmt/serializers/std_container/FMT_map.h index 98f2da40..d676a352 100644 --- a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_map.h +++ b/src/stream/fmt/serializers/std_container/FMT_map.h @@ -1,27 +1,27 @@ #pragma once #include -#include "StreamFormat/FMT/Context/FormatterExecutor/FormatterType.h" +#include "stream/fmt/context/formatter_executor/formatter_type.h" #include "FMT_tuple.h" -namespace StreamFormat::FMT +namespace stream::fmt { template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static inline std::expected Format(const std::map& t, FormatterExecutor& executor) + [[nodiscard]] static inline std::expected format(const std::map& t, FormatterExecutor& executor) { - return FormatterType>, FormatterExecutor>::Format(t, executor); + return FormatterType>, FormatterExecutor>::format(t, executor); } }; template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static inline std::expected Format(const std::multimap& t, FormatterExecutor& executor) + [[nodiscard]] static inline std::expected format(const std::multimap& t, FormatterExecutor& executor) { - return ormatterType>, FormatterExecutor>::Format(t, executor); + return ormatterType>, FormatterExecutor>::format(t, executor); } }; } diff --git a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_queue.h b/src/stream/fmt/serializers/std_container/FMT_queue.h similarity index 65% rename from src/StreamFormat/FMT/Serializers/STDContainer/FMT_queue.h rename to src/stream/fmt/serializers/std_container/FMT_queue.h index 8bdca2ec..08be1fc2 100644 --- a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_queue.h +++ b/src/stream/fmt/serializers/std_container/FMT_queue.h @@ -1,14 +1,14 @@ #pragma once #include -#include "StreamFormat/FMT/Context/FormatterExecutor/FormatterType.h" +#include "stream/fmt/context/formatter_executor/formatter_type.h" -namespace StreamFormat::FMT +namespace stream::fmt { template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static inline std::expected Format(const std::queue& t, FormatterExecutor& executor) + [[nodiscard]] static inline std::expected format(const std::queue& t, FormatterExecutor& executor) { return std::unexpected(FMTResult::FunctionNotImpl); } diff --git a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_set.h b/src/stream/fmt/serializers/std_container/FMT_set.h similarity index 62% rename from src/StreamFormat/FMT/Serializers/STDContainer/FMT_set.h rename to src/stream/fmt/serializers/std_container/FMT_set.h index 5724c3d5..d3d4c312 100644 --- a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_set.h +++ b/src/stream/fmt/serializers/std_container/FMT_set.h @@ -1,21 +1,21 @@ #pragma once #include -#include "StreamFormat/FMT/Context/FormatterExecutor/FormatterType.h" +#include "stream/fmt/context/formatter_executor/formatter_type.h" -namespace StreamFormat::FMT +namespace stream::fmt { template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static inline std::expected Format(const std::set& t, FormatterExecutor& executor) - { return FormatterType>, FormatterExecutor>::Format(t, executor); } + [[nodiscard]] static inline std::expected format(const std::set& t, FormatterExecutor& executor) + { return FormatterType>, FormatterExecutor>::format(t, executor); } }; template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static inline std::expected Format(const std::multiset& t, FormatterExecutor& executor) - { return FormatterType>, FormatterExecutor>::Format(t, executor); } + [[nodiscard]] static inline std::expected format(const std::multiset& t, FormatterExecutor& executor) + { return FormatterType>, FormatterExecutor>::format(t, executor); } }; } diff --git a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_stack.h b/src/stream/fmt/serializers/std_container/FMT_stack.h similarity index 62% rename from src/StreamFormat/FMT/Serializers/STDContainer/FMT_stack.h rename to src/stream/fmt/serializers/std_container/FMT_stack.h index 7468b1e7..3417791e 100644 --- a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_stack.h +++ b/src/stream/fmt/serializers/std_container/FMT_stack.h @@ -1,15 +1,15 @@ #pragma once #include -#include "StreamFormat/FMT/Context/FormatterExecutor/FormatterType.h" +#include "stream/fmt/context/formatter_executor/formatter_type.h" -namespace StreamFormat::FMT +namespace stream::fmt { /* template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static inline std::expected Format(const std::stack& t, FormatterExecutor& executor) { + [[nodiscard]] static inline std::expected format(const std::stack& t, FormatterExecutor& executor) { } }; */ diff --git a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_tuple.h b/src/stream/fmt/serializers/std_container/FMT_tuple.h similarity index 75% rename from src/StreamFormat/FMT/Serializers/STDContainer/FMT_tuple.h rename to src/stream/fmt/serializers/std_container/FMT_tuple.h index 4fcdb2bd..7c706a25 100644 --- a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_tuple.h +++ b/src/stream/fmt/serializers/std_container/FMT_tuple.h @@ -2,9 +2,9 @@ #include #include -#include "StreamFormat/FMT/Context/FormatterExecutor/FormatterType.h" +#include "stream/fmt/context/formatter_executor/formatter_type.h" -namespace StreamFormat::FMT::TupleDetail +namespace stream::fmt::TupleDetail { template using NthTypeOf = typename std::tuple_element>::type; @@ -32,20 +32,20 @@ namespace StreamFormat::FMT::TupleDetail [[nodiscard]] static inline std::expected TupleFormatRec(FormatterExecutor& executor, const T& t, Args&&... args) { SF_TRY(executor.WriteType(t)); - SF_TRY(executor.BufferOut.Pushback(',')); - SF_TRY(executor.BufferOut.Pushback(' ')); + SF_TRY(executor.buffer_out.Pushback(',')); + SF_TRY(executor.buffer_out.Pushback(' ')); return TupleFormatRec(context, args...); } } -namespace StreamFormat::FMT +namespace stream::fmt { template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static inline std::expected Format(const std::tuple& t, FormatterExecutor& executor) + [[nodiscard]] static inline std::expected format(const std::tuple& t, FormatterExecutor& executor) { - SF_TRY(executor.BufferOut.Pushback('<')); + SF_TRY(executor.buffer_out.Pushback('<')); std::expected err = {}; std::apply([&context, &err](auto&&... args) { @@ -53,20 +53,20 @@ namespace StreamFormat::FMT if (not res) { err = res.error(); } }, t); - SF_TRY(executor.BufferOut.Pushback('>')); + SF_TRY(executor.buffer_out.Pushback('>')); } }; template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static inline std::expected Format(const std::pair& t, FormatterExecutor& executor) + [[nodiscard]] static inline std::expected format(const std::pair& t, FormatterExecutor& executor) { - SF_TRY(executor.BufferOut.Pushback('<')); + SF_TRY(executor.buffer_out.Pushback('<')); SF_TRY(executor.WriteType(t.first)); - SF_TRY(executor.BufferOut.Pushback(':')); + SF_TRY(executor.buffer_out.Pushback(':')); SF_TRY(executor.WriteType(t.second)); - SF_TRY(executor.BufferOut.Pushback('>')); + SF_TRY(executor.buffer_out.Pushback('>')); return {}; } diff --git a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_unordered_map.h b/src/stream/fmt/serializers/std_container/FMT_unordered_map.h similarity index 66% rename from src/StreamFormat/FMT/Serializers/STDContainer/FMT_unordered_map.h rename to src/stream/fmt/serializers/std_container/FMT_unordered_map.h index 8c5383c9..13928e6f 100644 --- a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_unordered_map.h +++ b/src/stream/fmt/serializers/std_container/FMT_unordered_map.h @@ -1,27 +1,27 @@ #pragma once -#include "StreamFormat/FMT/Context/FormatterExecutor/FormatterType.h" +#include "stream/fmt/context/formatter_executor/formatter_type.h" #include #include "FMT_tuple.h" -namespace StreamFormat::FMT +namespace stream::fmt { template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static inline std::expected Format(const std::unordered_map& t, FormatterExecutor& executor) + [[nodiscard]] static inline std::expected format(const std::unordered_map& t, FormatterExecutor& executor) { - return FormatterType>, FormatterExecutor>::Format(t, executor); + return FormatterType>, FormatterExecutor>::format(t, executor); } }; template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static inline std::expected Format(const std::unordered_multimap& t, FormatterExecutor& executor) + [[nodiscard]] static inline std::expected format(const std::unordered_multimap& t, FormatterExecutor& executor) { - return FormatterType>, FormatterExecutor>::Format(t, executor); + return FormatterType>, FormatterExecutor>::format(t, executor); } }; } diff --git a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_unordered_set.h b/src/stream/fmt/serializers/std_container/FMT_unordered_set.h similarity index 64% rename from src/StreamFormat/FMT/Serializers/STDContainer/FMT_unordered_set.h rename to src/stream/fmt/serializers/std_container/FMT_unordered_set.h index f7b37e08..f74a6f0e 100644 --- a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_unordered_set.h +++ b/src/stream/fmt/serializers/std_container/FMT_unordered_set.h @@ -1,25 +1,25 @@ #pragma once #include -#include "StreamFormat/FMT/Context/FormatterExecutor/FormatterType.h" +#include "stream/fmt/context/formatter_executor/formatter_type.h" -namespace StreamFormat::FMT +namespace stream::fmt { template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static inline std::expected Format(const std::unordered_set& t, FormatterExecutor& executor) + [[nodiscard]] static inline std::expected format(const std::unordered_set& t, FormatterExecutor& executor) { - return FormatterType>, FormatterExecutor>::Format(t, executor); + return FormatterType>, FormatterExecutor>::format(t, executor); } }; template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static inline std::expected Format(const std::unordered_multiset& t, FormatterExecutor& executor) + [[nodiscard]] static inline std::expected format(const std::unordered_multiset& t, FormatterExecutor& executor) { - return FormatterType>, FormatterExecutor>::Format(t, executor); + return FormatterType>, FormatterExecutor>::format(t, executor); } }; } diff --git a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_vector.h b/src/stream/fmt/serializers/std_container/FMT_vector.h similarity index 57% rename from src/StreamFormat/FMT/Serializers/STDContainer/FMT_vector.h rename to src/stream/fmt/serializers/std_container/FMT_vector.h index 921fa8a3..897a7a6a 100644 --- a/src/StreamFormat/FMT/Serializers/STDContainer/FMT_vector.h +++ b/src/stream/fmt/serializers/std_container/FMT_vector.h @@ -1,14 +1,14 @@ #pragma once #include -#include "StreamFormat/FMT/Context/FormatterExecutor/FormatterType.h" +#include "stream/fmt/context/formatter_executor/formatter_type.h" -namespace StreamFormat::FMT +namespace stream::fmt { template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static inline std::expected Format(const std::vector& t, FormatterExecutor& executor) - { return FormatterType>, FormatterExecutor>::Format(t, executor); } + [[nodiscard]] static inline std::expected format(const std::vector& t, FormatterExecutor& executor) + { return FormatterType>, FormatterExecutor>::format(t, executor); } }; } diff --git a/src/StreamFormat/FMT/TextProperties/BaseTextProperties.h b/src/stream/fmt/text_properties/base_text_properties.h similarity index 79% rename from src/StreamFormat/FMT/TextProperties/BaseTextProperties.h rename to src/stream/fmt/text_properties/base_text_properties.h index 158fad39..2d6bf94c 100644 --- a/src/StreamFormat/FMT/TextProperties/BaseTextProperties.h +++ b/src/stream/fmt/text_properties/base_text_properties.h @@ -1,10 +1,10 @@ #pragma once -#include "StreamFormat/Core/Prelude.h" +#include "stream/core/prelude.h" // According to : https://en.wikipedia.org/wiki/ANSI_escape_code -namespace StreamFormat::FMT::Detail +namespace stream::fmt::detail { struct TextProperties { diff --git a/src/stream/fmt/text_properties/text_properties.h b/src/stream/fmt/text_properties/text_properties.h new file mode 100644 index 00000000..9faeefc6 --- /dev/null +++ b/src/stream/fmt/text_properties/text_properties.h @@ -0,0 +1,20 @@ +#pragma once + +#include "text_properties_color.h" +#include "text_properties_front.h" +#include "text_properties_style.h" + +namespace stream::fmt::detail +{ + struct TextProperties::Properties + { + TextProperties::TextColor::Color color; + TextProperties::TextStyle::Style style; + TextProperties::TextFront::Front front; + }; + + inline bool operator==(const TextProperties::Properties& lhs, const TextProperties::Properties& rhs) + { + return lhs.color == rhs.color && lhs.style == rhs.style && lhs.front == rhs.front; + } +} diff --git a/src/StreamFormat/FMT/TextProperties/TextPropertiesColor.h b/src/stream/fmt/text_properties/text_properties_color.h similarity index 98% rename from src/StreamFormat/FMT/TextProperties/TextPropertiesColor.h rename to src/stream/fmt/text_properties/text_properties_color.h index bb8cdf5c..e8163f7c 100644 --- a/src/StreamFormat/FMT/TextProperties/TextPropertiesColor.h +++ b/src/stream/fmt/text_properties/text_properties_color.h @@ -1,12 +1,12 @@ #pragma once -#include "BaseTextProperties.h" +#include "base_text_properties.h" -namespace StreamFormat::FMT::Detail +namespace stream::fmt::detail { struct TextProperties::TextColor { - struct ResetColor + struct reset_color { }; @@ -294,7 +294,7 @@ namespace StreamFormat::FMT::Detail inline bool operator==(const TextProperties::TextColor::BaseColorCube& lhs, const TextProperties::TextColor::BaseColorCube& rhs) { - return lhs.Color == rhs.Color; + return lhs.color == rhs.color; } struct TextProperties::TextColor::ColorCube @@ -461,7 +461,7 @@ namespace StreamFormat::FMT::Detail void Apply(const TextProperties::TextColor::Color& given) { *this = given; } - void Apply(const TextProperties::TextColor::ResetColor&) { ModifyReset(); } + void Apply(const TextProperties::TextColor::reset_color&) { ModifyReset(); } void Apply(const TextProperties::TextColor::BasicColorFG& given) { Fg.Type = TextProperties::TextColor::ColorType::BasicColor; @@ -509,7 +509,7 @@ namespace StreamFormat::FMT::Detail } public: - bool NeedModif(const TextProperties::TextColor::ResetColor&) { return true; } + bool NeedModif(const TextProperties::TextColor::reset_color&) { return true; } bool NeedModif(const TextProperties::TextColor::Color& given) { return *this != given; } @@ -539,7 +539,7 @@ namespace StreamFormat::FMT::Detail struct TextPropertiesColorIsApplyType { using BaseType = GetBaseType; - static constexpr bool Value = std::is_same_v || std::is_same_v || + static constexpr bool Value = std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || diff --git a/src/StreamFormat/FMT/TextProperties/TextPropertiesFront.h b/src/stream/fmt/text_properties/text_properties_front.h similarity index 87% rename from src/StreamFormat/FMT/TextProperties/TextPropertiesFront.h rename to src/stream/fmt/text_properties/text_properties_front.h index 21c5bdfc..21309d2b 100644 --- a/src/StreamFormat/FMT/TextProperties/TextPropertiesFront.h +++ b/src/stream/fmt/text_properties/text_properties_front.h @@ -1,12 +1,12 @@ #pragma once -#include "BaseTextProperties.h" +#include "base_text_properties.h" -namespace StreamFormat::FMT::Detail +namespace stream::fmt::detail { struct TextProperties::TextFront { - struct ResetFront + struct reset_front { }; @@ -51,12 +51,12 @@ namespace StreamFormat::FMT::Detail public: void ModifyReset() { *this = Front{}; } - void Apply(const TextProperties::TextFront::ResetFront&) { ModifyReset(); } + void Apply(const TextProperties::TextFront::reset_front&) { ModifyReset(); } void Apply(const TextProperties::TextFront::Front& given) { *this = given; } void Apply(const TextProperties::TextFront::FrontID& given) { CurrentID = given; } public: - bool NeedModif(const TextProperties::TextFront::ResetFront&) { return true; } + bool NeedModif(const TextProperties::TextFront::reset_front&) { return true; } bool NeedModif(const TextProperties::TextFront::Front& given) { return *this != given; } bool NeedModif(const TextProperties::TextFront::FrontID& given) { return CurrentID != given; } }; @@ -76,7 +76,7 @@ namespace StreamFormat::FMT::Detail struct TextPropertiesFrontIsApplyType { using BaseType = GetBaseType; - static constexpr bool Value = std::is_same_v || std::is_same_v || + static constexpr bool Value = std::is_same_v || std::is_same_v || std::is_same_v; }; diff --git a/src/StreamFormat/FMT/TextProperties/TextPropertiesStyle.h b/src/stream/fmt/text_properties/text_properties_style.h similarity index 98% rename from src/StreamFormat/FMT/TextProperties/TextPropertiesStyle.h rename to src/stream/fmt/text_properties/text_properties_style.h index 1b41be54..a1c74534 100644 --- a/src/StreamFormat/FMT/TextProperties/TextPropertiesStyle.h +++ b/src/stream/fmt/text_properties/text_properties_style.h @@ -1,9 +1,9 @@ #pragma once -#include "BaseTextProperties.h" -#include "TextPropertiesColor.h" +#include "base_text_properties.h" +#include "text_properties_color.h" -namespace StreamFormat::FMT::Detail +namespace stream::fmt::detail { struct TextProperties::TextStyle { @@ -256,7 +256,7 @@ namespace StreamFormat::FMT::Detail concept TextPropertiesStyleIsApply = TextPropertiesStyleIsApplyType::Value; } -namespace StreamFormat::FMT::Detail::OLD +namespace stream::fmt::detail::OLD { enum class BasicStyle : std::uint8_t { diff --git a/src/StreamFormat/Json.h b/src/stream/json.h similarity index 72% rename from src/StreamFormat/Json.h rename to src/stream/json.h index d8baa93a..fb82dfdb 100644 --- a/src/StreamFormat/Json.h +++ b/src/stream/json.h @@ -4,4 +4,4 @@ #include "Json/JsonObjects.h" #include "Json/JsonSerializer.h" -#include "Json/Serializers/Serializers.h" +#include "Json/serializers/Serializers.h" diff --git a/src/StreamFormat/Json/Detail.h b/src/stream/json/detail.h similarity index 96% rename from src/StreamFormat/Json/Detail.h rename to src/stream/json/detail.h index cf0e05a1..95b2467f 100644 --- a/src/StreamFormat/Json/Detail.h +++ b/src/stream/json/detail.h @@ -5,7 +5,7 @@ #include #include -namespace StreamFormat::JSON::Detail +namespace stream::JSON::detail { class JsonError : public std::exception { @@ -64,7 +64,7 @@ namespace StreamFormat::JSON::Detail }; } -namespace StreamFormat::JSON +namespace stream::JSON { template struct JsonObjectSerializer; diff --git a/src/StreamFormat/Json/JsonFactory.h b/src/stream/json/json_factory.h similarity index 66% rename from src/StreamFormat/Json/JsonFactory.h rename to src/stream/json/json_factory.h index ab751548..39619d57 100644 --- a/src/StreamFormat/Json/JsonFactory.h +++ b/src/stream/json/json_factory.h @@ -5,13 +5,13 @@ #include "JsonObjects.h" #include "JsonParser.h" #include "JsonSerializer.h" -#include "Serializers/JsonObjectsSerializer.h" -#include "Serializers/Serializers.h" +#include "serializers/JsonObjectsSerializer.h" +#include "serializers/Serializers.h" #include #include -namespace StreamFormat::JSON +namespace stream::JSON { class JsonFactory { @@ -19,26 +19,26 @@ namespace StreamFormat::JSON template > static T FromPath(const std::filesystem::path& path); template - static void SaveToPath(T& json, const std::filesystem::path& path, Detail::JsonFormatter::FormatSettings settings); + static void SaveToPath(T& json, const std::filesystem::path& path, detail::JsonFormatter::FormatSettings settings); }; } -#include "StreamFormat/FMT.h" -namespace StreamFormat::FMT +#include "stream/fmt.h" +namespace stream::fmt { template struct FormatterType { - [[nodiscard]] static std::expected Format(const JSON::JsonObject& object, FormatterExecutor& executor) + [[nodiscard]] static std::expected format(const JSON::JsonObject& object, FormatterExecutor& executor) { return executor.WriteType(JSON::FormatAsJson(object)); } }; } #include #include -#include "StreamFormat//FMT/Buffer/BufferOutManager/DynamicBufferOutManager.h" -#include "Serializers/JsonObjectsSerializer.h" -namespace StreamFormat::JSON +#include "stream//fmt/buffer/buffer_out_manager/dynamic_buffer_out_manager.h" +#include "serializers/JsonObjectsSerializer.h" +namespace stream::JSON { template T JsonFactory::FromPath(const std::filesystem::path& path) @@ -56,24 +56,24 @@ namespace StreamFormat::JSON file.read(buffer.data(), size); file.close(); - FMT::Detail::BufferInfoView input(buffer.data(), buffer.size()); - Detail::JsonParser parser(input); + fmt::detail::BufferInfoView input(buffer.data(), buffer.size()); + detail::JsonParser parser(input); T res; - JsonSerializer::Parse(res, parser); + JsonSerializer::parse(res, parser); return res; } template - void JsonFactory::SaveToPath(T& json, const std::filesystem::path& path, Detail::JsonFormatter::FormatSettings settings) + void JsonFactory::SaveToPath(T& json, const std::filesystem::path& path, detail::JsonFormatter::FormatSettings settings) { std::ofstream file(path.string(), std::ios::out); if (file.is_open() == false) throw std::runtime_error("unable to open file"); - FMT::Detail::DynamicBufferOutManager BufferOutManager(256); - FMT::Detail::BufferOutInfo bufferOut = FMT::Detail::BufferOutInfo::Create(BufferOutManager).value(); - Detail::JsonFormatter formatter(bufferOut, settings); - JsonSerializer::Format(json, formatter); + fmt::detail::DynamicBufferOutManager BufferOutManager(256); + fmt::detail::BufferOutInfo bufferOut = fmt::detail::BufferOutInfo::Create(BufferOutManager).value(); + detail::JsonFormatter formatter(bufferOut, settings); + JsonSerializer::format(json, formatter); file.write(BufferOutManager.GetBuffer(), static_cast(BufferOutManager.GetLastGeneratedDataSize())); file.flush(); diff --git a/src/StreamFormat/Json/JsonFormatter.h b/src/stream/json/json_formatter.h similarity index 76% rename from src/StreamFormat/Json/JsonFormatter.h rename to src/stream/json/json_formatter.h index 3e86ea28..97633a72 100644 --- a/src/StreamFormat/Json/JsonFormatter.h +++ b/src/stream/json/json_formatter.h @@ -1,9 +1,9 @@ #pragma once #include "JsonObjects.h" -#include "StreamFormat/FMT/Buffer/BufferOutManip.h" +#include "stream/fmt/buffer/buffer_out_manip.h" -namespace StreamFormat::JSON::Detail +namespace stream::JSON::detail { class JsonFormatter { @@ -18,12 +18,12 @@ namespace StreamFormat::JSON::Detail }; public: - JsonFormatter(StreamFormat::FMT::Detail::BufferOutInfo& bufferOut) + JsonFormatter(stream::fmt::detail::BufferOutInfo& bufferOut) : BufferOut(bufferOut) , Settings() , m_Indent(0) {} - JsonFormatter(StreamFormat::FMT::Detail::BufferOutInfo& bufferOut, FormatSettings settings) + JsonFormatter(stream::fmt::detail::BufferOutInfo& bufferOut, FormatSettings settings) : BufferOut(bufferOut) , Settings(settings) , m_Indent(0) @@ -31,7 +31,7 @@ namespace StreamFormat::JSON::Detail public: template - void Format(const T& t); + void format(const T& t); struct StructIntermediate; struct ArrayIntermediate; @@ -44,22 +44,22 @@ namespace StreamFormat::JSON::Detail if (Settings.OneLine) return; if (Settings.IndentWithSpaces) - FMT::Detail::BufferOutManip(BufferOut).Pushback(' ', m_Indent * Settings.IndentSize).value(); + fmt::detail::BufferOutManip(BufferOut).Pushback(' ', m_Indent * Settings.IndentSize).value(); else - FMT::Detail::BufferOutManip(BufferOut).Pushback('\t', m_Indent * Settings.IndentSize).value(); + fmt::detail::BufferOutManip(BufferOut).Pushback('\t', m_Indent * Settings.IndentSize).value(); } void NewLine() { if (Settings.OneLine) return; - FMT::Detail::BufferOutManip(BufferOut).Pushback('\n').value(); + fmt::detail::BufferOutManip(BufferOut).Pushback('\n').value(); Indent(); } void BeginNewObject() { ++m_Indent; } void EndNewObject() { --m_Indent; } public: - StreamFormat::FMT::Detail::BufferOutInfo& BufferOut; + stream::fmt::detail::BufferOutInfo& BufferOut; FormatSettings Settings; protected: @@ -67,7 +67,7 @@ namespace StreamFormat::JSON::Detail }; } -namespace StreamFormat::JSON::Detail +namespace stream::JSON::detail { struct JsonFormatter::StructIntermediate { @@ -77,7 +77,7 @@ namespace StreamFormat::JSON::Detail public: template - void Format(const std::string_view name, const T& t); + void format(const std::string_view name, const T& t); public: JsonFormatter& Formatter; @@ -92,7 +92,7 @@ namespace StreamFormat::JSON::Detail public: template - void Format(const T& t); + void format(const T& t); public: JsonFormatter& Formatter; diff --git a/src/StreamFormat/Json/JsonFormatter-inl.h b/src/stream/json/json_formatter_impl.h similarity index 85% rename from src/StreamFormat/Json/JsonFormatter-inl.h rename to src/stream/json/json_formatter_impl.h index 0f48a08c..642cad3e 100644 --- a/src/StreamFormat/Json/JsonFormatter-inl.h +++ b/src/stream/json/json_formatter_impl.h @@ -2,7 +2,7 @@ #include "JsonSerializer.h" -namespace StreamFormat::JSON::Detail +namespace stream::JSON::detail { inline JsonFormatter::StructIntermediate::StructIntermediate(JsonFormatter& formatter) : Formatter(formatter) @@ -15,7 +15,7 @@ namespace StreamFormat::JSON::Detail JsonStructSerializer::FormatEnd(Formatter); } template - inline void JsonFormatter::StructIntermediate::Format(const std::string_view name, const T& t) + inline void JsonFormatter::StructIntermediate::format(const std::string_view name, const T& t) { JsonStructSerializer::FormatObject(name, t, Idx++, Formatter); } @@ -31,7 +31,7 @@ namespace StreamFormat::JSON::Detail JsonArraySerializer::FormatEnd(Formatter); } template - inline void JsonFormatter::ArrayIntermediate::Format(const T& t) + inline void JsonFormatter::ArrayIntermediate::format(const T& t) { JsonArraySerializer::FormatObject(t, Idx++, Formatter); } diff --git a/src/stream/json/json_objects.cpp b/src/stream/json/json_objects.cpp new file mode 100644 index 00000000..1cb6979b --- /dev/null +++ b/src/stream/json/json_objects.cpp @@ -0,0 +1,59 @@ +#include "JsonObjects.h" +#include "serializers/JsonObjectsSerializer.h" + +namespace stream::JSON +{ + void JsonStringObject::ParserExecute(detail::JsonParser& parser) + { + JsonSerializer::parse(*this, parser); + } + void JsonStringObject::FormatterExecute(detail::JsonFormatter& formatter) const + { + JsonSerializer::format(*this, formatter); + } + + void JsonNumberObject::ParserExecute(detail::JsonParser& parser) + { + JsonSerializer::parse(*this, parser); + } + void JsonNumberObject::FormatterExecute(detail::JsonFormatter& formatter) const + { + JsonSerializer::format(*this, formatter); + } + + void JsonBooleanObject::ParserExecute(detail::JsonParser& parser) + { + JsonSerializer::parse(*this, parser); + } + void JsonBooleanObject::FormatterExecute(detail::JsonFormatter& formatter) const + { + JsonSerializer::format(*this, formatter); + } + + void JsonStructObject::ParserExecute(detail::JsonParser& parser) + { + JsonSerializer::parse(*this, parser); + } + void JsonStructObject::FormatterExecute(detail::JsonFormatter& formatter) const + { + JsonSerializer::format(*this, formatter); + } + + void JsonArrayObject::ParserExecute(detail::JsonParser& parser) + { + JsonSerializer::parse(*this, parser); + } + void JsonArrayObject::FormatterExecute(detail::JsonFormatter& formatter) const + { + JsonSerializer::format(*this, formatter); + } + + void JsonNullObject::ParserExecute(detail::JsonParser& parser) + { + JsonSerializer::parse(*this, parser); + } + void JsonNullObject::FormatterExecute(detail::JsonFormatter& formatter) const + { + JsonSerializer::format(*this, formatter); + } +} diff --git a/src/StreamFormat/Json/JsonObjects.h b/src/stream/json/json_objects.h similarity index 80% rename from src/StreamFormat/Json/JsonObjects.h rename to src/stream/json/json_objects.h index d1877297..43905ff4 100644 --- a/src/StreamFormat/Json/JsonObjects.h +++ b/src/stream/json/json_objects.h @@ -1,7 +1,7 @@ #pragma once -#include "Detail.h" -#include "StreamFormat/FMT.h" +#include "detail.h" +#include "stream/fmt.h" #include #include @@ -9,13 +9,13 @@ #include #include -namespace StreamFormat::JSON::Detail +namespace stream::JSON::detail { class JsonParser; class JsonFormatter; } -namespace StreamFormat::JSON +namespace stream::JSON { struct JsonObject { @@ -48,15 +48,15 @@ namespace StreamFormat::JSON JsonObject& operator[](const std::size_t index) { return Get(index); } JsonObject& operator[](const std::string_view subObject) { return Get(subObject); } - virtual JsonObject& Get(const std::size_t) { throw Detail::JsonIndexingError{}; } - virtual JsonObject& Get(const std::string_view) { throw Detail::JsonIndexingError{}; } + virtual JsonObject& Get(const std::size_t) { throw detail::JsonIndexingError{}; } + virtual JsonObject& Get(const std::string_view) { throw detail::JsonIndexingError{}; } public: template requires std::is_base_of_v T& As() { T* t = dynamic_cast(this); - if (t == nullptr) throw Detail::JsonCastError{}; + if (t == nullptr) throw detail::JsonCastError{}; return *t; } @@ -65,7 +65,7 @@ namespace StreamFormat::JSON const T& As() const { const T* t = dynamic_cast(this); - if (t == nullptr) throw Detail::JsonCastError{}; + if (t == nullptr) throw detail::JsonCastError{}; return *t; } @@ -83,11 +83,11 @@ namespace StreamFormat::JSON JsonObjectSerializer::WriteObject(t, *this); } - std::string ToString() { return FMT::FormatString(*this).value(); } + std::string ToString() { return fmt::FormatString(*this).value(); } public: - virtual void ParserExecute(Detail::JsonParser& parser) = 0; - virtual void FormatterExecute(Detail::JsonFormatter& formatter) const = 0; + virtual void ParserExecute(detail::JsonParser& parser) = 0; + virtual void FormatterExecute(detail::JsonFormatter& formatter) const = 0; }; struct JsonStringObject final : public JsonObject @@ -114,8 +114,8 @@ namespace StreamFormat::JSON static std::unique_ptr Create(std::string&& value) { return std::make_unique(std::move(value)); } public: - void ParserExecute(Detail::JsonParser& parser) override; - void FormatterExecute(Detail::JsonFormatter& formatter) const override; + void ParserExecute(detail::JsonParser& parser) override; + void FormatterExecute(detail::JsonFormatter& formatter) const override; }; struct JsonNumberObject final : public JsonObject @@ -133,8 +133,8 @@ namespace StreamFormat::JSON static std::unique_ptr Create(double value = 0.0) { return std::make_unique(value); } public: - void ParserExecute(Detail::JsonParser& parser) override; - void FormatterExecute(Detail::JsonFormatter& formatter) const override; + void ParserExecute(detail::JsonParser& parser) override; + void FormatterExecute(detail::JsonFormatter& formatter) const override; }; struct JsonBooleanObject final : public JsonObject @@ -152,8 +152,8 @@ namespace StreamFormat::JSON static std::unique_ptr Create(bool value = false) { return std::make_unique(value); } public: - void ParserExecute(Detail::JsonParser& parser) override; - void FormatterExecute(Detail::JsonFormatter& formatter) const override; + void ParserExecute(detail::JsonParser& parser) override; + void FormatterExecute(detail::JsonFormatter& formatter) const override; }; struct JsonStructObject final : public JsonObject @@ -181,13 +181,13 @@ namespace StreamFormat::JSON } catch (...) { - throw Detail::JsonIndexingError{}; + throw detail::JsonIndexingError{}; } } public: - void ParserExecute(Detail::JsonParser& parser) override; - void FormatterExecute(Detail::JsonFormatter& formatter) const override; + void ParserExecute(detail::JsonParser& parser) override; + void FormatterExecute(detail::JsonFormatter& formatter) const override; }; struct JsonArrayObject final : public JsonObject @@ -209,8 +209,8 @@ namespace StreamFormat::JSON JsonObject& Get(const std::size_t index) override { return *Objects[index]; } public: - void ParserExecute(Detail::JsonParser& parser) override; - void FormatterExecute(Detail::JsonFormatter& formatter) const override; + void ParserExecute(detail::JsonParser& parser) override; + void FormatterExecute(detail::JsonFormatter& formatter) const override; }; struct JsonNullObject final : public JsonObject @@ -225,7 +225,7 @@ namespace StreamFormat::JSON static std::unique_ptr Create() { return std::make_unique(); } public: - void ParserExecute(Detail::JsonParser& parser) override; - void FormatterExecute(Detail::JsonFormatter& formatter) const override; + void ParserExecute(detail::JsonParser& parser) override; + void FormatterExecute(detail::JsonFormatter& formatter) const override; }; } diff --git a/src/StreamFormat/Json/JsonParser.cpp b/src/stream/json/json_parser.cpp similarity index 80% rename from src/StreamFormat/Json/JsonParser.cpp rename to src/stream/json/json_parser.cpp index 6b08bdb0..6d524823 100644 --- a/src/StreamFormat/Json/JsonParser.cpp +++ b/src/stream/json/json_parser.cpp @@ -1,4 +1,4 @@ -#include "Detail.h" +#include "detail.h" #include #include @@ -6,12 +6,12 @@ #include "JsonSerializer.h" -namespace StreamFormat::JSON::Detail +namespace stream::JSON::detail { - void JsonParser::Intermediate::Parse(Detail::JsonParser& parser) + void JsonParser::Intermediate::parse(detail::JsonParser& parser) { - FMT::Detail::BufferTestAccess access(parser.BufferIn); - FMT::Detail::BufferTestManip manip(parser.BufferIn); + fmt::detail::BufferTestAccess access(parser.BufferIn); + fmt::detail::BufferTestManip manip(parser.BufferIn); manip.IgnoreEveryBlanks(); const char* begin = parser.BufferIn.CurrentPos; @@ -22,7 +22,7 @@ namespace StreamFormat::JSON::Detail while (true) { manip.GoTo('"'); - if (FMT::Detail::BufferTestAccess(parser.BufferIn).PrevIsNotEqualTo('\\')) + if (fmt::detail::BufferTestAccess(parser.BufferIn).PrevIsNotEqualTo('\\')) break; } manip.SkipOneOf('"').value(); @@ -41,14 +41,14 @@ namespace StreamFormat::JSON::Detail { JsonStructSerializer::LoadAllSubObjects(*this, parser, [](JsonParser::Intermediate&, std::size_t, std::string&&, JsonParser& jsonParser) { JsonParser::Intermediate intermediate; - intermediate.Parse(jsonParser); + intermediate.parse(jsonParser); }); } else if (parser.IsJsonArrayBegin()) { JsonArraySerializer::LoadAllSubObjects(*this, parser, [](JsonParser::Intermediate&, std::size_t, JsonParser& jsonParser) { JsonParser::Intermediate intermediate; - intermediate.Parse(jsonParser); + intermediate.parse(jsonParser); }); } else if (parser.IsJsonNullBegin()) @@ -60,21 +60,21 @@ namespace StreamFormat::JSON::Detail Data = std::string_view(begin, end); }; - void JsonParser::StructIntermediate::Parse(Detail::JsonParser& parser) + void JsonParser::StructIntermediate::parse(detail::JsonParser& parser) { JsonStructSerializer::LoadAllSubObjects(*this, parser, [](JsonParser::StructIntermediate& t, std::size_t, std::string&& name, JsonParser& jsonParser) { JsonParser::Intermediate intermediate; - intermediate.Parse(jsonParser); + intermediate.parse(jsonParser); t.Objects.insert({std::move(name), std::move(intermediate)}); }); }; - void JsonParser::ArrayIntermediate::Parse(Detail::JsonParser& parser) + void JsonParser::ArrayIntermediate::parse(detail::JsonParser& parser) { JsonArraySerializer::LoadAllSubObjects(*this, parser, [](JsonParser::ArrayIntermediate& t, std::size_t, JsonParser& jsonParser) { JsonParser::Intermediate intermediate; - intermediate.Parse(jsonParser); + intermediate.parse(jsonParser); t.Objects.emplace_back(std::move(intermediate)); }); }; diff --git a/src/StreamFormat/Json/JsonParser.h b/src/stream/json/json_parser.h similarity index 55% rename from src/StreamFormat/Json/JsonParser.h rename to src/stream/json/json_parser.h index 4d7c4569..6bf17362 100644 --- a/src/StreamFormat/Json/JsonParser.h +++ b/src/stream/json/json_parser.h @@ -1,10 +1,10 @@ #pragma once -#include "StreamFormat/FMT/Buffer/BufferInfo.h" +#include "stream/fmt/buffer/buffer_info.h" #include "JsonObjects.h" -namespace StreamFormat::JSON::Detail +namespace stream::JSON::detail { class JsonParser { @@ -13,27 +13,27 @@ namespace StreamFormat::JSON::Detail : BufferIn() {} - JsonParser(FMT::Detail::BufferInfoView& input) + JsonParser(fmt::detail::BufferInfoView& input) : BufferIn(input) {} public: - inline bool IsJsonStringBegin() const { return FMT::Detail::BufferTestAccess(BufferIn).IsEqualTo('"'); } - inline bool IsJsonNumberBegin() const { return FMT::Detail::BufferTestAccess(BufferIn).IsADigit() || FMT::Detail::BufferTestAccess(BufferIn).IsEqualTo('+', '-', '.'); } - inline bool IsJsonBooleanBegin() const { return FMT::Detail::BufferTestAccess(BufferIn).IsEqualTo('t', 'f'); } - inline bool IsJsonStructBegin() const { return FMT::Detail::BufferTestAccess(BufferIn).IsEqualTo('{'); } - inline bool IsJsonArrayBegin() const { return FMT::Detail::BufferTestAccess(BufferIn).IsEqualTo('['); } - inline bool IsJsonNullBegin() const { return FMT::Detail::BufferTestAccess(BufferIn).IsEqualTo('n'); } + inline bool IsJsonStringBegin() const { return fmt::detail::BufferTestAccess(BufferIn).IsEqualTo('"'); } + inline bool IsJsonNumberBegin() const { return fmt::detail::BufferTestAccess(BufferIn).IsADigit() || fmt::detail::BufferTestAccess(BufferIn).IsEqualTo('+', '-', '.'); } + inline bool IsJsonBooleanBegin() const { return fmt::detail::BufferTestAccess(BufferIn).IsEqualTo('t', 'f'); } + inline bool IsJsonStructBegin() const { return fmt::detail::BufferTestAccess(BufferIn).IsEqualTo('{'); } + inline bool IsJsonArrayBegin() const { return fmt::detail::BufferTestAccess(BufferIn).IsEqualTo('['); } + inline bool IsJsonNullBegin() const { return fmt::detail::BufferTestAccess(BufferIn).IsEqualTo('n'); } public: - FMT::Detail::BufferInfo BufferIn; + fmt::detail::BufferInfo BufferIn; public: struct Intermediate; public: template - void Parse(T& t); + void parse(T& t); struct StructIntermediate; struct ArrayIntermediate; @@ -42,19 +42,19 @@ namespace StreamFormat::JSON::Detail }; } -namespace StreamFormat::JSON::Detail +namespace stream::JSON::detail { struct JsonParser::Intermediate { std::string_view Data; - void Parse(Detail::JsonParser& parser); + void parse(detail::JsonParser& parser); template - void Parse(T& t) + void parse(T& t) { JsonParser parser; - parser.Parse(t); + parser.parse(t); } }; @@ -64,16 +64,16 @@ namespace StreamFormat::JSON::Detail friend JsonParser; private: - std::unordered_map Objects; + std::unordered_map Objects; - void Parse(Detail::JsonParser& parser); + void parse(detail::JsonParser& parser); public: template - void Parse(const std::string& name, T& t) + void parse(const std::string& name, T& t) { - if (Objects.contains(name) == false) throw Detail::JsonGivenTypeError{}; - Objects[name].Parse(t); + if (Objects.contains(name) == false) throw detail::JsonGivenTypeError{}; + Objects[name].parse(t); } }; @@ -83,29 +83,29 @@ namespace StreamFormat::JSON::Detail friend JsonParser; private: - std::vector Objects; + std::vector Objects; - void Parse(Detail::JsonParser& parser); + void parse(detail::JsonParser& parser); public: template - void Parse(const std::size_t idx, T& t) + void parse(const std::size_t idx, T& t) { - if (idx >= Objects.size()) throw Detail::JsonGivenTypeError{}; - Objects[idx].Parse(t); + if (idx >= Objects.size()) throw detail::JsonGivenTypeError{}; + Objects[idx].parse(t); } }; inline JsonParser::StructIntermediate JsonParser::GetStructIntermediate() { JsonParser::StructIntermediate res; - res.Parse(*this); + res.parse(*this); return res; } inline JsonParser::ArrayIntermediate JsonParser::GetArrayIntermediate() { JsonParser::ArrayIntermediate res; - res.Parse(*this); + res.parse(*this); return res; } } diff --git a/src/StreamFormat/Json/JsonSerializer.h b/src/stream/json/json_serializer.h similarity index 51% rename from src/StreamFormat/Json/JsonSerializer.h rename to src/stream/json/json_serializer.h index d30c465d..d6583d18 100644 --- a/src/StreamFormat/Json/JsonSerializer.h +++ b/src/stream/json/json_serializer.h @@ -3,50 +3,50 @@ #include "JsonFormatter.h" #include "JsonParser.h" -#include "StreamFormat/FMT.h" -#include "StreamFormat/FMT/Buffer/BufferReadManip.h" -#include "StreamFormat/FMT/Buffer/BufferWriteManip.h" -#include "StreamFormat/FMT/Buffer/Utils/BufferUtils.h" +#include "stream/fmt.h" +#include "stream/fmt/buffer/buffer_read_manip.h" +#include "stream/fmt/buffer/buffer_write_manip.h" +#include "stream/fmt/buffer/utils/buffer_utils.h" #include #include -namespace StreamFormat::JSON +namespace stream::JSON { template struct JsonSerializer { - static inline void Parse(T&, Detail::JsonParser&) + static inline void parse(T&, detail::JsonParser&) { #ifdef UNKOWN_TYPE_MESSAGE - FMT::FilePrint(std::cerr, "{C:red}JsonSerializer::Parse<{}> not impl", typeid(T).name()).value(); + fmt::FilePrint(std::cerr, "{C:red}JsonSerializer::Parse<{}> not impl", typeid(T).name()).value(); #endif #ifdef UNKOWN_TYPE_THROW - throw Detail::JsonTypeSerializerNotImpl{}; + throw detail::JsonTypeSerializerNotImpl{}; #endif #ifdef UNKOWN_TYPE_FAIL // FIXME - throw Detail::JsonTypeSerializerNotImpl{}; + throw detail::JsonTypeSerializerNotImpl{}; #endif #ifdef UNKOWN_TYPE_DEBUG STREAMFORMAT_DEBUGBREAK(); #endif } - static inline void Format(const T&, Detail::JsonFormatter& formatter) + static inline void format(const T&, detail::JsonFormatter& formatter) { - FMT::Detail::BufferWriteManip(formatter.BufferOut).FastWriteString(std::string_view("Unknown JsonFormatter for type : ")).value(); - FMT::Detail::BufferWriteManip(formatter.BufferOut).FastWriteString(std::string_view(typeid(T).name())).value(); + fmt::detail::BufferWriteManip(formatter.buffer_out).FastWriteString(std::string_view("Unknown JsonFormatter for type : ")).value(); + fmt::detail::BufferWriteManip(formatter.buffer_out).FastWriteString(std::string_view(typeid(T).name())).value(); #ifdef UNKOWN_TYPE_MESSAGE - FMT::FilePrint(std::cerr, "{C:red}JsonSerializer::Format<{}> not impl", typeid(T).name()).value(); + fmt::FilePrint(std::cerr, "{C:red}JsonSerializer::Format<{}> not impl", typeid(T).name()).value(); #endif #ifdef UNKOWN_TYPE_THROW - throw Detail::JsonTypeSerializerNotImpl{}; + throw detail::JsonTypeSerializerNotImpl{}; #endif #ifdef UNKOWN_TYPE_FAIL // FIXME - throw Detail::JsonTypeSerializerNotImpl{}; + throw detail::JsonTypeSerializerNotImpl{}; #endif #ifdef UNKOWN_TYPE_DEBUG STREAMFORMAT_DEBUGBREAK(); @@ -60,14 +60,14 @@ namespace StreamFormat::JSON static inline void ReadObject(T&, const JsonObject&) { #ifdef UNKOWN_TYPE_MESSAGE - FMT::FilePrint(std::cerr, "{C:red}JsonObjectSerializer::ReadObject<{}> not impl", typeid(T).name()).value(); + fmt::FilePrint(std::cerr, "{C:red}JsonObjectSerializer::ReadObject<{}> not impl", typeid(T).name()).value(); #endif #ifdef UNKOWN_TYPE_THROW - throw Detail::JsonTypeSerializerNotImpl{}; + throw detail::JsonTypeSerializerNotImpl{}; #endif #ifdef UNKOWN_TYPE_FAIL // FIXME - throw Detail::JsonTypeSerializerNotImpl{}; + throw detail::JsonTypeSerializerNotImpl{}; #endif #ifdef UNKOWN_TYPE_DEBUG STREAMFORMAT_DEBUGBREAK(); @@ -77,14 +77,14 @@ namespace StreamFormat::JSON static inline void WriteObject(const T&, JsonObject&) { #ifdef UNKOWN_TYPE_MESSAGE - FMT::FilePrint(std::cerr, "{C:red}JsonObjectSerializer::WriteObject<{}> not impl", typeid(T).name()).value(); + fmt::FilePrint(std::cerr, "{C:red}JsonObjectSerializer::WriteObject<{}> not impl", typeid(T).name()).value(); #endif #ifdef UNKOWN_TYPE_THROW - throw Detail::JsonTypeSerializerNotImpl{}; + throw detail::JsonTypeSerializerNotImpl{}; #endif #ifdef UNKOWN_TYPE_FAIL // FIXME - throw Detail::JsonTypeSerializerNotImpl{}; + throw detail::JsonTypeSerializerNotImpl{}; #endif #ifdef UNKOWN_TYPE_DEBUG STREAMFORMAT_DEBUGBREAK(); @@ -94,87 +94,87 @@ namespace StreamFormat::JSON struct JsonStringSerializer { - static inline void ParseSTDString(std::string& t, Detail::JsonParser& parser) + static inline void ParseSTDString(std::string& t, detail::JsonParser& parser) { - FMT::Detail::DynamicBufferOutManager bufferData; - FMT::Detail::BufferOutInfo buffer = FMT::Detail::BufferOutInfo::Create(bufferData).value(); - FMT::Detail::BufferUtils::ParseEscapedQuotedString(parser.BufferIn, buffer).value(); - FMT::Detail::BufferOutManip(buffer).ComputeGeneratedSize(); + fmt::detail::DynamicBufferOutManager bufferData; + fmt::detail::BufferOutInfo buffer = fmt::detail::BufferOutInfo::Create(bufferData).value(); + fmt::detail::BufferUtils::parse_escaped_quoted_string(parser.BufferIn, buffer).value(); + fmt::detail::BufferOutManip(buffer).ComputeGeneratedSize(); t = bufferData.GetLastGeneratedString(); } - static inline void FormatSTDString(const std::string_view t, Detail::JsonFormatter& formatter) + static inline void FormatSTDString(const std::string_view t, detail::JsonFormatter& formatter) { - FMT::Detail::BufferInfo buffer(t.data(), t.size()); - FMT::Detail::BufferUtils::FormatEscapedQuotedString(formatter.BufferOut, buffer).value(); + fmt::detail::BufferInfo buffer(t.data(), t.size()); + fmt::detail::BufferUtils::FormatEscapedQuotedString(formatter.buffer_out, buffer).value(); } }; struct JsonNumberSerializer { template - static inline void ParseFloat(FloatType& t, Detail::JsonParser& parser) + static inline void ParseFloat(FloatType& t, detail::JsonParser& parser) { - FMT::Detail::BufferReadManip(parser.BufferIn).FastReadFloat(t).value(); + fmt::detail::BufferReadManip(parser.BufferIn).FastReadFloat(t).value(); } template - static inline void ParseInteger(IntType& t, Detail::JsonParser& parser) + static inline void ParseInteger(IntType& t, detail::JsonParser& parser) { const char* begin = parser.BufferIn.CurrentPos; float tmp = 0; - FMT::Detail::BufferReadManip(parser.BufferIn).FastReadFloat(tmp).value(); + fmt::detail::BufferReadManip(parser.BufferIn).FastReadFloat(tmp).value(); const char* end = parser.BufferIn.CurrentPos; parser.BufferIn.CurrentPos = begin; - FMT::Detail::BufferReadManip(parser.BufferIn).FastReadInteger(t).value(); + fmt::detail::BufferReadManip(parser.BufferIn).FastReadInteger(t).value(); parser.BufferIn.CurrentPos = end; } template - static inline void FormatFloat(const FloatType& t, Detail::JsonFormatter& formatter) + static inline void FormatFloat(const FloatType& t, detail::JsonFormatter& formatter) { - FMT::Detail::BufferWriteManip(formatter.BufferOut).FastWriteFloat(t, formatter.Settings.FloatPrecision).value(); + fmt::detail::BufferWriteManip(formatter.buffer_out).FastWriteFloat(t, formatter.Settings.FloatPrecision).value(); } template - static inline void FormatInteger(const IntType& t, Detail::JsonFormatter& formatter) + static inline void FormatInteger(const IntType& t, detail::JsonFormatter& formatter) { - FMT::Detail::BufferWriteManip(formatter.BufferOut).FastWriteInteger(t).value(); + fmt::detail::BufferWriteManip(formatter.buffer_out).FastWriteInteger(t).value(); } }; struct JsonBooleanSerializer { - static inline void ParseBool(bool& t, Detail::JsonParser& parser) + static inline void ParseBool(bool& t, detail::JsonParser& parser) { - if (FMT::Detail::BufferTestManip(parser.BufferIn).IsSameForward("true", 5).value()) + if (fmt::detail::BufferTestManip(parser.BufferIn).is_same_forward("true", 5).value()) t = true; - else if (FMT::Detail::BufferTestManip(parser.BufferIn).IsSameForward("false", 5).value()) + else if (fmt::detail::BufferTestManip(parser.BufferIn).is_same_forward("false", 5).value()) t = false; } - static inline void FormatBool(const bool& t, Detail::JsonFormatter& formatter) + static inline void FormatBool(const bool& t, detail::JsonFormatter& formatter) { if (t) - FMT::Detail::BufferWriteManip(formatter.BufferOut).FastWriteCharArray("true", 5).value(); + fmt::detail::BufferWriteManip(formatter.buffer_out).FastWriteCharArray("true", 5).value(); else - FMT::Detail::BufferWriteManip(formatter.BufferOut).FastWriteCharArray("false", 5).value(); + fmt::detail::BufferWriteManip(formatter.buffer_out).FastWriteCharArray("false", 5).value(); } }; struct JsonStructSerializer { template - static inline void LoadAllSubObjects(T& t, Detail::JsonParser& parser, std::function subObjectParsingFunction) + static inline void LoadAllSubObjects(T& t, detail::JsonParser& parser, std::function subObjectParsingFunction) { - FMT::Detail::BufferTestAccess access(parser.BufferIn); - FMT::Detail::BufferTestManip manip(parser.BufferIn); + fmt::detail::BufferTestAccess access(parser.BufferIn); + fmt::detail::BufferTestManip manip(parser.BufferIn); manip.SkipOneOf('{').value(); std::size_t idx = 0; - while (FMT::Detail::BufferAccess(parser.BufferIn).IsEndOfString() == false) + while (fmt::detail::BufferAccess(parser.BufferIn).IsEndOfString() == false) { manip.GoTo('"', '}'); if (access.IsEqualTo('}')) break; @@ -196,34 +196,34 @@ namespace StreamFormat::JSON } template - static inline void LoadAllSubObjects(T& t, Detail::JsonParser& parserObject) + static inline void LoadAllSubObjects(T& t, detail::JsonParser& parserObject) { - LoadAllSubObjects(t, parserObject, [](T& mainObject, std::size_t idx, std::string&& name, Detail::JsonParser& parser) { + LoadAllSubObjects(t, parserObject, [](T& mainObject, std::size_t idx, std::string&& name, detail::JsonParser& parser) { typename JsonSerializer::StructSubObjectType subObject; - parser.Parse(subObject); + parser.parse(subObject); JsonSerializer::AddStructSubObject(mainObject, idx, std::move(name), std::move(subObject)); }); } - static inline void FormatBegin(Detail::JsonFormatter& formatter) { FMT::Detail::BufferOutManip(formatter.BufferOut).Pushback('{').value(); } + static inline void FormatBegin(detail::JsonFormatter& formatter) { fmt::detail::BufferOutManip(formatter.buffer_out).Pushback('{').value(); } - static inline void FormatEnd(Detail::JsonFormatter& formatter) + static inline void FormatEnd(detail::JsonFormatter& formatter) { formatter.NewLine(); - FMT::Detail::BufferOutManip(formatter.BufferOut).Pushback('}').value(); + fmt::detail::BufferOutManip(formatter.buffer_out).Pushback('}').value(); } template - static inline void FormatObject(const std::string_view name, const SubObject& subObject, const std::size_t idx, Detail::JsonFormatter& formatter) + static inline void FormatObject(const std::string_view name, const SubObject& subObject, const std::size_t idx, detail::JsonFormatter& formatter) { - if (idx != 0) FMT::Detail::BufferOutManip(formatter.BufferOut).Pushback(',').value(); + if (idx != 0) fmt::detail::BufferOutManip(formatter.buffer_out).Pushback(',').value(); formatter.BeginNewObject(); formatter.NewLine(); JsonStringSerializer::FormatSTDString(name, formatter); - FMT::Detail::BufferOutManip(formatter.BufferOut).Pushback(':').value(); - FMT::Detail::BufferOutManip(formatter.BufferOut).Pushback(' ').value(); - formatter.Format(subObject); + fmt::detail::BufferOutManip(formatter.buffer_out).Pushback(':').value(); + fmt::detail::BufferOutManip(formatter.buffer_out).Pushback(' ').value(); + formatter.format(subObject); formatter.EndNewObject(); } }; @@ -231,15 +231,15 @@ namespace StreamFormat::JSON struct JsonArraySerializer { template - static inline void LoadAllSubObjects(T& t, Detail::JsonParser& parser, std::function subObjectParsingFunction) + static inline void LoadAllSubObjects(T& t, detail::JsonParser& parser, std::function subObjectParsingFunction) { - FMT::Detail::BufferTestAccess access(parser.BufferIn); - FMT::Detail::BufferTestManip manip(parser.BufferIn); + fmt::detail::BufferTestAccess access(parser.BufferIn); + fmt::detail::BufferTestManip manip(parser.BufferIn); manip.SkipOneOf('[').value(); std::size_t idx = 0; - while (FMT::Detail::BufferAccess(parser.BufferIn).IsEndOfString() == false) + while (fmt::detail::BufferAccess(parser.BufferIn).IsEndOfString() == false) { manip.IgnoreEveryBlanks(); @@ -255,59 +255,59 @@ namespace StreamFormat::JSON } template - static inline void LoadAllSubObjects(T& t, Detail::JsonParser& parser) + static inline void LoadAllSubObjects(T& t, detail::JsonParser& parser) { - LoadAllSubObjects(t, parser, [](T& mainObject, std::size_t idx, Detail::JsonParser& jsonParser) { + LoadAllSubObjects(t, parser, [](T& mainObject, std::size_t idx, detail::JsonParser& jsonParser) { typename JsonSerializer::ArraySubObjectType subObject; - jsonParser.Parse(subObject); + jsonParser.parse(subObject); JsonSerializer::AddArraySubObject(mainObject, idx, std::move(subObject)); }); } - static inline void FormatBegin(Detail::JsonFormatter& formatter) { FMT::Detail::BufferOutManip(formatter.BufferOut).Pushback('[').value(); } + static inline void FormatBegin(detail::JsonFormatter& formatter) { fmt::detail::BufferOutManip(formatter.buffer_out).Pushback('[').value(); } - static inline void FormatEnd(Detail::JsonFormatter& formatter) + static inline void FormatEnd(detail::JsonFormatter& formatter) { formatter.NewLine(); - FMT::Detail::BufferOutManip(formatter.BufferOut).Pushback(']').value(); + fmt::detail::BufferOutManip(formatter.buffer_out).Pushback(']').value(); } template - static inline void FormatObject(const SubObject& subObject, const std::size_t idx, Detail::JsonFormatter& formatter) + static inline void FormatObject(const SubObject& subObject, const std::size_t idx, detail::JsonFormatter& formatter) { - if (idx != 0) FMT::Detail::BufferOutManip(formatter.BufferOut).Pushback(',').value(); + if (idx != 0) fmt::detail::BufferOutManip(formatter.buffer_out).Pushback(',').value(); formatter.BeginNewObject(); formatter.NewLine(); - formatter.Format(subObject); + formatter.format(subObject); formatter.EndNewObject(); } }; struct JsonNullSerializer { - static inline void ParseNull(Detail::JsonParser& parser) { FMT::Detail::BufferTestManip(parser.BufferIn).IsSameForward("null", 4).value(); } + static inline void ParseNull(detail::JsonParser& parser) { fmt::detail::BufferTestManip(parser.BufferIn).is_same_forward("null", 4).value(); } - static inline void FormatNull(Detail::JsonFormatter& formatter) { FMT::Detail::BufferWriteManip(formatter.BufferOut).FastWriteCharArray("null", 4).value(); } + static inline void FormatNull(detail::JsonFormatter& formatter) { fmt::detail::BufferWriteManip(formatter.buffer_out).FastWriteCharArray("null", 4).value(); } }; } -namespace StreamFormat::JSON::Detail +namespace stream::JSON::detail { template - void JsonFormatter::Format(const T& t) + void JsonFormatter::format(const T& t) { - JsonSerializer::Format(t, *this); + JsonSerializer::format(t, *this); } template - void JsonParser::Parse(T& t) + void JsonParser::parse(T& t) { - JsonSerializer::Parse(t, *this); + JsonSerializer::parse(t, *this); } } -namespace StreamFormat::JSON +namespace stream::JSON { template struct FormatAsJson @@ -322,19 +322,19 @@ namespace StreamFormat::JSON }; } -#include "StreamFormat/FMT.h" -namespace StreamFormat::FMT +#include "stream/fmt.h" +namespace stream::fmt { #ifdef STREAMFORMAT_FORMATTER_DECLARED template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static std::expected Format(const JSON::FormatAsJson& json, FormatterExecutor& executor) + [[nodiscard]] static std::expected format(const JSON::FormatAsJson& json, FormatterExecutor& executor) { bool ordered_struct = executor.Data.Specifiers.Has("ordered_struct"); - JSON::Detail::JsonFormatter::FormatSettings settings{.OrderedStruct = ordered_struct, .FloatPrecision = executor.Data.FloatPrecision}; - JSON::Detail::JsonFormatter jsonFormatter(executor.BufferOut, settings); - JSON::JsonSerializer::Format(json.Value, jsonFormatter); + JSON::detail::JsonFormatter::FormatSettings settings{.OrderedStruct = ordered_struct, .FloatPrecision = executor.Data.FloatPrecision}; + JSON::detail::JsonFormatter jsonFormatter(executor.buffer_out, settings); + JSON::JsonSerializer::format(json.Value, jsonFormatter); return {}; } }; @@ -344,12 +344,12 @@ namespace StreamFormat::FMT template struct ParserType, ParserExecutor> { - [[nodiscard]] static std::expected Parse(T& json, ParserExecutor& executor) + [[nodiscard]] static std::expected parse(T& json, ParserExecutor& executor) { - JSON::Detail::JsonParser jsonParser(*executor.BufferIn.Manager); + JSON::detail::JsonParser jsonParser(*executor.BufferIn.Manager); jsonParser.BufferIn.CurrentPos = executor.BufferIn.CurrentPos; // TODO: - // JSON::JsonSerializer::Parse(json.Value, jsonParser); + // JSON::JsonSerializer::parse(json.Value, jsonParser); executor.BufferIn.CurrentPos = jsonParser.BufferIn.CurrentPos; return {}; } diff --git a/src/StreamFormat/Json/Serializers/BaseSerializers.h b/src/stream/json/serializers/base_serializers.h similarity index 67% rename from src/StreamFormat/Json/Serializers/BaseSerializers.h rename to src/stream/json/serializers/base_serializers.h index d30fb32e..7706cae9 100644 --- a/src/StreamFormat/Json/Serializers/BaseSerializers.h +++ b/src/stream/json/serializers/base_serializers.h @@ -5,22 +5,22 @@ #include -namespace StreamFormat::JSON +namespace stream::JSON { template requires (std::is_integral_v && !std::is_floating_point_v) struct JsonSerializer { - static inline void Parse(T& t, Detail::JsonParser& parser) { JsonNumberSerializer::ParseInteger(t, parser); } - static inline void Format(const T t, Detail::JsonFormatter& formatter) { JsonNumberSerializer::FormatInteger(t, formatter); } + static inline void parse(T& t, detail::JsonParser& parser) { JsonNumberSerializer::ParseInteger(t, parser); } + static inline void format(const T t, detail::JsonFormatter& formatter) { JsonNumberSerializer::FormatInteger(t, formatter); } }; template requires std::is_floating_point_v struct JsonSerializer { - static inline void Parse(T& t, Detail::JsonParser& parser) { JsonNumberSerializer::ParseFloat(t, parser); } - static inline void Format(const T t, Detail::JsonFormatter& formatter) { JsonNumberSerializer::FormatFloat(t, formatter); } + static inline void parse(T& t, detail::JsonParser& parser) { JsonNumberSerializer::ParseFloat(t, parser); } + static inline void format(const T t, detail::JsonFormatter& formatter) { JsonNumberSerializer::FormatFloat(t, formatter); } }; template @@ -29,9 +29,9 @@ namespace StreamFormat::JSON using ArraySubObjectType = T; static inline void AddArraySubObject(T (&t)[SIZE], std::size_t idx, ArraySubObjectType&& subObject) { t[idx] = std::move(subObject); } - static inline void Parse(T (&t)[SIZE], Detail::JsonParser& parser) + static inline void parse(T (&t)[SIZE], detail::JsonParser& parser) { - if constexpr (FMT::Detail::IsCharType::Value) + if constexpr (fmt::detail::IsCharType::Value) { // TODO } @@ -41,9 +41,9 @@ namespace StreamFormat::JSON } } - static inline void Format(const T (&t)[SIZE], Detail::JsonFormatter& formatter) + static inline void format(const T (&t)[SIZE], detail::JsonFormatter& formatter) { - if constexpr (FMT::Detail::IsCharType::Value) + if constexpr (fmt::detail::IsCharType::Value) { // TODO } @@ -59,14 +59,14 @@ namespace StreamFormat::JSON template struct JsonSerializer { - static inline void Parse([[maybe_unused]] T* t, Detail::JsonParser& parser) + static inline void parse([[maybe_unused]] T* t, detail::JsonParser& parser) { - if (t == nullptr) throw Detail::JsonGivenTypeError{}; + if (t == nullptr) throw detail::JsonGivenTypeError{}; // TODO } - static inline void Format([[maybe_unused]] const T* t, Detail::JsonFormatter& formatter) + static inline void format([[maybe_unused]] const T* t, detail::JsonFormatter& formatter) { - if (t == nullptr) throw Detail::JsonGivenTypeError{}; + if (t == nullptr) throw detail::JsonGivenTypeError{}; // TODO } }; diff --git a/src/StreamFormat/Json/Serializers/JsonObjectsSerializer.h b/src/stream/json/serializers/json_objects_serializer.h similarity index 65% rename from src/StreamFormat/Json/Serializers/JsonObjectsSerializer.h rename to src/stream/json/serializers/json_objects_serializer.h index bff42cea..c279ded7 100644 --- a/src/StreamFormat/Json/Serializers/JsonObjectsSerializer.h +++ b/src/stream/json/serializers/json_objects_serializer.h @@ -8,14 +8,14 @@ #include -namespace StreamFormat::JSON +namespace stream::JSON { template <> struct JsonSerializer> { - static inline void Parse(std::unique_ptr& t, Detail::JsonParser& parser) + static inline void parse(std::unique_ptr& t, detail::JsonParser& parser) { - FMT::Detail::BufferTestManip(parser.BufferIn).IgnoreEveryBlanks(); + fmt::detail::BufferTestManip(parser.BufferIn).IgnoreEveryBlanks(); if (parser.IsJsonStringBegin()) t = std::make_unique(); else if (parser.IsJsonNumberBegin()) @@ -32,74 +32,74 @@ namespace StreamFormat::JSON t->ParserExecute(parser); } - static inline void Format(const std::unique_ptr& t, Detail::JsonFormatter& formatter) { t->FormatterExecute(formatter); } + static inline void format(const std::unique_ptr& t, detail::JsonFormatter& formatter) { t->FormatterExecute(formatter); } }; template <> struct JsonSerializer { - static inline void Format(const JsonObject& t, Detail::JsonFormatter& formatter) { t.FormatterExecute(formatter); } + static inline void format(const JsonObject& t, detail::JsonFormatter& formatter) { t.FormatterExecute(formatter); } }; template <> struct JsonSerializer { - static inline void Parse(JsonStringObject& t, Detail::JsonParser& parser) + static inline void parse(JsonStringObject& t, detail::JsonParser& parser) { t.String.clear(); JsonStringSerializer::ParseSTDString(t.String, parser); } - static inline void Format(const JsonStringObject& t, Detail::JsonFormatter& formatter) { JsonStringSerializer::FormatSTDString(t.String, formatter); } + static inline void format(const JsonStringObject& t, detail::JsonFormatter& formatter) { JsonStringSerializer::FormatSTDString(t.String, formatter); } }; template <> struct JsonSerializer { - static inline void Parse(JsonNumberObject& t, Detail::JsonParser& parser) { JsonNumberSerializer::ParseFloat(t.Number, parser); } + static inline void parse(JsonNumberObject& t, detail::JsonParser& parser) { JsonNumberSerializer::ParseFloat(t.Number, parser); } - static inline void Format(const JsonNumberObject& t, Detail::JsonFormatter& formatter) { JsonNumberSerializer::FormatFloat(t.Number, formatter); } + static inline void format(const JsonNumberObject& t, detail::JsonFormatter& formatter) { JsonNumberSerializer::FormatFloat(t.Number, formatter); } }; template <> struct JsonSerializer { - static inline void Parse(JsonBooleanObject& t, Detail::JsonParser& parser) { JsonBooleanSerializer::ParseBool(t.Boolean, parser); } + static inline void parse(JsonBooleanObject& t, detail::JsonParser& parser) { JsonBooleanSerializer::ParseBool(t.Boolean, parser); } - static inline void Format(const JsonBooleanObject& t, Detail::JsonFormatter& formatter) { JsonBooleanSerializer::FormatBool(t.Boolean, formatter); } + static inline void format(const JsonBooleanObject& t, detail::JsonFormatter& formatter) { JsonBooleanSerializer::FormatBool(t.Boolean, formatter); } }; template <> struct JsonSerializer { - static inline void Parse(JsonNullObject&, Detail::JsonParser& parser) { JsonNullSerializer::ParseNull(parser); } + static inline void parse(JsonNullObject&, detail::JsonParser& parser) { JsonNullSerializer::ParseNull(parser); } - static inline void Format(const JsonNullObject&, Detail::JsonFormatter& formatter) { JsonNullSerializer::FormatNull(formatter); } + static inline void format(const JsonNullObject&, detail::JsonFormatter& formatter) { JsonNullSerializer::FormatNull(formatter); } }; template <> struct JsonSerializer { - static inline void Parse(JsonStructObject& t, Detail::JsonParser& parser) { parser.Parse(t.Objects); } - static inline void Format(const JsonStructObject& t, Detail::JsonFormatter& formatter) + static inline void parse(JsonStructObject& t, detail::JsonParser& parser) { parser.parse(t.Objects); } + static inline void format(const JsonStructObject& t, detail::JsonFormatter& formatter) { if (formatter.Settings.OrderedStruct == false) { - formatter.Format(t.Objects); + formatter.format(t.Objects); return; } std::map objectsOrdered; for (auto& [name, objects] : t.Objects) objectsOrdered.insert({name, objects.get()}); - formatter.Format(objectsOrdered); + formatter.format(objectsOrdered); } }; template <> struct JsonSerializer { - static inline void Parse(JsonArrayObject& t, Detail::JsonParser& parser) { parser.Parse(t.Objects); } - static inline void Format(const JsonArrayObject& t, Detail::JsonFormatter& formatter) { formatter.Format(t.Objects); } + static inline void parse(JsonArrayObject& t, detail::JsonParser& parser) { parser.parse(t.Objects); } + static inline void format(const JsonArrayObject& t, detail::JsonFormatter& formatter) { formatter.format(t.Objects); } }; } diff --git a/src/StreamFormat/Json/Serializers/Serializers.h b/src/stream/json/serializers/serializers.h similarity index 100% rename from src/StreamFormat/Json/Serializers/Serializers.h rename to src/stream/json/serializers/serializers.h diff --git a/src/StreamFormat/Json/Serializers/STDSerializers/BasicSTDSerializers.h b/src/stream/json/serializers/std_serializers/basic_std_serializers.h similarity index 58% rename from src/StreamFormat/Json/Serializers/STDSerializers/BasicSTDSerializers.h rename to src/stream/json/serializers/std_serializers/basic_std_serializers.h index 881f418b..43222675 100644 --- a/src/StreamFormat/Json/Serializers/STDSerializers/BasicSTDSerializers.h +++ b/src/stream/json/serializers/std_serializers/basic_std_serializers.h @@ -1,25 +1,25 @@ #pragma once -#include "StreamFormat/Json/JsonSerializer.h" +#include "stream/Json/JsonSerializer.h" #include -namespace StreamFormat::JSON +namespace stream::JSON { template <> struct JsonSerializer { - static inline void Parse(std::string& t, Detail::JsonParser& parser) { JsonStringSerializer::ParseSTDString(t, parser); } - static inline void Format(const std::string& t, Detail::JsonFormatter& formatter) { JsonStringSerializer::FormatSTDString(t, formatter); } + static inline void parse(std::string& t, detail::JsonParser& parser) { JsonStringSerializer::ParseSTDString(t, parser); } + static inline void format(const std::string& t, detail::JsonFormatter& formatter) { JsonStringSerializer::FormatSTDString(t, formatter); } }; template <> struct JsonSerializer { - static inline void Parse(std::string_view& t, Detail::JsonParser& parser) + static inline void parse(std::string_view& t, detail::JsonParser& parser) { // TODO: } - static inline void Format(const std::string_view& t, Detail::JsonFormatter& formatter) { JsonStringSerializer::FormatSTDString(t, formatter); } + static inline void format(const std::string_view& t, detail::JsonFormatter& formatter) { JsonStringSerializer::FormatSTDString(t, formatter); } }; } diff --git a/src/StreamFormat/Json/Serializers/STDSerializers/JSON_map.h b/src/stream/json/serializers/std_serializers/json_map.h similarity index 81% rename from src/StreamFormat/Json/Serializers/STDSerializers/JSON_map.h rename to src/stream/json/serializers/std_serializers/json_map.h index 498104dd..947dcb60 100644 --- a/src/StreamFormat/Json/Serializers/STDSerializers/JSON_map.h +++ b/src/stream/json/serializers/std_serializers/json_map.h @@ -1,10 +1,10 @@ #pragma once -#include "StreamFormat/Json/JsonSerializer.h" +#include "stream/Json/JsonSerializer.h" #include -namespace StreamFormat::JSON +namespace stream::JSON { template struct JsonSerializer> @@ -12,13 +12,13 @@ namespace StreamFormat::JSON using KeyType = K; using StructSubObjectType = T; - static inline void Parse(std::map& t, Detail::JsonParser& parser) { JsonStructSerializer::LoadAllSubObjects>(t, parser); } + static inline void parse(std::map& t, detail::JsonParser& parser) { JsonStructSerializer::LoadAllSubObjects>(t, parser); } static inline void AddStructSubObject(std::map& t, std::size_t, std::string&& name, StructSubObjectType&& subObject) { t.insert({std::move(name), std::move(subObject)}); } - static inline void Format(const std::map& t, Detail::JsonFormatter& formatter) + static inline void format(const std::map& t, detail::JsonFormatter& formatter) { JsonStructSerializer::FormatBegin(formatter); std::size_t idx = 0; @@ -34,13 +34,13 @@ namespace StreamFormat::JSON using KeyType = K; using StructSubObjectType = T; - static inline void Parse(std::multimap& t, Detail::JsonParser& parser) { JsonStructSerializer::LoadAllSubObjects>(t, parser); } + static inline void parse(std::multimap& t, detail::JsonParser& parser) { JsonStructSerializer::LoadAllSubObjects>(t, parser); } static inline void AddStructSubObject(std::multimap& t, std::size_t, std::string&& name, StructSubObjectType&& subObject) { t.insert({std::move(name), std::move(subObject)}); } - static inline void Format(const std::multimap& t, Detail::JsonFormatter& formatter) + static inline void format(const std::multimap& t, detail::JsonFormatter& formatter) { JsonStructSerializer::FormatBegin(formatter); std::size_t idx = 0; diff --git a/src/StreamFormat/Json/Serializers/STDSerializers/JSON_unordered_map.h b/src/stream/json/serializers/std_serializers/json_unordered_map.h similarity index 77% rename from src/StreamFormat/Json/Serializers/STDSerializers/JSON_unordered_map.h rename to src/stream/json/serializers/std_serializers/json_unordered_map.h index cc56a68f..9a39d85c 100644 --- a/src/StreamFormat/Json/Serializers/STDSerializers/JSON_unordered_map.h +++ b/src/stream/json/serializers/std_serializers/json_unordered_map.h @@ -1,11 +1,11 @@ #pragma once -#include "StreamFormat/Json/JsonObjects.h" -#include "StreamFormat/Json/JsonSerializer.h" +#include "stream/Json/JsonObjects.h" +#include "stream/Json/JsonSerializer.h" #include -namespace StreamFormat::JSON +namespace stream::JSON { template struct JsonSerializer> @@ -13,13 +13,13 @@ namespace StreamFormat::JSON using KeyType = K; using StructSubObjectType = T; - static inline void Parse(std::unordered_map& t, Detail::JsonParser& parser) { JsonStructSerializer::LoadAllSubObjects>(t, parser); } + static inline void parse(std::unordered_map& t, detail::JsonParser& parser) { JsonStructSerializer::LoadAllSubObjects>(t, parser); } static inline void AddStructSubObject(std::unordered_map& t, std::size_t, std::string&& name, StructSubObjectType&& subObject) { t.insert({std::move(name), std::move(subObject)}); } - static inline void Format(const std::unordered_map& t, Detail::JsonFormatter& formatter) + static inline void format(const std::unordered_map& t, detail::JsonFormatter& formatter) { JsonStructSerializer::FormatBegin(formatter); std::size_t idx = 0; @@ -35,7 +35,7 @@ namespace StreamFormat::JSON using KeyType = K; using StructSubObjectType = T; - static inline void Parse(std::unordered_multimap& t, Detail::JsonParser& parser) + static inline void parse(std::unordered_multimap& t, detail::JsonParser& parser) { JsonStructSerializer::LoadAllSubObjects>(t, parser); } @@ -44,7 +44,7 @@ namespace StreamFormat::JSON t.insert({std::move(name), std::move(subObject)}); } - static inline void Format(const std::unordered_multimap& t, Detail::JsonFormatter& formatter) + static inline void format(const std::unordered_multimap& t, detail::JsonFormatter& formatter) { JsonStructSerializer::FormatBegin(formatter); std::size_t idx = 0; diff --git a/src/StreamFormat/Json/Serializers/STDSerializers/JSON_vector.h b/src/stream/json/serializers/std_serializers/json_vector.h similarity index 74% rename from src/StreamFormat/Json/Serializers/STDSerializers/JSON_vector.h rename to src/stream/json/serializers/std_serializers/json_vector.h index 7b9426b4..d1159116 100644 --- a/src/StreamFormat/Json/Serializers/STDSerializers/JSON_vector.h +++ b/src/stream/json/serializers/std_serializers/json_vector.h @@ -1,21 +1,21 @@ #pragma once -#include "StreamFormat/Json/JsonObjects.h" -#include "StreamFormat/Json/JsonSerializer.h" +#include "stream/Json/JsonObjects.h" +#include "stream/Json/JsonSerializer.h" #include -namespace StreamFormat::JSON +namespace stream::JSON { template struct JsonSerializer> { using ArraySubObjectType = T; - static inline void Parse(std::vector& t, Detail::JsonParser& parser) { JsonArraySerializer::LoadAllSubObjects>(t, parser); } + static inline void parse(std::vector& t, detail::JsonParser& parser) { JsonArraySerializer::LoadAllSubObjects>(t, parser); } static inline void AddArraySubObject(std::vector& t, std::size_t, ArraySubObjectType&& subObject) { t.emplace_back(std::move(subObject)); } - static inline void Format(const std::vector& t, Detail::JsonFormatter& formatter) + static inline void format(const std::vector& t, detail::JsonFormatter& formatter) { JsonArraySerializer::FormatBegin(formatter); std::size_t idx = 0; diff --git a/src/StreamFormat/ProfilerManager.h b/src/stream/profiler.h similarity index 100% rename from src/StreamFormat/ProfilerManager.h rename to src/stream/profiler.h diff --git a/src/StreamFormat/ProfilerManager/AllEvents.h b/src/stream/profiler/all_events.h similarity index 96% rename from src/StreamFormat/ProfilerManager/AllEvents.h rename to src/stream/profiler/all_events.h index e964438a..bdb9701d 100644 --- a/src/StreamFormat/ProfilerManager/AllEvents.h +++ b/src/stream/profiler/all_events.h @@ -2,7 +2,7 @@ #include "Event.h" -namespace StreamFormat::ProfilerManager +namespace stream::ProfilerManager { class DurationEvent : public Event { diff --git a/src/StreamFormat/ProfilerManager/Detail.h b/src/stream/profiler/detail.h similarity index 85% rename from src/StreamFormat/ProfilerManager/Detail.h rename to src/stream/profiler/detail.h index af796c37..12352320 100644 --- a/src/StreamFormat/ProfilerManager/Detail.h +++ b/src/stream/profiler/detail.h @@ -2,7 +2,7 @@ #include -namespace StreamFormat::ProfilerManager +namespace stream::ProfilerManager { inline double GetMicroseconds() { diff --git a/src/StreamFormat/ProfilerManager/Event.h b/src/stream/profiler/event.h similarity index 85% rename from src/StreamFormat/ProfilerManager/Event.h rename to src/stream/profiler/event.h index 1fd6281f..7a3c0a3e 100644 --- a/src/StreamFormat/ProfilerManager/Event.h +++ b/src/stream/profiler/event.h @@ -1,9 +1,9 @@ #pragma once -#include "Detail.h" +#include "detail.h" #include "EventData.h" -#include "StreamFormat/Core/Prelude.h" -#include "StreamFormat/FMT.h" +#include "stream/core/prelude.h" +#include "stream/fmt.h" #include #include @@ -11,7 +11,7 @@ // https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview -namespace StreamFormat::ProfilerManager +namespace stream::ProfilerManager { int GetPid(); @@ -107,11 +107,11 @@ namespace StreamFormat::ProfilerManager Event() = default; Event(const std::string& name, const std::string& category, EventType type, EventData* data = nullptr) - : Info(name, category, type, data) + : info(name, category, type, data) {} Event(std::string&& name, std::string&& category, EventType type, EventData* data = nullptr) - : Info(std::move(name), std::move(category), type, data) + : info(std::move(name), std::move(category), type, data) {} virtual ~Event() = default; @@ -124,12 +124,12 @@ namespace StreamFormat::ProfilerManager }; } -namespace StreamFormat::FMT +namespace stream::fmt { template - struct FormatterType + struct FormatterType { - [[nodiscard]] static std::expected Format(const StreamFormat::ProfilerManager::EventType& t, FormatterExecutor& executor) - { return executor.BufferOut.Pushback(static_cast(t)); } + [[nodiscard]] static std::expected format(const stream::ProfilerManager::EventType& t, FormatterExecutor& executor) + { return executor.buffer_out.Pushback(static_cast(t)); } }; } diff --git a/src/StreamFormat/ProfilerManager/EventData.h b/src/stream/profiler/event_data.h similarity index 53% rename from src/StreamFormat/ProfilerManager/EventData.h rename to src/stream/profiler/event_data.h index cd7dc794..7f91642f 100644 --- a/src/StreamFormat/ProfilerManager/EventData.h +++ b/src/stream/profiler/event_data.h @@ -1,8 +1,8 @@ #pragma once -#include "StreamFormat/Json.h" +#include "stream/Json.h" -namespace StreamFormat::ProfilerManager +namespace stream::ProfilerManager { class EventData { @@ -10,8 +10,8 @@ namespace StreamFormat::ProfilerManager virtual ~EventData() = default; public: - virtual void ToJson(JSON::Detail::JsonFormatter& formatter) const = 0; - virtual void FromJson(JSON::Detail::JsonParser& parser) = 0; + virtual void ToJson(JSON::detail::JsonFormatter& formatter) const = 0; + virtual void FromJson(JSON::detail::JsonParser& parser) = 0; }; class EventDataJsonObject final : public EventData @@ -20,8 +20,8 @@ namespace StreamFormat::ProfilerManager ~EventDataJsonObject() override = default; public: - void ToJson(JSON::Detail::JsonFormatter& formatter) const override { JSON::JsonSerializer::Format(Data, formatter); } - void FromJson(JSON::Detail::JsonParser& parser) override { JSON::JsonSerializer::Parse(Data, parser); } + void ToJson(JSON::detail::JsonFormatter& formatter) const override { JSON::JsonSerializer::format(Data, formatter); } + void FromJson(JSON::detail::JsonParser& parser) override { JSON::JsonSerializer::parse(Data, parser); } JSON::JsonStructObject Data; }; } diff --git a/src/StreamFormat/ProfilerManager/GetPid.cpp b/src/stream/profiler/get_pid.cpp similarity index 90% rename from src/StreamFormat/ProfilerManager/GetPid.cpp rename to src/stream/profiler/get_pid.cpp index a535e715..2732b4f9 100644 --- a/src/StreamFormat/ProfilerManager/GetPid.cpp +++ b/src/stream/profiler/get_pid.cpp @@ -9,7 +9,7 @@ #include #endif -namespace StreamFormat::ProfilerManager +namespace stream::ProfilerManager { int GetPid() { diff --git a/src/StreamFormat/ProfilerManager/Profiler.h b/src/stream/profiler/profiler.h similarity index 80% rename from src/StreamFormat/ProfilerManager/Profiler.h rename to src/stream/profiler/profiler.h index 103ceaa6..d27ae38b 100644 --- a/src/StreamFormat/ProfilerManager/Profiler.h +++ b/src/stream/profiler/profiler.h @@ -1,13 +1,13 @@ #pragma once -#include "StreamFormat/Core/Prelude.h" -#include "StreamFormat/FLog.h" +#include "stream/core/prelude.h" +#include "stream/flog.h" #include "AllEvents.h" #include "Event.h" #include "ProfilerEventCreator.h" -namespace StreamFormat::ProfilerManager +namespace stream::ProfilerManager { class Profiler { @@ -27,7 +27,7 @@ namespace StreamFormat::ProfilerManager public: void AddEvent(const Event& event) { AddEventInfo(event.Info); } void AddEventInfo(const EventInfo& eventInfo) { Events.push_back(eventInfo); } - inline StreamFormat::FLog::BasicLogger& GetLogger() { return Logger; } + inline stream::flog::BasicLogger& GetLogger() { return Logger; } public: static Profiler& GetInstance() @@ -38,7 +38,7 @@ namespace StreamFormat::ProfilerManager public: std::string Name; - FLog::BasicLogger Logger; + flog::BasicLogger Logger; DurationEvent ProfilerDuration; std::vector Events; }; diff --git a/src/StreamFormat/ProfilerManager/ProfilerEventCreator.cpp b/src/stream/profiler/profiler_event_creator.cpp similarity index 87% rename from src/StreamFormat/ProfilerManager/ProfilerEventCreator.cpp rename to src/stream/profiler/profiler_event_creator.cpp index 4114b2b2..c6715ece 100644 --- a/src/StreamFormat/ProfilerManager/ProfilerEventCreator.cpp +++ b/src/stream/profiler/profiler_event_creator.cpp @@ -1,7 +1,7 @@ #include "ProfilerEventCreator.h" #include "Profiler.h" -namespace StreamFormat::ProfilerManager +namespace stream::ProfilerManager { ScopeProfile::~ScopeProfile() { @@ -11,11 +11,11 @@ namespace StreamFormat::ProfilerManager double sec = millis / 1000; if (sec > 1.5) - m_Profiler.GetLogger().Trace("{} : {} seconds", Info.Name, sec); + m_Profiler.GetLogger().trace("{} : {} seconds", Info.Name, sec); else if (millis > 5.0) - m_Profiler.GetLogger().Trace("{} : {} ms", Info.Name, millis); + m_Profiler.GetLogger().trace("{} : {} ms", Info.Name, millis); else - m_Profiler.GetLogger().Trace("{} : {} us", Info.Name, Info.Duration); + m_Profiler.GetLogger().trace("{} : {} us", Info.Name, Info.Duration); m_Profiler.AddEvent(*this); } diff --git a/src/StreamFormat/ProfilerManager/ProfilerEventCreator.h b/src/stream/profiler/profiler_event_creator.h similarity index 97% rename from src/StreamFormat/ProfilerManager/ProfilerEventCreator.h rename to src/stream/profiler/profiler_event_creator.h index 6bf6b7da..93377bbd 100644 --- a/src/StreamFormat/ProfilerManager/ProfilerEventCreator.h +++ b/src/stream/profiler/profiler_event_creator.h @@ -2,7 +2,7 @@ #include "AllEvents.h" -namespace StreamFormat::ProfilerManager +namespace stream::ProfilerManager { class Profiler; diff --git a/src/StreamFormat/ProfilerManager/ProfilerFactory.cpp b/src/stream/profiler/profiler_factory.cpp similarity index 84% rename from src/StreamFormat/ProfilerManager/ProfilerFactory.cpp rename to src/stream/profiler/profiler_factory.cpp index b4c8aabd..c06ce71a 100644 --- a/src/StreamFormat/ProfilerManager/ProfilerFactory.cpp +++ b/src/stream/profiler/profiler_factory.cpp @@ -3,7 +3,7 @@ #include -namespace StreamFormat::ProfilerManager +namespace stream::ProfilerManager { void ProfilerFactory::ToJson(Profiler& profiler, std::filesystem::path path) { @@ -14,7 +14,7 @@ namespace StreamFormat::ProfilerManager std::ofstream file(path.string(), std::ios::out); JSON::FormatAsJson formatProfiler(profiler); - FMT::FilePrint(file, formatProfiler).value(); + fmt::FilePrint(file, formatProfiler).value(); file.close(); } } diff --git a/src/StreamFormat/ProfilerManager/ProfilerFactory.h b/src/stream/profiler/profiler_factory.h similarity index 83% rename from src/StreamFormat/ProfilerManager/ProfilerFactory.h rename to src/stream/profiler/profiler_factory.h index c363bf11..842fb2c6 100644 --- a/src/StreamFormat/ProfilerManager/ProfilerFactory.h +++ b/src/stream/profiler/profiler_factory.h @@ -4,7 +4,7 @@ #include -namespace StreamFormat::ProfilerManager +namespace stream::ProfilerManager { class ProfilerFactory { diff --git a/src/stream/profiler/profiler_json_serializers.h b/src/stream/profiler/profiler_json_serializers.h new file mode 100644 index 00000000..1a30c5e1 --- /dev/null +++ b/src/stream/profiler/profiler_json_serializers.h @@ -0,0 +1,83 @@ +#pragma once + +#include "ProfilerFactory.h" +#include "stream/Json.h" + +namespace stream::JSON +{ + template <> + struct JsonSerializer + { + static inline void format(const ProfilerManager::Profiler& t, detail::JsonFormatter& formatter) + { + auto intermediate = formatter.GetStructIntermediate(); + intermediate.format("displayTimeUnit", "us"); + intermediate.format("traceEvents", t.Events); + } + + static inline void parse(ProfilerManager::Profiler& t, detail::JsonParser& parser) + { + auto intermediate = parser.GetStructIntermediate(); + intermediate.parse("traceEvents", t.Events); + } + }; + + template <> + struct JsonSerializer + { + static inline void format(const ProfilerManager::EventType& t, detail::JsonFormatter& formatter) { formatter.format(static_cast(t)); } + + static inline void parse(ProfilerManager::EventType& t, detail::JsonParser& parser) { parser.parse(reinterpret_cast(t)); } + }; + + template <> + struct JsonSerializer + { + static inline void format(const ProfilerManager::EventData& t, detail::JsonFormatter& formatter) { t.ToJson(formatter); } + + static inline void parse(ProfilerManager::EventData& t, detail::JsonParser& parser) { t.FromJson(parser); } + }; + + template <> + struct JsonSerializer + { + static inline void format(const ProfilerManager::EventInfo& t, detail::JsonFormatter& formatter) + { + auto intermediate = formatter.GetStructIntermediate(); + intermediate.format("name", t.Name); + intermediate.format("cat", t.Category); + intermediate.format("ph", t.Type); + intermediate.format("pid", t.PID); + intermediate.format("tid", t.TID); + intermediate.format("ts", t.TimeOfEvent); + intermediate.format("dur", t.Duration); + intermediate.format("id", t.Id); + if (t.Data != nullptr) intermediate.format("args", *t.Data); + } + + static inline void parse(ProfilerManager::EventInfo& t, detail::JsonParser& parser) + { + auto intermediate = parser.GetStructIntermediate(); + intermediate.parse("name", t.Name); + intermediate.parse("cat", t.Category); + intermediate.parse("ph", t.Type); + intermediate.parse("pid", t.PID); + intermediate.parse("tid", t.TID); + intermediate.parse("ts", t.TimeOfEvent); + intermediate.parse("dur", t.Duration); + intermediate.parse("id", t.Id); + intermediate.parse("args", *t.Data); + } + }; + + template <> + struct JsonSerializer + { + static inline void format(const ProfilerManager::Event& t, detail::JsonFormatter& formatter) + { + return JsonSerializer::format(t.Info, formatter); + } + + static inline void parse(ProfilerManager::Event& t, detail::JsonParser& parser) { return JsonSerializer::parse(t.Info, parser); } + }; +} diff --git a/src/stream/profiler/profiler_macros.h b/src/stream/profiler/profiler_macros.h new file mode 100644 index 00000000..943a508e --- /dev/null +++ b/src/stream/profiler/profiler_macros.h @@ -0,0 +1,17 @@ +#pragma once + +#ifdef STREAMFORMAT_PROFILING_ENABLE + +#define SFP_PROFILE_FUNCTION() stream::ProfilerManager::ScopeProfile profile##__LINE__(stream::ProfilerManager::Profiler::GetInstance(), __FUNCSIG__, "Function") +#define SFP_PROFILE_FUNCTION_FMT(...) \ + stream::ProfilerManager::ScopeProfile profile##__LINE__(stream::ProfilerManager::Profiler::GetInstance(), \ + stream::ProfilerManager::fmt::FormatString(__VA_ARGS__), "Function") +#define SFP_SAVE_DEFAULT_PROFILER() stream::ProfilerManager::ProfilerFactory::ToJson(stream::ProfilerManager::Profiler::GetInstance()) + +#else // STREAMFORMAT_PROFILING_ENABLE + +#define SFP_PROFILE_FUNCTION() +#define SFP_PROFILE_FUNCTION_FMT(...) +#define SFP_SAVE_DEFAULT_PROFILER() + +#endif // STREAMFORMAT_PROFILING_ENABLE diff --git a/src/StreamFormat/Tester/CopyMoveCheck.h b/src/stream/tester/copy_move_check.h similarity index 74% rename from src/StreamFormat/Tester/CopyMoveCheck.h rename to src/stream/tester/copy_move_check.h index a953ae4c..7e9c4a51 100644 --- a/src/StreamFormat/Tester/CopyMoveCheck.h +++ b/src/stream/tester/copy_move_check.h @@ -1,56 +1,56 @@ #pragma once -#include "StreamFormat/FLog.h" +#include "stream/flog.h" -namespace StreamFormat::Tester +namespace stream::Tester { class CopyMoveCheck { public: - static inline FLog::BasicLogger Logger; + static inline flog::BasicLogger Logger; public: CopyMoveCheck(const std::string& name) : m_Name(name) { - Logger.Info("CopyMoveCheck {} : {:C:red} ( {:C:red} )", m_Name, "Default (copy string) Constructor", "TestCopy(const std::string& name)"); + Logger.info("CopyMoveCheck {} : {:C:red} ( {:C:red} )", m_Name, "Default (copy string) Constructor", "TestCopy(const std::string& name)"); } CopyMoveCheck(std::string&& name) : m_Name(std::move(name)) { - Logger.Info("CopyMoveCheck {} : {:C:red} ( {:C:red} )", m_Name, "Default (move string) Constructor", "TestCopy(std::string&& name)"); + Logger.info("CopyMoveCheck {} : {:C:red} ( {:C:red} )", m_Name, "Default (move string) Constructor", "TestCopy(std::string&& name)"); } CopyMoveCheck(CopyMoveCheck& other) : m_Name("Copy of " + other.m_Name) { - Logger.Info("CopyMoveCheck {} : {:C:red} ( {:C:red} )", m_Name, "Copy Constructor", "TestCopy(TestCopy&)"); + Logger.info("CopyMoveCheck {} : {:C:red} ( {:C:red} )", m_Name, "Copy Constructor", "TestCopy(TestCopy&)"); } CopyMoveCheck(const CopyMoveCheck& other) : m_Name("Copy of " + other.m_Name) { - Logger.Info("CopyMoveCheck {} : {:C:red} ( {:C:red} )", m_Name, "Const Copy Constructor", "TestCopy(const TestCopy&)"); + Logger.info("CopyMoveCheck {} : {:C:red} ( {:C:red} )", m_Name, "Const Copy Constructor", "TestCopy(const TestCopy&)"); } CopyMoveCheck(CopyMoveCheck&& other) noexcept : m_Name("Move of " + other.m_Name) { - Logger.Info("CopyMoveCheck {} : {:C:red} ( {:C:red} )", m_Name, "Move Constructor", "TestCopy(TestCopy&&)"); + Logger.info("CopyMoveCheck {} : {:C:red} ( {:C:red} )", m_Name, "Move Constructor", "TestCopy(TestCopy&&)"); } CopyMoveCheck(const CopyMoveCheck&& other) noexcept : m_Name("Move of " + other.m_Name) { - Logger.Info("CopyMoveCheck {} : {:C:red} ( {:C:red} )", m_Name, "Const Move Constructor", "TestCopy(const TestCopy&&)"); + Logger.info("CopyMoveCheck {} : {:C:red} ( {:C:red} )", m_Name, "Const Move Constructor", "TestCopy(const TestCopy&&)"); } CopyMoveCheck& operator=(CopyMoveCheck& other) { m_Name = "Copy Of " + other.m_Name; - Logger.Info("CopyMoveCheck {} : {:C:red} ( {:C:red} )", m_Name, "Copy Assignment", "TestCopy& operator=(TestCopy&)"); + Logger.info("CopyMoveCheck {} : {:C:red} ( {:C:red} )", m_Name, "Copy Assignment", "TestCopy& operator=(TestCopy&)"); return *this; } @@ -58,7 +58,7 @@ namespace StreamFormat::Tester { m_Name = "Copy Of " + other.m_Name; - Logger.Info("CopyMoveCheck {} : {:C:red} ( {:C:red} )", m_Name, "Const Copy Assignment", "TestCopy& operator=(const TestCopy&)"); + Logger.info("CopyMoveCheck {} : {:C:red} ( {:C:red} )", m_Name, "Const Copy Assignment", "TestCopy& operator=(const TestCopy&)"); return *this; } @@ -66,7 +66,7 @@ namespace StreamFormat::Tester { m_Name = "Move Of " + other.m_Name; - Logger.Info("CopyMoveCheck {} : {:C:red} ( {:C:red} )", m_Name, "Move Assignment", "TestCopy& operator=(TestCopy&&)"); + Logger.info("CopyMoveCheck {} : {:C:red} ( {:C:red} )", m_Name, "Move Assignment", "TestCopy& operator=(TestCopy&&)"); return *this; } @@ -74,7 +74,7 @@ namespace StreamFormat::Tester { m_Name = "Move Of " + other.m_Name; - Logger.Info("CopyMoveCheck {} : {:C:red} ( {:C:red} )", m_Name, "Const Move Assignment", "TestCopy& operator=(const TestCopy&&)"); + Logger.info("CopyMoveCheck {} : {:C:red} ( {:C:red} )", m_Name, "Const Move Assignment", "TestCopy& operator=(const TestCopy&&)"); return *this; } diff --git a/src/StreamFormat/Tester/TestSuite/AllTestSuite.h b/src/stream/tester/test_suite/all_test_suite.h similarity index 100% rename from src/StreamFormat/Tester/TestSuite/AllTestSuite.h rename to src/stream/tester/test_suite/all_test_suite.h diff --git a/src/StreamFormat/Tester/TestSuite/BasicTest.h b/src/stream/tester/test_suite/basic_test.h similarity index 85% rename from src/StreamFormat/Tester/TestSuite/BasicTest.h rename to src/stream/tester/test_suite/basic_test.h index eca962b0..93d6e8b1 100644 --- a/src/StreamFormat/Tester/TestSuite/BasicTest.h +++ b/src/stream/tester/test_suite/basic_test.h @@ -2,9 +2,9 @@ #include "TestSuite.h" -#include "StreamFormat/Core/Prelude.h" +#include "stream/core/prelude.h" -namespace StreamFormat::Tester::Detail +namespace stream::Tester::detail { struct TestFunction : public Test { @@ -12,7 +12,7 @@ namespace StreamFormat::Tester::Detail using FuncType = std::function; public: - TestFunction(std::string&& name, TestSuite& link, FuncType func, const FMT::Detail::FileLocation& location) + TestFunction(std::string&& name, TestSuite& link, FuncType func, const fmt::detail::FileLocation& location) : Test(std::move(name), link, location) , Func(func) { @@ -55,29 +55,29 @@ namespace StreamFormat::Tester::Detail T expected_as_T = static_cast(expected); if (result != expected_as_T) { - Link.TestLogger.Error("{C:red}{} return {} instead of {}", testView, result, expected, FORMAT_SV("test_name", Name)).value(); + Link.TestLogger.error("{C:red}{} return {} instead of {}", testView, result, expected, FORMAT_SV("test_name", Name)).value(); throw TestFailure{}; } - Link.TestLogger.Trace("{C:green}{} return {}", testView, result, FORMAT_SV("test_name", Name)).value(); + Link.TestLogger.trace("{C:green}{} return {}", testView, result, FORMAT_SV("test_name", Name)).value(); } template void TestFunction::TestNotEq(T result, std::convertible_to auto notExpected, std::string_view testView, [[maybe_unused]] int line) { if (result == static_cast(notExpected)) { - Link.TestLogger.Error("{C:red}{} return {} but that result was prohibited", testView, result, FORMAT_SV("test_name", Name)).value(); + Link.TestLogger.error("{C:red}{} return {} but that result was prohibited", testView, result, FORMAT_SV("test_name", Name)).value(); throw TestFailure{}; } - Link.TestLogger.Trace("{C:green}{} return {}", testView, result, FORMAT_SV("test_name", Name)).value(); + Link.TestLogger.trace("{C:green}{} return {}", testView, result, FORMAT_SV("test_name", Name)).value(); } inline void TestFunction::TestAssert(bool assert, std::string_view assertView, [[maybe_unused]] int line) { if (assert == false) { - Link.TestLogger.Error("{C:red}ASSERT FAILED : {}", assertView, FORMAT_SV("test_name", Name)).value(); + Link.TestLogger.error("{C:red}ASSERT FAILED : {}", assertView, FORMAT_SV("test_name", Name)).value(); throw TestFailure{}; } - Link.TestLogger.Trace("{C:green}ASSERT SUCCED : {}", assertView, FORMAT_SV("test_name", Name)).value(); + Link.TestLogger.trace("{C:green}ASSERT SUCCED : {}", assertView, FORMAT_SV("test_name", Name)).value(); } @@ -104,7 +104,7 @@ namespace StreamFormat::Tester::Detail { if (result.has_value() == false) { - Link.TestLogger.Error("{C:red}{} return an error: {}", testView, result.error(), FORMAT_SV("test_name", Name)).value(); + Link.TestLogger.error("{C:red}{} return an error: {}", testView, result.error(), FORMAT_SV("test_name", Name)).value(); throw TestFailure{}; } } @@ -113,22 +113,22 @@ namespace StreamFormat::Tester::Detail { if (result.has_value() == false) { - Link.TestLogger.Error("{C:red}{} didn't return any value", testView, FORMAT_SV("test_name", Name)).value(); + Link.TestLogger.error("{C:red}{} didn't return any value", testView, FORMAT_SV("test_name", Name)).value(); throw TestFailure{}; } } } #define STREAMFORMAT_TESTINTERNAL_FUNC_DECLARE_EXEC(TestSuiteName, TestName) \ - void STREAMFORMAT_TESTINTERNAL_FUNC_EXEC_NAME(TestSuiteName, TestName)(StreamFormat::Tester::Detail::TestFunction & link); + void STREAMFORMAT_TESTINTERNAL_FUNC_EXEC_NAME(TestSuiteName, TestName)(stream::Tester::detail::TestFunction & link); #define STREAMFORMAT_TESTINTERNAL_FUNC_CREATE(TestSuiteName, TestName, ...) \ - volatile StreamFormat::Tester::Detail::TestFunction STREAMFORMAT_TESTINTERNAL_FUNC_NAME(TestSuiteName, TestName)( \ + volatile stream::Tester::detail::TestFunction STREAMFORMAT_TESTINTERNAL_FUNC_NAME(TestSuiteName, TestName)( \ #TestName, STREAMFORMAT_TESTINTERNAL_SUITE_NAME(TestSuiteName), STREAMFORMAT_TESTINTERNAL_FUNC_EXEC_NAME(TestSuiteName, TestName), STREAMFORMAT_FMT_FILE_LOCATION()) #define SFT_TEST_FUNC(TestSuiteName, TestName) \ STREAMFORMAT_TESTINTERNAL_FUNC_DECLARE_EXEC(TestSuiteName, TestName) \ STREAMFORMAT_TESTINTERNAL_FUNC_CREATE(TestSuiteName, TestName); \ - void STREAMFORMAT_TESTINTERNAL_FUNC_EXEC_NAME(TestSuiteName, TestName)(StreamFormat::Tester::Detail::TestFunction & link) + void STREAMFORMAT_TESTINTERNAL_FUNC_EXEC_NAME(TestSuiteName, TestName)(stream::Tester::detail::TestFunction & link) #define SFT_ASSERT(Test) link.TestAssert(Test, #Test, __LINE__) #define SFT_EQ(Test, Expected) link.TestEq(Test, Expected, #Test, __LINE__) diff --git a/src/StreamFormat/Tester/TestSuite/TestSuite.cpp b/src/stream/tester/test_suite/test_suite.cpp similarity index 85% rename from src/StreamFormat/Tester/TestSuite/TestSuite.cpp rename to src/stream/tester/test_suite/test_suite.cpp index c4188cb9..d14f0fac 100644 --- a/src/StreamFormat/Tester/TestSuite/TestSuite.cpp +++ b/src/stream/tester/test_suite/test_suite.cpp @@ -1,27 +1,27 @@ #include "TestSuite.h" -#include "StreamFormat/ProfilerManager.h" +#include "stream/ProfilerManager.h" -namespace StreamFormat::Tester +namespace stream::Tester { bool TestSuitesManager::ExecAllTestSuites() { - Detail::TestStatusBank status; + detail::TestStatusBank status; for (auto& [name, testSuite] : TestSuites) status.Add(testSuite->ExecAllTests()); - FLog::BasicLogger logger("TestSuite"); + flog::BasicLogger logger("TestSuite"); if (status.IsAllOk()) - logger.Info("{C:white}RESULT => {C:+black}{}", status); + logger.info("{C:white}RESULT => {C:+black}{}", status); else - logger.Error("{C:white}RESULT => {C:+black}{}", status); + logger.error("{C:white}RESULT => {C:+black}{}", status); return status.ErrorStatus(); } } -namespace StreamFormat::Tester::Detail +namespace stream::Tester::detail { TestStatusBank TestSuite::ExecAllTests() { @@ -29,7 +29,7 @@ namespace StreamFormat::Tester::Detail InitLogger(); ProfilerManager::Profiler& profiler = GetProfiler(); - Logger.Info("{C:+black}{}", "BEGIN"); + Logger.info("{C:+black}{}", "BEGIN"); ProfilerManager::DurationEvent testSuiteDuration(GetFullName(), "Profile"); testSuiteDuration.Start(); bool firstTestSuite = true; @@ -56,7 +56,7 @@ namespace StreamFormat::Tester::Detail if (testStatus != TestStatus::Ok) {} testSuiteStatus.AddTestStatus(testStatus); - Logger.Debug("{} -> {}", testStatus, name); + Logger.debug("{} -> {}", testStatus, name); profiler.AddEvent(currentTestDuration); } testsDuration.Stop(); @@ -78,9 +78,9 @@ namespace StreamFormat::Tester::Detail profiler.AddEvent(testSuiteDuration); if (testSuiteStatus.IsAllOk()) - Logger.Info("{C:+black}{}", testSuiteStatus); + Logger.info("{C:+black}{}", testSuiteStatus); else - Logger.Error("{C:+black}{}", testSuiteStatus); + Logger.error("{C:+black}{}", testSuiteStatus); if (Parent == nullptr) { @@ -95,13 +95,13 @@ namespace StreamFormat::Tester::Detail { if (TestSuitesManager::Verbose == false) { - Logger.SetSeverity(FLog::LogSeverity::Debug); - TestLogger.SetSeverity(FLog::LogSeverity::Debug); + Logger.SetSeverity(flog::LogSeverity::Debug); + TestLogger.SetSeverity(flog::LogSeverity::Debug); } else { - Logger.SetSeverity(FLog::LogSeverity::Trace); - TestLogger.SetSeverity(FLog::LogSeverity::Trace); + Logger.SetSeverity(flog::LogSeverity::Trace); + TestLogger.SetSeverity(flog::LogSeverity::Trace); } std::string timePattern = ""; diff --git a/src/StreamFormat/Tester/TestSuite/TestSuite.h b/src/stream/tester/test_suite/test_suite.h similarity index 69% rename from src/StreamFormat/Tester/TestSuite/TestSuite.h rename to src/stream/tester/test_suite/test_suite.h index 16219b56..fc9fc5ff 100644 --- a/src/StreamFormat/Tester/TestSuite/TestSuite.h +++ b/src/stream/tester/test_suite/test_suite.h @@ -1,16 +1,16 @@ #pragma once -#include "StreamFormat/FLog.h" -#include "StreamFormat/FMT.h" -#include "StreamFormat/ProfilerManager.h" +#include "stream/flog.h" +#include "stream/fmt.h" +#include "stream/ProfilerManager.h" -#include "StreamFormat/FMT/Serializers/CompilationData.h" +#include "stream/fmt/serializers/CompilationData.h" #include #include #include -namespace StreamFormat::Tester +namespace stream::Tester { class TestFailure { @@ -24,13 +24,13 @@ namespace StreamFormat::Tester }; } -namespace StreamFormat::Tester::Detail +namespace stream::Tester::detail { class TestSuite; class Test { public: - Test(std::string&& name, TestSuite& link, const FMT::Detail::FileLocation& location) + Test(std::string&& name, TestSuite& link, const fmt::detail::FileLocation& location) : Name(std::move(name)) , Link(link) , Location(location) @@ -62,7 +62,7 @@ namespace StreamFormat::Tester::Detail public: std::string Name; TestSuite& Link; - FMT::Detail::FileLocation Location; + fmt::detail::FileLocation Location; TestStatus LastStatus; }; @@ -113,7 +113,7 @@ namespace StreamFormat::Tester::Detail class TestSuite; } -namespace StreamFormat::Tester +namespace stream::Tester { struct PerformanceTestData { @@ -130,7 +130,7 @@ namespace StreamFormat::Tester { public: static bool ExecAllTestSuites(); - static inline std::unordered_map TestSuites; + static inline std::unordered_map TestSuites; public: static inline bool Verbose = false; @@ -139,7 +139,7 @@ namespace StreamFormat::Tester static inline ConcurenceSpecificationData ConcurenceSpecification = ConcurenceSpecificationData{}; }; } -namespace StreamFormat::Tester::Detail +namespace stream::Tester::detail { struct TestSuiteData { @@ -171,8 +171,8 @@ namespace StreamFormat::Tester::Detail std::unordered_map TestSuitesLinked; TestSuiteData Extra; - FLog::BasicLogger Logger; - FLog::BasicLogger TestLogger; + flog::BasicLogger Logger; + flog::BasicLogger TestLogger; ProfilerManager::Profiler* Profiler; TestSuite* Parent; @@ -190,39 +190,39 @@ namespace StreamFormat::Tester::Detail }; } -namespace StreamFormat::FMT +namespace stream::fmt { template - struct FormatterType + struct FormatterType { - [[nodiscard]] static std::expected Format(const StreamFormat::Tester::Detail::TestSuite& t, FormatterExecutor& executor) - { return executor.BufferOut.FastWriteString(t.Name); } + [[nodiscard]] static std::expected format(const stream::Tester::detail::TestSuite& t, FormatterExecutor& executor) + { return executor.buffer_out.FastWriteString(t.Name); } }; template - struct FormatterType + struct FormatterType { - [[nodiscard]] static std::expected Format(const StreamFormat::Tester::Detail::Test& t, FormatterExecutor& executor) + [[nodiscard]] static std::expected format(const stream::Tester::detail::Test& t, FormatterExecutor& executor) { - SF_TRY(Detail::BufferWriteManip(executor.BufferOut).FastWriteString(t.Link.Name)); - SF_TRY(Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("::")); - SF_TRY(Detail::BufferWriteManip(executor.BufferOut).FastWriteString(t.Name)); + SF_TRY(detail::BufferWriteManip(executor.buffer_out).FastWriteString(t.Link.Name)); + SF_TRY(detail::BufferWriteManip(executor.buffer_out).FastWriteStringLitteral("::")); + SF_TRY(detail::BufferWriteManip(executor.buffer_out).FastWriteString(t.Name)); return {}; } }; template - struct FormatterType + struct FormatterType { - [[nodiscard]] static std::expected Format(const StreamFormat::Tester::TestStatus& status, FormatterExecutor& executor) + [[nodiscard]] static std::expected format(const stream::Tester::TestStatus& status, FormatterExecutor& executor) { switch (status) { - case StreamFormat::Tester::TestStatus::Ok: + case stream::Tester::TestStatus::Ok: return executor.Run("[ {C:green}OK{C} ]"); - case StreamFormat::Tester::TestStatus::Fail: + case stream::Tester::TestStatus::Fail: return executor.Run("[ {C:red}FAIL{C} ]"); - case StreamFormat::Tester::TestStatus::Crash: + case stream::Tester::TestStatus::Crash: return executor.Run("[{C:magenta}Crash{C} ]"); } return {}; @@ -230,26 +230,26 @@ namespace StreamFormat::FMT }; template - struct FormatterType + struct FormatterType { - [[nodiscard]] static std::expected Format(const StreamFormat::Tester::Detail::TestStatusBank& statusBank, FormatterExecutor& executor) + [[nodiscard]] static std::expected format(const stream::Tester::detail::TestStatusBank& statusBank, FormatterExecutor& executor) { - SF_TRY(Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral("TestsDone ")); + SF_TRY(detail::BufferWriteManip(executor.buffer_out).FastWriteStringLitteral("TestsDone ")); SF_TRY(executor.Run("{:C:white}", statusBank.TestsDone)); - SF_TRY(Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral(" | TestsOK ")); + SF_TRY(detail::BufferWriteManip(executor.buffer_out).FastWriteStringLitteral(" | TestsOK ")); if (statusBank.TestsOk == statusBank.TestsDone) { SF_TRY(executor.Run("{:C:green}", statusBank.TestsOk)); } else { SF_TRY(executor.Run("{:C:yellow}", statusBank.TestsOk)); } - SF_TRY(Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral(" | TestsFAIL ")); + SF_TRY(detail::BufferWriteManip(executor.buffer_out).FastWriteStringLitteral(" | TestsFAIL ")); if (statusBank.TestsFail == 0) { SF_TRY(executor.Run("{:C:green}", statusBank.TestsFail)); } else { SF_TRY(executor.Run("{:C:red}", statusBank.TestsFail)); } - SF_TRY(Detail::BufferWriteManip(executor.BufferOut).FastWriteStringLitteral(" | TestCrash ")); + SF_TRY(detail::BufferWriteManip(executor.buffer_out).FastWriteStringLitteral(" | TestCrash ")); if (statusBank.TestsCrash == 0) { SF_TRY(executor.Run("{:C:green}", statusBank.TestsCrash)); } else @@ -265,17 +265,17 @@ namespace StreamFormat::FMT #define STREAMFORMAT_TESTINTERNAL_FUNC_NAME(TestSuiteName, TestName) TestSuite_##TestSuiteName##TestName #define STREAMFORMAT_TESTINTERNAL_FUNC_EXEC_NAME(TestSuiteName, TestName) TestSuite_##TestSuiteName##TestName##_ExecMethod #define STREAMFORMAT_TESTINTERNAL_SUITE_EXTRA(...) \ - StreamFormat::Tester::Detail::TestSuiteData \ + stream::Tester::detail::TestSuiteData \ { \ __VA_ARGS__ \ } //-------------------- TestSuite --------------------// #define SFT_TEST_SUITE(TestSuiteName, ...) \ - StreamFormat::Tester::Detail::TestSuite STREAMFORMAT_TESTINTERNAL_SUITE_NAME(TestSuiteName)(#TestSuiteName, STREAMFORMAT_TESTINTERNAL_SUITE_EXTRA(__VA_ARGS__)) + stream::Tester::detail::TestSuite STREAMFORMAT_TESTINTERNAL_SUITE_NAME(TestSuiteName)(#TestSuiteName, STREAMFORMAT_TESTINTERNAL_SUITE_EXTRA(__VA_ARGS__)) #define SFT_TEST_GROUP(TestSuiteName, GroupName, ...) \ - StreamFormat::Tester::Detail::TestSuite STREAMFORMAT_TESTINTERNAL_SUITE_NAME(GroupName)(#GroupName, STREAMFORMAT_TESTINTERNAL_SUITE_EXTRA(__VA_ARGS__), \ + stream::Tester::detail::TestSuite STREAMFORMAT_TESTINTERNAL_SUITE_NAME(GroupName)(#GroupName, STREAMFORMAT_TESTINTERNAL_SUITE_EXTRA(__VA_ARGS__), \ &STREAMFORMAT_TESTINTERNAL_SUITE_NAME(TestSuiteName)) -#define SFT_TEST_SUITE_DECLARATION(TestSuiteName, ...) StreamFormat::Tester::Detail::TestSuite STREAMFORMAT_TESTINTERNAL_SUITE_NAME(TestSuiteName) -#define SFT_TEST_GROUP_DECLARATION(TestSuiteName, GroupName, ...) StreamFormat::Tester::Detail::TestSuite STREAMFORMAT_TESTINTERNAL_SUITE_NAME(GroupName) +#define SFT_TEST_SUITE_DECLARATION(TestSuiteName, ...) stream::Tester::detail::TestSuite STREAMFORMAT_TESTINTERNAL_SUITE_NAME(TestSuiteName) +#define SFT_TEST_GROUP_DECLARATION(TestSuiteName, GroupName, ...) stream::Tester::detail::TestSuite STREAMFORMAT_TESTINTERNAL_SUITE_NAME(GroupName) diff --git a/src/StreamFormat/Tester/TestsMacros.h b/src/stream/tester/tests_macros.h similarity index 78% rename from src/StreamFormat/Tester/TestsMacros.h rename to src/stream/tester/tests_macros.h index 5c1daa44..ca7f2877 100644 --- a/src/StreamFormat/Tester/TestsMacros.h +++ b/src/stream/tester/tests_macros.h @@ -1,24 +1,24 @@ #pragma once -#include "StreamFormat/FLog.h" +#include "stream/flog.h" -#define STREAMFORMAT_TEST_TRACE(...) StreamFormat::Test::TestCore::GetLogger().Trace(__VA_ARGS__) -#define STREAMFORMAT_TEST_INFO(...) StreamFormat::Test::TestCore::GetLogger().Info(__VA_ARGS__) -#define STREAMFORMAT_TEST_WARN(...) StreamFormat::Test::TestCore::GetLogger().Warn(__VA_ARGS__) -#define STREAMFORMAT_TEST_ERROR(...) StreamFormat::Test::TestCore::GetLogger().Error(__VA_ARGS__) -#define STREAMFORMAT_TEST_FATAL(...) StreamFormat::Test::TestCore::GetLogger().Fatal(__VA_ARGS__) -#define STREAMFORMAT_TEST_OK(...) StreamFormat::Test::TestCore::GetLogger().Ok(__VA_ARGS__) -#define STREAMFORMAT_TEST_FAIL(...) StreamFormat::Test::TestCore::GetLogger().Fail(__VA_ARGS__) -#define STREAMFORMAT_TEST_BASIC(...) StreamFormat::Test::TestCore::GetLogger().Basic(__VA_ARGS__) +#define STREAMFORMAT_TEST_TRACE(...) stream::Test::TestCore::GetLogger().trace(__VA_ARGS__) +#define STREAMFORMAT_TEST_INFO(...) stream::Test::TestCore::GetLogger().info(__VA_ARGS__) +#define STREAMFORMAT_TEST_WARN(...) stream::Test::TestCore::GetLogger().warn(__VA_ARGS__) +#define STREAMFORMAT_TEST_ERROR(...) stream::Test::TestCore::GetLogger().error(__VA_ARGS__) +#define STREAMFORMAT_TEST_FATAL(...) stream::Test::TestCore::GetLogger().fatal(__VA_ARGS__) +#define STREAMFORMAT_TEST_OK(...) stream::Test::TestCore::GetLogger().Ok(__VA_ARGS__) +#define STREAMFORMAT_TEST_FAIL(...) stream::Test::TestCore::GetLogger().Fail(__VA_ARGS__) +#define STREAMFORMAT_TEST_BASIC(...) stream::Test::TestCore::GetLogger().Basic(__VA_ARGS__) -namespace StreamFormat::Test +namespace stream::Test { class TestCore { public: - static FLog::BasicLogger& GetLogger() + static flog::BasicLogger& GetLogger() { - static FLog::BasicLogger instance("StreamFormat-Test", "{name} {color} -> {data}"); + static flog::BasicLogger instance("stream-Test", "{name} {color} -> {data}"); return instance; } }; diff --git a/tests/fmt/base_fmt_tests.h b/tests/fmt/base_fmt_tests.h new file mode 100644 index 00000000..3c1090f3 --- /dev/null +++ b/tests/fmt/base_fmt_tests.h @@ -0,0 +1,5 @@ +#pragma once + +#include "stream/Tester/TestSuite/AllTestSuite.h" + +inline SFT_TEST_SUITE(FMT); diff --git a/Tests/FMT/ComplexPattern.cpp b/tests/fmt/complex_pattern.cpp similarity index 50% rename from Tests/FMT/ComplexPattern.cpp rename to tests/fmt/complex_pattern.cpp index 84ccfca8..932a006b 100644 --- a/Tests/FMT/ComplexPattern.cpp +++ b/tests/fmt/complex_pattern.cpp @@ -1,11 +1,11 @@ -#include "StreamFormat/FMT.h" -#include "StreamFormat/Tester/TestSuite/AllTestSuite.h" +#include "stream/fmt.h" +#include "stream/Tester/TestSuite/AllTestSuite.h" #include "BaseFMTTests.h" SFT_TEST_GROUP(FMT, COMPLEX_PATTERN); -#define TEST_FMT(fmt_test, expected, ...) SFT_EQ(StreamFormat::FMT::FormatString(fmt_test, __VA_ARGS__).value(), std::string(expected)) +#define TEST_FMT(fmt_test, expected, ...) SFT_EQ(stream::fmt::FormatString(fmt_test, __VA_ARGS__).value(), std::string(expected)) SFT_TEST_FUNC(COMPLEX_PATTERN, UNESCAPED_ESCAPE_PATTERN) { diff --git a/Tests/FMT/Globber.cpp b/tests/fmt/globber.cpp similarity index 64% rename from Tests/FMT/Globber.cpp rename to tests/fmt/globber.cpp index ab277ecd..cf0a6bf6 100644 --- a/Tests/FMT/Globber.cpp +++ b/tests/fmt/globber.cpp @@ -1,18 +1,18 @@ #include "BaseFMTTests.h" -#include "StreamFormat/FMT/Context/ParserExecutor/UtilityFunctions.h" +#include "stream/fmt/context/ParserExecutor/utility_functions.h" -#include "StreamFormat/FMT/Buffer/Utils/BufferGlobberManip.h" +#include "stream/fmt/buffer/utils/BufferGlobberManip.h" SFT_TEST_GROUP(FMT, GLOBBER); #define TEST_GLOBBER(data, glob) \ { \ - StreamFormat::FMT::Detail::BufferInfoView p_buffer(data); \ - StreamFormat::FMT::Detail::BufferInfoView p_glob(glob); \ - StreamFormat::FMT::Detail::Globber::BufferInExecGlob(p_buffer, \ + stream::fmt::detail::BufferInfoView p_buffer(data); \ + stream::fmt::detail::BufferInfoView p_glob(glob); \ + stream::fmt::detail::Globber::BufferInExecGlob(p_buffer, \ p_glob).value(); \ SFT_ASSERT( \ - StreamFormat::FMT::Detail::BufferAccess(p_buffer).IsEndOfString()); \ + stream::fmt::detail::BufferAccess(p_buffer).IsEndOfString()); \ } SFT_TEST_FUNC(GLOBBER, BASIC_WILDCARD){ @@ -25,43 +25,43 @@ SFT_TEST_FUNC(GLOBBER, BASIC_WILDCARD){ SFT_TEST_GROUP(FMT, PARSE_GLOBBER); SFT_TEST_FUNC(PARSE_GLOBBER, PG_BASIC_WILDCARD) { int k = 0; - StreamFormat::FMT::Parse("|123|", "|{}|", k).value(); + stream::fmt::parse("|123|", "|{}|", k).value(); SFT_EQ(k, 123); { // char test[5]; - // StreamFormat::FMT::Parse("|test|", "|{}|", test).value(); + // stream::fmt::parse("|test|", "|{}|", test).value(); // SFT_EQ(std::string(test), std::string("test")); } { // char test[4]; - // StreamFormat::FMT::Parse("|test|", "|{:no-zero-end}|", test).value(); + // stream::fmt::parse("|test|", "|{:no-zero-end}|", test).value(); // SFT_EQ(std::string(test, 4), std::string("test")); } { // char test[4]; - // StreamFormat::FMT::Parse("|test|", "|{}t|", test).value(); + // stream::fmt::parse("|test|", "|{}t|", test).value(); // SFT_EQ(std::string(test), std::string("tes")); } { // char test[11]; - // StreamFormat::FMT::Parse("|test123456|", "|{}|", test).value(); + // stream::fmt::parse("|test123456|", "|{}|", test).value(); // SFT_EQ(std::string(test), std::string("test123456")); } { // char test[11]; - // StreamFormat::FMT::Parse("|test123456|", "|{:glob='*1'}23456|", test).value(); + // stream::fmt::parse("|test123456|", "|{:glob='*1'}23456|", test).value(); // SFT_EQ(std::string(test), std::string("test1")); } { // char test[11]; // just glob = '????' but compiler are anrgy about trigraph on '??' - // StreamFormat::FMT::Parse("|test123456|", + // stream::fmt::parse("|test123456|", // "|{:glob='?" // "?" // "?" diff --git a/Tests/FMT/Index.cpp b/tests/fmt/index.cpp similarity index 53% rename from Tests/FMT/Index.cpp rename to tests/fmt/index.cpp index 703df7fd..26fcb531 100644 --- a/Tests/FMT/Index.cpp +++ b/tests/fmt/index.cpp @@ -1,5 +1,5 @@ -#include "StreamFormat/FMT.h" -#include "StreamFormat/Tester/TestSuite/AllTestSuite.h" +#include "stream/fmt.h" +#include "stream/Tester/TestSuite/AllTestSuite.h" #include "BaseFMTTests.h" diff --git a/Tests/FMT/Limits.cpp b/tests/fmt/limits.cpp similarity index 69% rename from Tests/FMT/Limits.cpp rename to tests/fmt/limits.cpp index eaf1643c..3d67d872 100644 --- a/Tests/FMT/Limits.cpp +++ b/tests/fmt/limits.cpp @@ -1,5 +1,5 @@ -#include "StreamFormat/FMT.h" -#include "StreamFormat/Tester/TestSuite/AllTestSuite.h" +#include "stream/fmt.h" +#include "stream/Tester/TestSuite/AllTestSuite.h" #include "BaseFMTTests.h" @@ -8,7 +8,7 @@ SFT_TEST_GROUP(FMT, LIMITS); #define SFT_TEST_FUNC_LowBufferSize(k) \ SFT_TEST_FUNC(LIMITS, LowBufferSize##k) { \ char buffer[k] = {0}; \ - auto res = StreamFormat::FMT::FormatInChar(buffer, "0123456789"); \ + auto res = stream::fmt::FormatInChar(buffer, "0123456789"); \ SFT_EXPECTED_VALUE(res); \ for (int i = 0; i < k; ++i) \ SFT_EQ(buffer[i] - '0', i); \ @@ -27,7 +27,7 @@ SFT_TEST_FUNC_LowBufferSize(1); SFT_TEST_FUNC(LIMITS, PlainLowBufferSize10) { char buffer[10] = {0}; - auto res = StreamFormat::FMT::FormatInChar(buffer, "0123456789"); + auto res = stream::fmt::FormatInChar(buffer, "0123456789"); SFT_EXPECTED_VALUE(res); for (int i = 0; i < 10; ++i) SFT_EQ(buffer[i] - '0', i); @@ -35,7 +35,7 @@ SFT_TEST_FUNC(LIMITS, PlainLowBufferSize10) { SFT_TEST_FUNC(LIMITS, PlainLowBufferSize1) { char buffer[1] = {0}; - auto res = StreamFormat::FMT::FormatInChar(buffer, "0"); + auto res = stream::fmt::FormatInChar(buffer, "0"); SFT_EXPECTED_VALUE(res); for (int i = 0; i < 1; ++i) SFT_EQ(buffer[i] - '0', i); @@ -46,9 +46,9 @@ SFT_TEST_FUNC(LIMITS, PlainLowBufferSize1) { char buffer[k] = {0}; \ const char fmtBuffer[] = { \ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; \ - StreamFormat::FMT::Detail::BufferInfoView format(fmtBuffer, k); \ - StreamFormat::FMT::Detail::GivenBufferOutManager manager(buffer, k); \ - auto res = StreamFormat::FMT::Detail::FormatInManager(manager, false, format); \ + stream::fmt::detail::BufferInfoView format(fmtBuffer, k); \ + stream::fmt::detail::GivenBufferOutManager manager(buffer, k); \ + auto res = stream::fmt::detail::FormatInManager(manager, false, format); \ SFT_EXPECTED_VALUE(res); \ for (int i = 0; i < k; ++i) \ SFT_EQ(buffer[i] - '0', i); \ @@ -68,9 +68,9 @@ SFT_TEST_FUNC_LowBufferSizeArray(1); SFT_TEST_FUNC(LIMITS, PlainLowBufferSizeArray10) { char buffer[10] = {0}; const char fmtBuffer[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; - StreamFormat::FMT::Detail::BufferInfoView fmt(fmtBuffer, 10); - StreamFormat::FMT::Detail::GivenBufferOutManager manager(buffer, 10); - auto res = StreamFormat::FMT::Detail::FormatInManager(manager, false, fmt); + stream::fmt::detail::BufferInfoView fmt(fmtBuffer, 10); + stream::fmt::detail::GivenBufferOutManager manager(buffer, 10); + auto res = stream::fmt::detail::FormatInManager(manager, false, fmt); SFT_EXPECTED_VALUE(res); for (int i = 0; i < 10; ++i) SFT_EQ(buffer[i] - '0', i); @@ -79,9 +79,9 @@ SFT_TEST_FUNC(LIMITS, PlainLowBufferSizeArray10) { SFT_TEST_FUNC(LIMITS, PlainLowBufferSizeArray1) { char buffer[1] = {0}; const char fmtBuffer[] = {'0'}; - StreamFormat::FMT::Detail::BufferInfoView fmt(fmtBuffer, 1); - StreamFormat::FMT::Detail::GivenBufferOutManager manager(buffer, 1); - auto res = StreamFormat::FMT::Detail::FormatInManager(manager, false, fmt); + stream::fmt::detail::BufferInfoView fmt(fmtBuffer, 1); + stream::fmt::detail::GivenBufferOutManager manager(buffer, 1); + auto res = stream::fmt::detail::FormatInManager(manager, false, fmt); SFT_EXPECTED_VALUE(res); for (int i = 0; i < 1; ++i) SFT_EQ(buffer[i] - '0', i); @@ -92,9 +92,9 @@ SFT_TEST_FUNC(LIMITS, LowBufferSizeArray10FMT30) { const char fmtBuffer[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; - StreamFormat::FMT::Detail::BufferInfoView fmt(fmtBuffer, 30); - StreamFormat::FMT::Detail::GivenBufferOutManager manager(buffer, 10); - auto res = StreamFormat::FMT::Detail::FormatInManager(manager, false, fmt); + stream::fmt::detail::BufferInfoView fmt(fmtBuffer, 30); + stream::fmt::detail::GivenBufferOutManager manager(buffer, 10); + auto res = stream::fmt::detail::FormatInManager(manager, false, fmt); SFT_EXPECTED_VALUE(res); for (int k = 0; k < 10; ++k) SFT_EQ(buffer[k] - '0', k); @@ -102,10 +102,10 @@ SFT_TEST_FUNC(LIMITS, LowBufferSizeArray10FMT30) { SFT_TEST_FUNC(LIMITS, LowBufferSizeArray5Number9) { char buffer[10] = {0}; - StreamFormat::FMT::Detail::BufferInfoView fmt("{}"); - StreamFormat::FMT::Detail::GivenBufferOutManager manager(buffer, 10); + stream::fmt::detail::BufferInfoView fmt("{}"); + stream::fmt::detail::GivenBufferOutManager manager(buffer, 10); std::uint64_t i = 9'876'543'210; - auto res = StreamFormat::FMT::Detail::FormatInManager(manager, false, fmt, i); + auto res = stream::fmt::detail::FormatInManager(manager, false, fmt, i); SFT_EXPECTED_VALUE(res); for (int k = 0; k < 10; ++k) SFT_EQ(buffer[k] - '0', 9 - k); diff --git a/Tests/FMT/Shift.cpp b/tests/fmt/shift.cpp similarity index 98% rename from Tests/FMT/Shift.cpp rename to tests/fmt/shift.cpp index d30079f3..8dc55675 100644 --- a/Tests/FMT/Shift.cpp +++ b/tests/fmt/shift.cpp @@ -1,11 +1,11 @@ -#include "StreamFormat/FMT.h" -#include "StreamFormat/Tester/TestSuite/AllTestSuite.h" +#include "stream/fmt.h" +#include "stream/Tester/TestSuite/AllTestSuite.h" #include "BaseFMTTests.h" SFT_TEST_GROUP(FMT, SHIFT); -#define TEST_FMT(fmt_test, expected, ...) SFT_EQ(StreamFormat::FMT::FormatString(fmt_test, __VA_ARGS__), expected) +#define TEST_FMT(fmt_test, expected, ...) SFT_EQ(stream::fmt::FormatString(fmt_test, __VA_ARGS__), expected) SFT_TEST_GROUP(SHIFT, NUMBER_SHIFT); SFT_TEST_GROUP(NUMBER_SHIFT, ONE_DIGIT); diff --git a/Tests/FMT/Specifier.cpp b/tests/fmt/specifier.cpp similarity index 88% rename from Tests/FMT/Specifier.cpp rename to tests/fmt/specifier.cpp index 2dfb5b39..042b062d 100644 --- a/Tests/FMT/Specifier.cpp +++ b/tests/fmt/specifier.cpp @@ -1,11 +1,11 @@ -#include "StreamFormat/FMT.h" -#include "StreamFormat/Tester/TestSuite/AllTestSuite.h" +#include "stream/fmt.h" +#include "stream/Tester/TestSuite/AllTestSuite.h" #include "BaseFMTTests.h" SFT_TEST_GROUP(FMT, SPECIFIER); -#define TEST_FMT_ARRAY_SPECIFIERS(fmt_test, test_data, expected) SFT_EQ(StreamFormat::FMT::FormatString(fmt_test, test_data), expected) +#define TEST_FMT_ARRAY_SPECIFIERS(fmt_test, test_data, expected) SFT_EQ(stream::fmt::FormatString(fmt_test, test_data), expected) SFT_TEST_FUNC(SPECIFIER, BEGIN_END) { diff --git a/Tests/FMT/TextProperties.cpp b/tests/fmt/text_properties.cpp similarity index 88% rename from Tests/FMT/TextProperties.cpp rename to tests/fmt/text_properties.cpp index 0a881b43..6befe4ab 100644 --- a/Tests/FMT/TextProperties.cpp +++ b/tests/fmt/text_properties.cpp @@ -1,11 +1,11 @@ -#include "StreamFormat/FMT.h" -#include "StreamFormat/Tester/TestSuite/AllTestSuite.h" +#include "stream/fmt.h" +#include "stream/Tester/TestSuite/AllTestSuite.h" #include "BaseFMTTests.h" SFT_TEST_GROUP(FMT, TEXT_PROPERTIES); -#define TEST_FMT(fmt_test, expected) SFT_EQ(Escaper(StreamFormat::FMT::FormatString(fmt_test, 0).value()), Escaper(expected)) +#define TEST_FMT(fmt_test, expected) SFT_EQ(Escaper(stream::fmt::FormatString(fmt_test, 0).value()), Escaper(expected)) static std::string Escaper(const std::string& str) { @@ -83,7 +83,7 @@ class TEST_FMT_ContextOut }; STREAMFORMAT_AUTO_FORMATTER_T(TEST_FMT_ContextOut, "{C:red} TEST_FMT_ContextOut {} ", 0); -#define TEST_FMT_CONTEXT(fmt_test, expected) SFT_EQ(Escaper(StreamFormat::FMT::FormatString(fmt_test, TEST_FMT_ContextOut{}).value()), Escaper(expected)) +#define TEST_FMT_CONTEXT(fmt_test, expected) SFT_EQ(Escaper(stream::fmt::FormatString(fmt_test, TEST_FMT_ContextOut{}).value()), Escaper(expected)) SFT_TEST_FUNC(TEXT_PROPERTIES, ContextOut) { @@ -91,7 +91,7 @@ SFT_TEST_FUNC(TEXT_PROPERTIES, ContextOut) TEST_FMT_CONTEXT("{} 123 ", "\033[31m TEST_FMT_ContextOut 0 \033[39m 123 "); - // TODO : check before doing a Detail::TextPropertiesExecution, should only have one \033[31m + // TODO : check before doing a detail::TextPropertiesExecution, should only have one \033[31m TEST_FMT_CONTEXT("{C:red}{} 123 ", "\033[31m TEST_FMT_ContextOut 0 123 \033[39m"); TEST_FMT_CONTEXT("{C:+red}{} 123 ", "\033[91m\033[31m TEST_FMT_ContextOut 0 \033[91m 123 \033[39m"); diff --git a/tests/tests.cpp b/tests/tests.cpp new file mode 100644 index 00000000..55308fe0 --- /dev/null +++ b/tests/tests.cpp @@ -0,0 +1,9 @@ + +#include "stream/Tester/TestSuite/AllTestSuite.h" +#include "stream/flog/DefaultLogger.h" + +int main() +{ + stream::Tester::TestSuitesManager::Verbose = false; + return stream::Tester::TestSuitesManager::ExecAllTestSuites(); +} From cfbf8cb42aaf9de047c09a6b0ba4215e87d2aa6a Mon Sep 17 00:00:00 2001 From: Sacha Bellier Date: Sun, 23 Mar 2025 15:29:19 +0100 Subject: [PATCH 17/42] wip: rename to lowercase --- BUILD.bazel | 21 -- examples/hello/main.cpp | 7 +- src/stream/default_logger.h | 20 +- src/stream/flog.h | 4 +- src/stream/flog/backends/basic_logger.h | 52 +-- src/stream/flog/backends/logger_multi_sink.h | 26 +- .../flog/backends/logger_multi_sink_fast.h | 52 +-- .../flog/backends/logger_multi_sink_safe.h | 62 ++-- src/stream/flog/detail/detail.h | 30 +- src/stream/flog/frontends/xlogger.cpp | 2 +- src/stream/flog/frontends/xlogger.h | 32 +- src/stream/flog/sinks/file_sink.h | 2 +- src/stream/flog/sinks/logger_sink.h | 30 +- src/stream/fmt/buf/fmt_manip_io.h | 118 ++++++ src/stream/fmt/buf/fmt_read_manip.h | 238 +++++++++++++ src/stream/fmt/buf/fmt_write_manip.h | 275 ++++++++++++++ src/stream/fmt/buf/manip.h | 101 ++++++ src/stream/fmt/buf/manip_io.h | 83 +++++ .../buffer_read_manip.h => buf/read_manip.h} | 63 ++-- src/stream/fmt/buf/stream.h | 83 +++++ src/stream/fmt/buf/streamio.h | 56 +++ .../streamio_manager/basic_streamio_manager.h | 52 +++ .../dynamic_streamio_manager.h | 128 +++++++ .../streamio_manager/given_streamio_manager.h | 42 +++ .../static_streamio_manager.h | 29 ++ src/stream/fmt/buf/test_manip.h | 180 ++++++++++ .../fmt/buf/utils/buffer_globber_manip.h | 129 +++++++ src/stream/fmt/buf/utils/buffer_shift_manip.h | 102 ++++++ src/stream/fmt/buf/utils/buffer_utils.h | 130 +++++++ src/stream/fmt/buf/write_manip.h | 172 +++++++++ src/stream/fmt/buffer/buffer_info.h | 85 ----- src/stream/fmt/buffer/buffer_manip.h | 105 ------ .../basic_buffer_out_manager.h | 55 --- .../dynamic_buffer_out_manager.h | 128 ------- .../given_buffer_out_manager.h | 42 --- .../static_buffer_out_manager.h | 29 -- src/stream/fmt/buffer/buffer_out_manip.h | 139 -------- src/stream/fmt/buffer/buffer_test_manip.h | 185 ---------- src/stream/fmt/buffer/buffer_write_manip.h | 170 --------- src/stream/fmt/buffer/fmt_buffer_out_manip.h | 119 ------- src/stream/fmt/buffer/fmt_buffer_read_manip.h | 238 ------------- .../fmt/buffer/fmt_buffer_write_manip.h | 272 -------------- .../fmt/buffer/utils/buffer_globber_manip.h | 129 ------- .../fmt/buffer/utils/buffer_shift_manip.h | 102 ------ src/stream/fmt/buffer/utils/buffer_utils.h | 131 ------- .../basic_context/basic_args_interface.h | 44 +-- .../fmt/context/basic_context/basic_context.h | 124 +++---- .../basic_context/basic_context_parse_impl.h | 336 +++++++++--------- .../basic_context/text_properties_executor.h | 4 +- .../basic_context/text_properties_manager.cpp | 134 +++---- .../basic_context/text_properties_manager.h | 222 ++++++------ .../text_properties_manager_impl.h | 220 ++++++------ .../basic_formatter_executor.h | 74 ++-- .../formatter_executor/format_basics_impl.h | 84 ++--- .../format_text_properties_impl.h | 22 +- .../formatter_executor/formatter_args.h | 62 ++-- .../formatter_text_properties_executor.h | 10 +- .../formatter_text_properties_executor_ansi.h | 112 +++--- .../formatter_executor/formatter_type.h | 10 +- .../context/formatter_executor/index_args.h | 10 +- .../context/formatter_executor/named_args.h | 30 +- .../formatter_executor/std_enumerable.h | 42 +-- .../formatter_executor/utility_functions.h | 248 ++++++------- .../parser_executor/basic_parser_executor.h | 70 ++-- .../parser_executor/parse_basics_impl.h | 36 +- .../parse_text_properties_impl.h | 24 +- .../fmt/context/parser_executor/parser_args.h | 62 ++-- .../parser_text_properties_executor.h | 12 +- .../parser_text_properties_executor_ansi.h | 56 +-- .../fmt/context/parser_executor/parser_type.h | 6 +- .../parser_executor/utility_functions.h | 22 +- .../fmt/context/utils/context_functions.h | 16 +- src/stream/fmt/detail/convert_traits.h | 26 +- src/stream/fmt/detail/fmt_result.h | 8 +- src/stream/fmt/detail/indent_handlers.h | 14 +- src/stream/fmt/detail/prelude.h | 2 +- src/stream/fmt/detail/specifiers.h | 204 +++++------ src/stream/fmt/detail/types_traits.h | 6 +- src/stream/fmt/serializers/compilation_data.h | 52 +-- src/stream/fmt/serializers/format_chrono.h | 106 +++--- src/stream/fmt/serializers/format_stdlib.h | 10 +- src/stream/fmt/serializers/parse_chrono.h | 2 +- src/stream/fmt/serializers/parse_stdlib.h | 2 +- .../fmt/serializers/std_container/FMT_tuple.h | 26 +- .../text_properties/text_properties_color.h | 238 ++++++------- .../text_properties/text_properties_front.h | 26 +- .../text_properties/text_properties_style.h | 124 +++---- src/stream/json.h | 8 +- src/stream/json/detail.h | 4 +- src/stream/json/json_factory.h | 38 +- src/stream/json/json_formatter.h | 69 ++-- src/stream/json/json_formatter_impl.h | 6 +- src/stream/json/json_objects.cpp | 6 +- src/stream/json/json_objects.h | 34 +- src/stream/json/json_parser.cpp | 32 +- src/stream/json/json_parser.h | 38 +- src/stream/json/json_serializer.h | 152 ++++---- .../json/serializers/base_serializers.h | 10 +- .../serializers/json_objects_serializer.h | 26 +- src/stream/json/serializers/serializers.h | 6 +- .../std_serializers/basic_std_serializers.h | 4 +- .../serializers/std_serializers/json_map.h | 4 +- .../std_serializers/json_unordered_map.h | 6 +- .../serializers/std_serializers/json_vector.h | 6 +- src/stream/profiler.h | 4 +- src/stream/profiler/all_events.h | 8 +- src/stream/profiler/detail.h | 4 +- src/stream/profiler/event.h | 52 +-- src/stream/profiler/event_data.h | 14 +- src/stream/profiler/get_pid.cpp | 2 +- src/stream/profiler/profiler.h | 38 +- .../profiler/profiler_event_creator.cpp | 60 ++-- src/stream/profiler/profiler_event_creator.h | 48 +-- src/stream/profiler/profiler_factory.cpp | 16 +- src/stream/profiler/profiler_factory.h | 4 +- .../profiler/profiler_json_serializers.h | 62 ++-- src/stream/profiler/profiler_macros.h | 8 +- src/stream/tester/copy_move_check.h | 46 +-- src/stream/tester/test_suite/all_test_suite.h | 4 +- src/stream/tester/test_suite/basic_test.h | 28 +- src/stream/tester/test_suite/test_suite.cpp | 147 ++++---- src/stream/tester/test_suite/test_suite.h | 182 +++++----- src/stream/tester/tests_macros.h | 18 +- tests/BUILD.bazel | 24 ++ tests/fmt/base_fmt_tests.h | 2 +- tests/fmt/complex_pattern.cpp | 6 +- tests/fmt/globber.cpp | 14 +- tests/fmt/index.cpp | 4 +- tests/fmt/limits.cpp | 40 +-- tests/fmt/shift.cpp | 6 +- tests/fmt/specifier.cpp | 6 +- tests/fmt/text_properties.cpp | 10 +- tests/tests.cpp | 8 +- 133 files changed, 4248 insertions(+), 4254 deletions(-) create mode 100644 src/stream/fmt/buf/fmt_manip_io.h create mode 100644 src/stream/fmt/buf/fmt_read_manip.h create mode 100644 src/stream/fmt/buf/fmt_write_manip.h create mode 100644 src/stream/fmt/buf/manip.h create mode 100644 src/stream/fmt/buf/manip_io.h rename src/stream/fmt/{buffer/buffer_read_manip.h => buf/read_manip.h} (51%) create mode 100644 src/stream/fmt/buf/stream.h create mode 100644 src/stream/fmt/buf/streamio.h create mode 100644 src/stream/fmt/buf/streamio_manager/basic_streamio_manager.h create mode 100644 src/stream/fmt/buf/streamio_manager/dynamic_streamio_manager.h create mode 100644 src/stream/fmt/buf/streamio_manager/given_streamio_manager.h create mode 100644 src/stream/fmt/buf/streamio_manager/static_streamio_manager.h create mode 100644 src/stream/fmt/buf/test_manip.h create mode 100644 src/stream/fmt/buf/utils/buffer_globber_manip.h create mode 100644 src/stream/fmt/buf/utils/buffer_shift_manip.h create mode 100644 src/stream/fmt/buf/utils/buffer_utils.h create mode 100644 src/stream/fmt/buf/write_manip.h delete mode 100644 src/stream/fmt/buffer/buffer_info.h delete mode 100644 src/stream/fmt/buffer/buffer_manip.h delete mode 100644 src/stream/fmt/buffer/buffer_out_manager/basic_buffer_out_manager.h delete mode 100644 src/stream/fmt/buffer/buffer_out_manager/dynamic_buffer_out_manager.h delete mode 100644 src/stream/fmt/buffer/buffer_out_manager/given_buffer_out_manager.h delete mode 100644 src/stream/fmt/buffer/buffer_out_manager/static_buffer_out_manager.h delete mode 100644 src/stream/fmt/buffer/buffer_out_manip.h delete mode 100644 src/stream/fmt/buffer/buffer_test_manip.h delete mode 100644 src/stream/fmt/buffer/buffer_write_manip.h delete mode 100644 src/stream/fmt/buffer/fmt_buffer_out_manip.h delete mode 100644 src/stream/fmt/buffer/fmt_buffer_read_manip.h delete mode 100644 src/stream/fmt/buffer/fmt_buffer_write_manip.h delete mode 100644 src/stream/fmt/buffer/utils/buffer_globber_manip.h delete mode 100644 src/stream/fmt/buffer/utils/buffer_shift_manip.h delete mode 100644 src/stream/fmt/buffer/utils/buffer_utils.h create mode 100644 tests/BUILD.bazel diff --git a/BUILD.bazel b/BUILD.bazel index 67944ba3..21bfc394 100644 --- a/BUILD.bazel +++ b/BUILD.bazel @@ -16,24 +16,3 @@ cc_library( linkstatic = True, visibility = ["//visibility:public"], ) - -cc_test( - name = "streamTests", - srcs = glob([ "Tests/**/*.h", "Tests/**/*.cpp" ]), - copts = select({ - "@rules_cc//cc/compiler:msvc-cl": ["/std:latest"], - "//conditions:default": [ - "-std=c++23", - "-Wall", "-Wextra", "-Wpedantic", - "-Wshadow", - "-Wconversion", "-Wsign-conversion", - "-Werror=return-type" - ], - }), - deps = [ ":stream" ], - linkopts = select({ - "@rules_cc//cc/compiler:msvc-cl": [""], - "//conditions:default": ["-pthread"], - }), - visibility = ["//visibility:public"], -) diff --git a/examples/hello/main.cpp b/examples/hello/main.cpp index 9afc867e..926a845b 100644 --- a/examples/hello/main.cpp +++ b/examples/hello/main.cpp @@ -1,15 +1,16 @@ #include "stream/flog.h" -#include "stream/flog/DefaultLogger.h" #include "stream/fmt/context/formatter_executor/utility_functions.h" +#include "stream/default_logger.h" + #include int main() { - stream::flog::DefaultLogger::Core().info("HelloWorld !"); + stream::flog::DefaultLogger::core().info("HelloWorld !"); using namespace std::chrono_literals; std::this_thread::sleep_for(100ms); - stream::flog::DefaultLogger::Core().warn("After 100ms !"); + stream::flog::DefaultLogger::core().warn("after 100ms !"); } diff --git a/src/stream/default_logger.h b/src/stream/default_logger.h index 8e037ed5..9070d3e2 100644 --- a/src/stream/default_logger.h +++ b/src/stream/default_logger.h @@ -12,26 +12,26 @@ namespace stream::flog class DefaultLogger { public: - [[maybe_unused]] static BasicLogger& Core() + [[maybe_unused]] static BasicLogger& core() { - static BasicLogger instance(STREAMFORMAT_BASE_LOGGER_NAME "-Core", LogSeverity::Trace); + static BasicLogger instance(STREAMFORMAT_BASE_LOGGER_NAME "-core", LogSeverity::Trace); return instance; } - [[maybe_unused]] static BasicLogger& Client() + [[maybe_unused]] static BasicLogger& client() { - static BasicLogger instance(STREAMFORMAT_BASE_LOGGER_NAME "-Client", LogSeverity::Trace); + static BasicLogger instance(STREAMFORMAT_BASE_LOGGER_NAME "-client", LogSeverity::Trace); return instance; } }; } #ifdef STREAMFORMAT_LOGGER_ENABLE - #define CORE_TRACE(...) stream::flog::BasicLogger::Core().trace(__VA_ARGS__) - #define CORE_DEBUG(...) stream::flog::BasicLogger::Core().debug(__VA_ARGS__) - #define CORE_INFO(...) stream::flog::BasicLogger::Core().info(__VA_ARGS__) - #define CORE_WARN(...) stream::flog::BasicLogger::Core().warn(__VA_ARGS__) - #define CORE_ERROR(...) stream::flog::BasicLogger::Core().error(__VA_ARGS__) - #define CORE_FATAL(...) stream::flog::BasicLogger::Core().fatal(__VA_ARGS__) + #define CORE_TRACE(...) stream::flog::BasicLogger::core().trace(__VA_ARGS__) + #define CORE_DEBUG(...) stream::flog::BasicLogger::core().debug(__VA_ARGS__) + #define CORE_INFO(...) stream::flog::BasicLogger::core().info(__VA_ARGS__) + #define CORE_WARN(...) stream::flog::BasicLogger::core().warn(__VA_ARGS__) + #define CORE_ERROR(...) stream::flog::BasicLogger::core().error(__VA_ARGS__) + #define CORE_FATAL(...) stream::flog::BasicLogger::core().fatal(__VA_ARGS__) #else #define CORE_TRACE(...) #define CORE_DEBUG(...) diff --git a/src/stream/flog.h b/src/stream/flog.h index 9ceb3c76..621d4d65 100644 --- a/src/stream/flog.h +++ b/src/stream/flog.h @@ -6,6 +6,6 @@ #include "flog/sinks/file_sink.h" -#include "flog/LoggerImpl/XLogger.h" +#include "flog/frontends/xlogger.h" -#include "flog/LoggerFactory.h" +#include "flog/logger_factory.h" diff --git a/src/stream/flog/backends/basic_logger.h b/src/stream/flog/backends/basic_logger.h index b7b6904a..5a34bb45 100644 --- a/src/stream/flog/backends/basic_logger.h +++ b/src/stream/flog/backends/basic_logger.h @@ -1,7 +1,7 @@ #pragma once #include "stream/flog/detail/detail.h" -#include "stream/fmt/serializers/FormatChrono.h" +#include "stream/fmt/serializers/format_chrono.h" #include #include @@ -16,32 +16,32 @@ namespace stream::flog::detail public: BasicLoggerImpl() - : m_Name("Logger") + : name_("logger_") , m_Severity(Severity::Value::DefaultSeverity) , m_Stream(std::cout) - , m_StartTime(std::chrono::high_resolution_clock::now()) + , start_time_(std::chrono::high_resolution_clock::now()) { ResetPattern(); } explicit BasicLoggerImpl(const std::string_view& name, typename Severity::Value severity = Severity::Value::DefaultSeverity, std::ostream& stream = std::cout) - : m_Name(name) + : name_(name) , m_Severity(severity) , m_Stream(stream) - , preFormatBufferOutManager(64) - , fullFormatBufferOutManager(64) - , m_StartTime(std::chrono::high_resolution_clock::now()) + , preFormatStreamIOManager(64) + , fullFormatStreamIOManager(64) + , start_time_(std::chrono::high_resolution_clock::now()) { ResetPattern(); } explicit BasicLoggerImpl(const std::string_view& name, const std::string_view& format, typename Severity::Value severity = Severity::Value::DefaultSeverity, std::ostream& stream = std::cout) - : m_Name(name) + : name_(name) , m_Severity(severity) , m_Stream(stream) - , preFormatBufferOutManager(64) - , fullFormatBufferOutManager(64) - , m_StartTime(std::chrono::high_resolution_clock::now()) + , preFormatStreamIOManager(64) + , fullFormatStreamIOManager(64) + , start_time_(std::chrono::high_resolution_clock::now()) { SetPattern(format); } @@ -50,8 +50,8 @@ namespace stream::flog::detail public: void SetSeverity(const SeverityValueType& severity) { m_Severity = severity; } - void SetName(const std::string& name) { m_Name = name; } - void SetName(std::string&& name) { m_Name = std::move(name); } + void set_name(const std::string& name) { name_ = name; } + void set_name(std::string&& name) { name_ = std::move(name); } void SetRealPattern(std::string_view pattern) { m_Pattern = pattern; } void SetRealPatternStrmv(std::string&& pattern) { m_Pattern = std::move(pattern); } void SetPattern(std::string_view pattern) @@ -62,32 +62,32 @@ namespace stream::flog::detail void ResetPattern() { SetPattern("[{time:pattern='%h:%m:%s:%ms'}] {name} >> {data}"); } private: - std::string m_Name; + std::string name_; SeverityValueType m_Severity; std::ostream& m_Stream; std::string m_Pattern; - fmt::detail::DynamicBufferOutManager preFormatBufferOutManager; - fmt::detail::DynamicBufferOutManager fullFormatBufferOutManager; + fmt::buf::DynamicStreamIOManager preFormatStreamIOManager; + fmt::buf::DynamicStreamIOManager fullFormatStreamIOManager; - std::chrono::time_point m_StartTime; + std::chrono::time_point start_time_; public: void NewLine() { m_Stream.write("\n", 1); } template - requires fmt::detail::ConvertibleToBufferInfoView + requires fmt::buf::convertible_to_buffer_info_view [[nodiscard]] std::expected log(const SeverityValueType& severity, Format&& format, Args&&... args) { if (severity < m_Severity) return {}; - std::chrono::nanoseconds logTime = std::chrono::high_resolution_clock::now() - m_StartTime; + std::chrono::nanoseconds logTime = std::chrono::high_resolution_clock::now() - start_time_; - SF_TRY(fmt::detail::FormatInManager(preFormatBufferOutManager, false, fmt::detail::BufferInfoView(m_Pattern), FORMAT_SV("time", logTime), FORMAT_SV("name", m_Name), + SF_TRY(fmt::detail::format_in_manager(preFormatStreamIOManager, false, fmt::buf::StreamView(m_Pattern), FORMAT_SV("time", logTime), FORMAT_SV("name", name_), FORMAT_SV("data", flog::AddIndentInFormat(format)))); - SF_TRY(fmt::detail::FormatInManager(fullFormatBufferOutManager, true, preFormatBufferOutManager.GetLastGeneratedBufferInfoView(), std::forward(args)..., FORMAT_SV("color", severity))); - m_Stream.write(fullFormatBufferOutManager.GetBuffer(), static_cast(fullFormatBufferOutManager.GetLastGeneratedDataSize())); + SF_TRY(fmt::detail::format_in_manager(fullFormatStreamIOManager, true, preFormatStreamIOManager.get_last_generated_buffer_info_view(), std::forward(args)..., FORMAT_SV("color", severity))); + m_Stream.write(fullFormatStreamIOManager.get_buffer(), static_cast(fullFormatStreamIOManager.get_last_generated_data_size())); m_Stream.flush(); return {}; @@ -99,11 +99,11 @@ namespace stream::flog::detail if (severity < m_Severity) return {}; - std::chrono::nanoseconds logTime = std::chrono::high_resolution_clock::now() - m_StartTime; + std::chrono::nanoseconds logTime = std::chrono::high_resolution_clock::now() - start_time_; - SF_TRY(fmt::detail::FormatInManager(fullFormatBufferOutManager, true, fmt::detail::BufferInfoView(m_Pattern), FORMAT_SV("data", t), FORMAT_SV("color", severity), - FORMAT_SV("time", logTime), FORMAT_SV("name", m_Name))); - m_Stream.write(fullFormatBufferOutManager.GetBuffer(), static_cast(fullFormatBufferOutManager.GetLastGeneratedDataSize())); + SF_TRY(fmt::detail::format_in_manager(fullFormatStreamIOManager, true, fmt::buf::StreamView(m_Pattern), FORMAT_SV("data", t), FORMAT_SV("color", severity), + FORMAT_SV("time", logTime), FORMAT_SV("name", name_))); + m_Stream.write(fullFormatStreamIOManager.get_buffer(), static_cast(fullFormatStreamIOManager.get_last_generated_data_size())); m_Stream.flush(); return {}; diff --git a/src/stream/flog/backends/logger_multi_sink.h b/src/stream/flog/backends/logger_multi_sink.h index 8c8b704b..31ab3b8a 100644 --- a/src/stream/flog/backends/logger_multi_sink.h +++ b/src/stream/flog/backends/logger_multi_sink.h @@ -1,7 +1,7 @@ #pragma once #include "stream/flog/detail/detail.h" -#include "stream/flog/sinks/LoggerSink.h" +#include "stream/flog/sinks/logger_sink.h" namespace stream::flog::detail { @@ -14,37 +14,37 @@ namespace stream::flog::detail public: BasicLoggerMultiSinkImpl() - : m_Name("Logger:{sink}") - , m_StartTime(std::chrono::high_resolution_clock::now()) + : name_("logger_:{sink}") + , start_time_(std::chrono::high_resolution_clock::now()) {} BasicLoggerMultiSinkImpl(std::basic_string&& name) - : m_Name(std::forward>(name)) - , m_StartTime(std::chrono::high_resolution_clock::now()) + : name_(std::forward>(name)) + , start_time_(std::chrono::high_resolution_clock::now()) {} virtual ~BasicLoggerMultiSinkImpl() = default; public: - void SetName(std::basic_string&& name) { m_Name = std::forward>(name); } + void set_name(std::basic_string&& name) { name_ = std::forward>(name); } - std::basic_string& GetName() { return m_Name; } - std::vector>& GetSinks() { return m_Sinks; } + std::basic_string& get_name() { return name_; } + std::vector>& get_sinks() { return sinks_; } protected: - std::basic_string m_Name; - std::vector> m_Sinks; + std::basic_string name_; + std::vector> sinks_; - std::chrono::time_point m_StartTime; + std::chrono::time_point start_time_; public: - void AddSink(std::shared_ptr sink) { m_Sinks.push_back(sink); } + void add_sink(std::shared_ptr sink) { sinks_.pushback(sink); } template void EmplaceSink(Args&&... args) { std::shared_ptr sink = std::make_shared(std::forward(args)...); - AddSink(sink); + add_sink(sink); } }; } diff --git a/src/stream/flog/backends/logger_multi_sink_fast.h b/src/stream/flog/backends/logger_multi_sink_fast.h index b2e4930d..682f71de 100644 --- a/src/stream/flog/backends/logger_multi_sink_fast.h +++ b/src/stream/flog/backends/logger_multi_sink_fast.h @@ -1,6 +1,6 @@ #pragma once -#include "LoggerMultiSinks.h" +#include "logger_multi_sink.h" namespace stream::flog::detail { @@ -9,14 +9,14 @@ namespace stream::flog::detail { public: using Base = BasicLoggerMultiSinkImpl; - using Base::SetName; - using Base::GetName; - using Base::GetSinks; - using Base::AddSink; - using Base::m_Name; - using Base::m_Sinks; + using Base::set_name; + using Base::get_name; + using Base::get_sinks; + using Base::add_sink; + using Base::name_; + using Base::sinks_; - using Base::m_StartTime; + using Base::start_time_; using typename Base::SeverityValueType; @@ -32,41 +32,41 @@ namespace stream::flog::detail ~BasicLoggerMultiSinkFastImpl() override = default; public: - void Await(const SeverityValueType& severity) + void await(const SeverityValueType& severity) { - for (auto& sink : m_Sinks) - if (sink->NeedToLog(severity)) sink->WaitUnitlFinishedToWrite(); + for (auto& sink : sinks_) + if (sink->need_to_log(severity)) sink->wait_until_finished_to_write(); } public: template - requires fmt::detail::ConvertibleToBufferInfoView + requires fmt::buf::convertible_to_buffer_info_view [[nodiscard]] std::expected log(const SeverityValueType& severity, const Format& format, Args&&... args) { - std::chrono::nanoseconds logTime = std::chrono::high_resolution_clock::now() - m_StartTime; + std::chrono::nanoseconds logTime = std::chrono::high_resolution_clock::now() - start_time_; - fmt::detail::DynamicBufferOutManager manager(256); - auto formatBuffer = SF_TRY(fmt::detail::FormatInManager(manager, false, format, std::forward(args)...)); - for (auto& sink : m_Sinks) - if (sink->NeedToLog(severity)) - { SF_TRY(sink->FormatAndWriteToSink(sink->get_pattern(severity), logTime, m_Name, static_cast>(*formatBuffer))); } + fmt::buf::DynamicStreamIOManager manager(256); + auto formatBuffer = SF_TRY(fmt::detail::format_in_manager(manager, false, format, std::forward(args)...)); + for (auto& sink : sinks_) + if (sink->need_to_log(severity)) + { SF_TRY(sink->format_and_write_to_sink(sink->get_pattern(severity), logTime, name_, static_cast>(*formatBuffer))); } - Await(severity); + await(severity); return {}; } template [[nodiscard]] std::expected log(const SeverityValueType& severity, T&& t) { - std::chrono::nanoseconds logTime = std::chrono::high_resolution_clock::now() - m_StartTime; + std::chrono::nanoseconds logTime = std::chrono::high_resolution_clock::now() - start_time_; - fmt::detail::DynamicBufferOutManager manager(256); - auto formatBuffer = SF_TRY(fmt::detail::FormatInManager(manager, false, std::forward(t))); - for (auto& sink : m_Sinks) - if (sink->NeedToLog(severity)) - { SF_TRY(sink->FormatAndWriteToSink(sink->get_pattern(severity), logTime, m_Name, static_cast>(*formatBuffer))); } + fmt::buf::DynamicStreamIOManager manager(256); + auto formatBuffer = SF_TRY(fmt::detail::format_in_manager(manager, false, std::forward(t))); + for (auto& sink : sinks_) + if (sink->need_to_log(severity)) + { SF_TRY(sink->format_and_write_to_sink(sink->get_pattern(severity), logTime, name_, static_cast>(*formatBuffer))); } - Await(severity); + await(severity); return {}; } diff --git a/src/stream/flog/backends/logger_multi_sink_safe.h b/src/stream/flog/backends/logger_multi_sink_safe.h index 2ef2c3dd..72bdd0cc 100644 --- a/src/stream/flog/backends/logger_multi_sink_safe.h +++ b/src/stream/flog/backends/logger_multi_sink_safe.h @@ -1,6 +1,6 @@ #pragma once -#include "LoggerMultiSinks.h" +#include "logger_multi_sink.h" namespace stream::flog::detail { @@ -9,14 +9,14 @@ namespace stream::flog::detail { public: using Base = BasicLoggerMultiSinkImpl; - using Base::SetName; - using Base::GetName; - using Base::GetSinks; - using Base::m_Name; - using Base::m_Sinks; - using Base::AddSink; + using Base::set_name; + using Base::get_name; + using Base::get_sinks; + using Base::name_; + using Base::sinks_; + using Base::add_sink; - using Base::m_StartTime; + using Base::start_time_; using typename Base::SeverityValueType; @@ -32,56 +32,56 @@ namespace stream::flog::detail ~BasicLoggerMultiSinkSafeImpl() override = default; public: - void Await(const SeverityValueType& severity) + void await(const SeverityValueType& severity) { - for (auto& sink : m_Sinks) - if (sink->NeedToLog(severity)) sink->WaitUnitlFinishedToWrite(); + for (auto& sink : sinks_) + if (sink->need_to_log(severity)) sink->wait_until_finished_to_write(); } public: template - requires fmt::detail::ConvertibleToBufferInfoView + requires fmt::buf::convertible_to_buffer_info_view [[nodiscard]] std::expected log(const SeverityValueType& severity, const Format& format, Args&&... args) { - std::chrono::nanoseconds logTime = std::chrono::high_resolution_clock::now() - m_StartTime; + std::chrono::nanoseconds logTime = std::chrono::high_resolution_clock::now() - start_time_; // FIXME maybe add : name ; indent ??? - for (auto& sink : m_Sinks) + for (auto& sink : sinks_) { - if (sink->NeedToLog(severity)) + if (sink->need_to_log(severity)) { - fmt::detail::DynamicBufferOutManager managerPattern(256); - fmt::detail::DynamicBufferOutManager managerFormat(256); - auto formatPatternStr = - SF_TRY(fmt::detail::FormatInManager(managerPattern, false, std::string_view(sink->get_pattern(severity)), FORMAT_SV("time", logTime), - FORMAT_SV("name", FuturConcateNameAndSinkName(m_Name)), FORMAT_SV("data", flog::AddIndentInFormat(format)))); - auto formatFormatStr = SF_TRY(fmt::detail::FormatInManager(managerFormat, false, static_cast(*formatPatternStr), std::forward(args)..., - FORMAT_SV("sink", sink->GetName()), FORMAT_SV("color", severity))); - SF_TRY(sink->WriteToSink(static_cast>(*formatFormatStr))); + fmt::buf::DynamicStreamIOManager manager_pattern(256); + fmt::buf::DynamicStreamIOManager manager_format(256); + auto format_pattern_str = + SF_TRY(fmt::detail::format_in_manager(manager_pattern, false, std::string_view(sink->get_pattern(severity)), FORMAT_SV("time", logTime), + FORMAT_SV("name", FutureConcatNameAndSinkName(name_)), FORMAT_SV("data", flog::AddIndentInFormat(format)))); + auto format_format_str = SF_TRY(fmt::detail::format_in_manager(manager_format, false, static_cast(*format_pattern_str), std::forward(args)..., + FORMAT_SV("sink", sink->get_name()), FORMAT_SV("color", severity))); + SF_TRY(sink->WriteToSink(static_cast>(*format_format_str))); } } - Await(severity); + await(severity); return {}; } template [[nodiscard]] std::expected log(const SeverityValueType& severity, T&& t) { - std::chrono::nanoseconds logTime = std::chrono::high_resolution_clock::now() - m_StartTime; + std::chrono::nanoseconds logTime = std::chrono::high_resolution_clock::now() - start_time_; - for (auto& sink : m_Sinks) + for (auto& sink : sinks_) { - if (sink->NeedToLog(severity)) + if (sink->need_to_log(severity)) { - fmt::detail::DynamicBufferOutManager manager(256); - auto formatBuffer = SF_TRY(fmt::detail::FormatInManager(manager, false, std::string_view(sink->get_pattern(severity)), FORMAT_SV("time", logTime), - FORMAT_SV("name", ConcateNameAndSinkName(m_Name, sink->GetName())), FORMAT_SV("data", t))); + fmt::buf::DynamicStreamIOManager manager(256); + auto formatBuffer = SF_TRY(fmt::detail::format_in_manager(manager, false, std::string_view(sink->get_pattern(severity)), FORMAT_SV("time", logTime), + FORMAT_SV("name", ConcatNameAndSinkName(name_, sink->get_name())), FORMAT_SV("data", t))); SF_TRY(sink->WriteToSink(static_cast>(*formatBuffer))); } } - Await(severity); + await(severity); return {}; } }; diff --git a/src/stream/flog/detail/detail.h b/src/stream/flog/detail/detail.h index 5b3d98e1..b3696691 100644 --- a/src/stream/flog/detail/detail.h +++ b/src/stream/flog/detail/detail.h @@ -2,8 +2,8 @@ #include "stream/fmt.h" -#include "stream/fmt/buffer/buffer_manip.h" -#include "stream/fmt/buffer/buffer_write_manip.h" +#include "stream/fmt/buf/manip.h" +#include "stream/fmt/buf/write_manip.h" namespace stream::flog { @@ -13,13 +13,13 @@ namespace stream::flog AddIndentInFormat(const FormatStr& format) : format(format) {} - const FormatStr& Format; + const FormatStr& format; }; template - struct ConcateNameAndSinkName + struct ConcatNameAndSinkName { - ConcateNameAndSinkName(const std::basic_string& loggerName, const std::basic_string& sinkName) + ConcatNameAndSinkName(const std::basic_string& loggerName, const std::basic_string& sinkName) : LoggerName(loggerName) , SinkName(sinkName) {} @@ -28,9 +28,9 @@ namespace stream::flog }; template - struct FuturConcateNameAndSinkName + struct FutureConcatNameAndSinkName { - FuturConcateNameAndSinkName(const std::basic_string& loggerName) + FutureConcatNameAndSinkName(const std::basic_string& loggerName) : LoggerName(loggerName) {} const std::basic_string& LoggerName; @@ -44,26 +44,26 @@ namespace stream::fmt { [[nodiscard]] static std::expected format(const stream::flog::AddIndentInFormat& format, FormatterExecutor& executor) { - SF_TRY(detail::BufferWriteManip(executor.buffer_out).FastWriteStringLitteral("{K:indent}")); - return executor.WriteType(format.Format); + SF_TRY(buf::WriteManip(executor.ostream).fast_write_string_literal("{K:indent}")); + return executor.write_type(format.format); } }; template - struct FormatterType, FormatterExecutor> + struct FormatterType, FormatterExecutor> { - [[nodiscard]] static std::expected format(const stream::flog::ConcateNameAndSinkName& names, FormatterExecutor& executor) + [[nodiscard]] static std::expected format(const stream::flog::ConcatNameAndSinkName& names, FormatterExecutor& executor) { - return executor.Run(names.LoggerName, FORMAT_SV("sink", names.SinkName)); + return executor.run(names.LoggerName, FORMAT_SV("sink", names.SinkName)); } }; template - struct FormatterType, FormatterExecutor> + struct FormatterType, FormatterExecutor> { - [[nodiscard]] static std::expected format(const stream::flog::FuturConcateNameAndSinkName& names, FormatterExecutor& executor) + [[nodiscard]] static std::expected format(const stream::flog::FutureConcatNameAndSinkName& names, FormatterExecutor& executor) { - return executor.Run(names.LoggerName, "sink"); + return executor.run(names.LoggerName, "sink"); } }; } diff --git a/src/stream/flog/frontends/xlogger.cpp b/src/stream/flog/frontends/xlogger.cpp index 6e098267..2b737982 100644 --- a/src/stream/flog/frontends/xlogger.cpp +++ b/src/stream/flog/frontends/xlogger.cpp @@ -1,4 +1,4 @@ -#include "XLogger.h" +#include "xlogger.h" namespace stream::flog { diff --git a/src/stream/flog/frontends/xlogger.h b/src/stream/flog/frontends/xlogger.h index 50c11d27..2616afdc 100644 --- a/src/stream/flog/frontends/xlogger.h +++ b/src/stream/flog/frontends/xlogger.h @@ -13,23 +13,23 @@ namespace stream::flog public: enum class Value : int { - trace, - debug, + Trace, + Debug, Info, Warn, Error, Fatal, - DefaultSeverity = trace + DefaultSeverity = Trace }; public: - static constexpr Value trace{Value::Trace}; - static constexpr Value debug{Value::Debug}; + static constexpr Value Trace{Value::Trace}; + static constexpr Value Debug{Value::Debug}; static constexpr Value Info{Value::Info}; static constexpr Value Warn{Value::Warn}; static constexpr Value Error{Value::Error}; static constexpr Value Fatal{Value::Fatal}; - static constexpr Value DefaultSeverity = trace; + static constexpr Value DefaultSeverity = Trace; public: class PatternOverride @@ -86,7 +86,7 @@ namespace stream::flog::detail public: template - requires fmt::detail::ConvertibleToBufferInfoView + requires fmt::buf::convertible_to_buffer_info_view [[nodiscard]] std::expected log(Severity status, Format&& format, Args&&... args) { return Master::template log(status, format, std::forward(args)...); @@ -99,45 +99,45 @@ namespace stream::flog::detail } public: - /////---------- Logger Severity with array as format ----------///// + /////---------- logger Severity with array as format ----------///// template - requires fmt::detail::ConvertibleToBufferInfoView + requires fmt::buf::convertible_to_buffer_info_view inline std::expected trace(Format&& format, Args&&... args) { return log(LogSeverity::Trace, format, std::forward(args)...); } template - requires fmt::detail::ConvertibleToBufferInfoView + requires fmt::buf::convertible_to_buffer_info_view inline std::expected debug(Format&& format, Args&&... args) { return log(LogSeverity::Debug, format, std::forward(args)...); } template - requires fmt::detail::ConvertibleToBufferInfoView + requires fmt::buf::convertible_to_buffer_info_view inline std::expected info(Format&& format, Args&&... args) { return log(LogSeverity::Info, format, std::forward(args)...); } template - requires fmt::detail::ConvertibleToBufferInfoView + requires fmt::buf::convertible_to_buffer_info_view inline std::expected warn(Format&& format, Args&&... args) { return log(LogSeverity::Warn, format, std::forward(args)...); } template - requires fmt::detail::ConvertibleToBufferInfoView + requires fmt::buf::convertible_to_buffer_info_view inline std::expected error(Format&& format, Args&&... args) { return log(LogSeverity::Error, format, std::forward(args)...); } template - requires fmt::detail::ConvertibleToBufferInfoView + requires fmt::buf::convertible_to_buffer_info_view inline std::expected fatal(Format&& format, Args&&... args) { return log(LogSeverity::Fatal, format, std::forward(args)...); } - /////---------- NO-FORMAT Logger Severity ----------///// + /////---------- NO-FORMAT logger Severity ----------///// template inline std::expected trace(T&& t) { @@ -178,7 +178,7 @@ namespace stream::fmt { [[nodiscard]] static std::expected format(const stream::flog::LogSeverity::Value t, FormatterExecutor& executor) { - executor.Data.KeepNewStyle = true; + executor.data.keep_new_style = true; switch (t) { case stream::flog::LogSeverity::Trace: diff --git a/src/stream/flog/sinks/file_sink.h b/src/stream/flog/sinks/file_sink.h index 667285ef..a3d14144 100644 --- a/src/stream/flog/sinks/file_sink.h +++ b/src/stream/flog/sinks/file_sink.h @@ -1,6 +1,6 @@ #pragma once -#include "LoggerSink.h" +#include "logger_sink.h" #include #include diff --git a/src/stream/flog/sinks/logger_sink.h b/src/stream/flog/sinks/logger_sink.h index 34d1bda5..342f592c 100644 --- a/src/stream/flog/sinks/logger_sink.h +++ b/src/stream/flog/sinks/logger_sink.h @@ -17,7 +17,7 @@ namespace stream::flog::detail { public: using PatternType = std::basic_string; - using PatternTransfertType = std::basic_string_view; + using PatternTransferType = std::basic_string_view; using NameType = std::basic_string; using BufferType = std::basic_string_view; @@ -25,19 +25,19 @@ namespace stream::flog::detail public: BasicLoggerSink(NameType&& name) - : Name(std::forward(name)) + : name(std::forward(name)) , IsAsync(AsyncSink::Sync) {} BasicLoggerSink(NameType&& name, AsyncSink isAsync) - : Name(std::forward(name)) + : name(std::forward(name)) , IsAsync(isAsync) {} virtual ~BasicLoggerSink() = default; public: - NameType Name = ""; + NameType name = ""; PatternType Pattern = "[{time:pattern='%h:%m:%s:%ms'}] {name} >> {data}"; SeverityValueType SinkSeverity{SeverityValueType::DefaultSeverity}; typename Severity::PatternOverride SeverityPatternOverride; @@ -47,17 +47,17 @@ namespace stream::flog::detail std::future m_AsyncWaiter; public: - bool NeedToLog(const SeverityValueType& severity) { return severity >= SinkSeverity; } + bool need_to_log(const SeverityValueType& severity) { return severity >= SinkSeverity; } void WriteToSink(const SeverityValueType& severity, const BufferType& bufferToPrint) { - if (NeedToLog(severity)) + if (need_to_log(severity)) WriteToSink(bufferToPrint); } public: - PatternTransfertType get_pattern(const typename Severity::Value& severity) const + PatternTransferType get_pattern(const typename Severity::Value& severity) const { - PatternTransfertType customPattern = SeverityPatternOverride.get_pattern(severity); + PatternTransferType customPattern = SeverityPatternOverride.get_pattern(severity); if (customPattern.data() == nullptr || customPattern.size() == 0) return Pattern; return customPattern; } @@ -81,29 +81,29 @@ namespace stream::flog::detail } public: - void WaitUnitlFinishedToWrite() + void wait_until_finished_to_write() { if (IsAsync == AsyncSink::Async) return m_AsyncWaiter.get(); } - [[nodiscard]] std::expected FormatAndWriteToSinkSync(PatternTransfertType pattern, const std::chrono::nanoseconds& logTime, const NameType& loggerName, const BufferType& formatBuffer) + [[nodiscard]] std::expected FormatAndWriteToSinkSync(PatternTransferType pattern, const std::chrono::nanoseconds& logTime, const NameType& loggerName, const BufferType& formatBuffer) { - fmt::detail::DynamicBufferOutManager manager(256); - auto formatPatternStr = SF_TRY(fmt::detail::FormatInManager(manager, false, pattern, FORMAT_SV("time", logTime), FORMAT_SV("name", ConcateNameAndSinkName(loggerName, Name)), + fmt::buf::DynamicStreamIOManager manager(256); + auto format_pattern_str = SF_TRY(fmt::detail::format_in_manager(manager, false, pattern, FORMAT_SV("time", logTime), FORMAT_SV("name", ConcatNameAndSinkName(loggerName, name)), FORMAT_SV("data", formatBuffer))); - BufferType buffer(*formatPatternStr); + BufferType buffer(*format_pattern_str); WriteToSinkSync(buffer); return {}; } - [[nodiscard]] std::expected FormatAndWriteToSinkAsync(PatternTransfertType pattern, const std::chrono::nanoseconds& logTime, const NameType& loggerName, const BufferType& formatBuffer) + [[nodiscard]] std::expected FormatAndWriteToSinkAsync(PatternTransferType pattern, const std::chrono::nanoseconds& logTime, const NameType& loggerName, const BufferType& formatBuffer) { // TODO m_AsyncWaiter = std::async(std::launch::async, &BasicLoggerSink::FormatAndWriteToSinkSync, this, pattern, logTime, loggerName, formatBuffer); return {}; } - [[nodiscard]] std::expected FormatAndWriteToSink(PatternTransfertType pattern, const std::chrono::nanoseconds& logTime, const NameType& loggerName, const BufferType& formatBuffer) + [[nodiscard]] std::expected format_and_write_to_sink(PatternTransferType pattern, const std::chrono::nanoseconds& logTime, const NameType& loggerName, const BufferType& formatBuffer) { if (IsAsync == AsyncSink::Sync) return FormatAndWriteToSinkSync(pattern, logTime, loggerName, formatBuffer); diff --git a/src/stream/fmt/buf/fmt_manip_io.h b/src/stream/fmt/buf/fmt_manip_io.h new file mode 100644 index 00000000..d67f4b70 --- /dev/null +++ b/src/stream/fmt/buf/fmt_manip_io.h @@ -0,0 +1,118 @@ +#pragma once + +#include "stream.h" +#include "manip_io.h" +#include "test_manip.h" + +namespace stream::fmt::buf +{ + template + class FMTStreamIO : public StreamIO + { + public: + using typename StreamIO::TChar; + + using StreamIO::buffer; + using StreamIO::current_pos; + using StreamIO::buffer_end; + + using StreamIO::get; + + using StreamIO::Manager; + + protected: + FMTStreamIO(BasicStreamIOManager& ostream_manager) noexcept + : StreamIO(ostream_manager) + {} + + public: + [[nodiscard]] static std::expected, FMTResult> create(BasicStreamIOManager& ostream_manager) + { + FMTStreamIO res(ostream_manager); + SF_TRY(StreamIO::init(res)); + return res; + } + + public: + std::size_t NoStride = 0; + std::size_t indent = 0; + }; + + template + class FMTManipIO + { + public: + FMTManipIO(FMTStreamIO& buffer) : buffer(buffer) {} + public: + FMTStreamIO& buffer; + + public: + constexpr inline void add_no_stride(const std::size_t no_stride) noexcept { buffer.NoStride += no_stride; } + + constexpr inline void add_indent(const std::size_t indent) noexcept { buffer.indent += indent; } + constexpr inline void remove_indent(const std::size_t indent) noexcept { buffer.indent -= indent; } + constexpr inline void set_indent() noexcept { buffer.indent = Manip(buffer).get_buffer_current_size() - buffer.NoStride; } + + public: + [[nodiscard]] constexpr inline std::expected new_line_indent() + { + SF_TRY(ManipIO(buffer).pushback('\n')); + return ManipIO(buffer).pushback(' ', buffer.indent); + } + + [[nodiscard]] constexpr inline std::expected pushback_check_indent(const TChar c) + { + SF_TRY(ManipIO(buffer).pushback(c)); + if (c == '\n') + { return ManipIO(buffer).pushback(' ', buffer.indent); } + return {}; + } + }; + + template + class FMTParamsManip + { + public: + FMTParamsManip(Stream& buffer) : buffer(buffer) {} + public: + Stream& buffer; + + public: + template + inline void param_go_to(const CharToTest... ele) + { + TestManip(buffer).GoTo(ele..., '}'); + } + template + [[nodiscard]] inline std::expected param_go_to_forward(const CharToTest... ele) + { + return TestManip(buffer).go_to_forward(ele..., '}'); + } + + inline bool is_begin_of_parameter() + { + return TestAccess(buffer).is_equal_to('{'); + } + inline bool is_end_of_parameter() + { + return TestAccess(buffer).is_equal_to('}'); + } + + public: + template + [[nodiscard]] std::expected next_is_named_args(const std::basic_string_view& sv) + { + TestAccess access(buffer); + TestManip manip(buffer); + + TChar* const oldpos = buffer.current_pos; + auto is_same = SF_TRY(manip.is_same_forward(sv)); + if (is_same && (access.is_equal_to(':') || access.is_equal_to('}'))) + { + return true; + } + buffer.current_pos = oldpos; + return false; + } + }; +} diff --git a/src/stream/fmt/buf/fmt_read_manip.h b/src/stream/fmt/buf/fmt_read_manip.h new file mode 100644 index 00000000..2a89cd8c --- /dev/null +++ b/src/stream/fmt/buf/fmt_read_manip.h @@ -0,0 +1,238 @@ +#pragma once + +#include "stream/fmt/buf/stream.h" +#include "stream/fmt/buf/utils/buffer_shift_manip.h" +#include "stream/fmt/buf/manip.h" +#include "stream/fmt/buf/test_manip.h" +#include "stream/fmt/buf/read_manip.h" + +namespace stream::fmt::buf +{ + template + class FMTReadManip + { + public: + FMTReadManip(Stream& buffer) : buffer(buffer) {} + public: + Stream& buffer; + + public: + template + [[nodiscard]] std::expected read_integer(T& i, detail::ShiftInfo shift = detail::ShiftInfo{}) + { + ShiftReadManip shift_manip(buffer); + buf::TestManip manip(buffer); + + SF_TRY(shift_manip.ignore_shift_begin_space(shift)); + + bool sign = false; + if constexpr (std::is_signed_v) + { + sign = SF_TRY(manip.is_equal_to_forward('-')); + if (sign) --shift.size; + } + + TestAccess(buffer).is_a_digit(); + + T res = (T)0; + while (TestAccess(buffer).is_a_digit()) + { + char c = SF_TRY(Manip(buffer).get_and_forward()); + res = res * 10 + (c - '0'); + --shift.size; + } + + SF_TRY(shift_manip.ignore_shift_end(shift)); + + i = sign ? -res : res; + return {}; + } + public: + template + [[nodiscard]] std::expected read_float(T& t, std::int32_t float_precision = -1, detail::ShiftInfo shift = detail::ShiftInfo{}) + { + ShiftReadManip shift_manip(buffer); + buf::TestAccess access(buffer); + buf::TestManip manip(buffer); + + SF_TRY(shift_manip.ignore_shift_begin_space(shift)); + + bool sign = SF_TRY(manip.is_equal_to_forward('-')); + if (sign) --shift.size; + + T intpart = static_cast(0); + if (access.is_a_digit()) + { + while (access.is_a_digit()) + { + char c = SF_TRY(Manip(buffer).get_and_forward()); + intpart = intpart * 10 + (c - '0'); + --shift.size; + } + } + else if (access.is_equal_to('.')) + { SF_TRY(buf::Manip(buffer).forward()); } + else + { return std::unexpected(FMTResult::Parse_NonValidDigit); } + + if (float_precision <= 0) + while (access.is_a_digit() && access.is_end_of_string() == false) + { + Manip(buffer).forward_force(); + --shift.size; + } + else + { + while (Access(buffer).is_a_digit() && float_precision > 0 && Access(buffer).is_end_of_string() == false) + { + Manip(buffer).forward_force(); + float_precision--; + --shift.size; + } + } + Manip(buffer).backward_force(); + + T dec = (T)0; + while (access.is_a_digit()) + { + dec += static_cast(buffer.get() - '0'); + Manip(buffer).backward_force(); + dec /= 10; + } + + SF_TRY(shift_manip.ignore_shift_end(shift)); + + t = sign ? - intpart - dec : intpart + dec; + return {}; + } + + public: + template + [[nodiscard]] std::expected read_integer_h(T& i, std::uint8_t digitSize, std::uint8_t (&digit_lut)(TChar), TChar base_prefix = '\0', detail::ShiftInfo shift = detail::ShiftInfo{}) + { + ShiftReadManip shift_manip(buffer); + buf::TestAccess access(buffer); + buf::TestManip manip(buffer); + + shift.size -= sizeof(T) * 8; + if (base_prefix != '\0') shift.size -= 2; + + SF_TRY(shift_manip.ignore_shift_begin_space(shift)); + + if (base_prefix != '\0') + { + SF_TRY(manip.skip_one_of('0')); + SF_TRY(manip.skip_one_of(base_prefix)); + } + + T res = (T)0; + while (digit_lut(buffer.get()) != std::numeric_limits::max()) + { + res = res << digitSize; + res += digit_lut(buffer.get()); + Manip(buffer).forward_force(); + } + + SF_TRY(shift_manip.ignore_shift_end(shift)); + + i = res; + return {}; + } + + protected: + static constexpr std::uint8_t digit_lut_bin(TChar in) + { + if (in == '0') return 0; + if (in == '1') return 1; + return std::numeric_limits::max(); + } + static constexpr std::uint8_t digit_lut_oct(TChar in) + { + if (in >= '0' && in <= '7') + return in - '0'; + return std::numeric_limits::max(); + } + static constexpr std::uint8_t digit_lut_dec(TChar in) + { + if (in >= '0' && in <= '9') + return in - '0'; + return std::numeric_limits::max(); + } + static constexpr std::uint8_t digit_lut_hexupper(TChar in) + { + if (in >= '0' && in <= '9') + return in - '0'; + if (in >= 'A' && in <= 'F') + return in - 'A'; + return std::numeric_limits::max(); + } + static constexpr std::uint8_t digit_lut_hexlower(TChar in) + { + if (in >= '0' && in <= '9') + return in - '0'; + if (in >= 'a' && in <= 'f') + return in - 'a'; + return std::numeric_limits::max(); + } + + public: + template + [[nodiscard]] std::expected read_integer_format_data(T& i, const detail::FormatData& formatdata) + { + if (formatdata.has_spec) + { + switch (formatdata.integer_print) + { + case detail::IntegerPrintBase::Dec: + if (formatdata.shift.type == detail::ShiftInfo::ShiftType::Nothing) + return ReadManip(buffer).fast_read_integer(i); + else + return read_integer(i, formatdata.shift); + case detail::IntegerPrintBase::Bin: + case detail::IntegerPrintBase::BinUpper: + return read_integer_h(i, 1, digit_lut_bin, formatdata.prefix_suffix ? (char)formatdata.integer_print : '\0', formatdata.shift); + case detail::IntegerPrintBase::Oct: + case detail::IntegerPrintBase::OctUpper: + return read_integer_h(i, 3, digit_lut_oct, formatdata.prefix_suffix ? (char)formatdata.integer_print : '\0', formatdata.shift); + case detail::IntegerPrintBase::Hex: + return read_integer_h(i, 4, digit_lut_hexlower, formatdata.prefix_suffix ? (char)formatdata.integer_print : '\0', formatdata.shift); + case detail::IntegerPrintBase::HexUpper: + return read_integer_h(i, 4, digit_lut_hexupper, formatdata.prefix_suffix ? (char)formatdata.integer_print : '\0', formatdata.shift); + } + } + return ReadManip(buffer).fast_read_integer(i); + } + template + [[nodiscard]] std::expected read_float_format_data(T& i, const detail::FormatData& formatdata) + { + if (formatdata.has_spec) + { + if (formatdata.ShiftType == detail::ShiftInfo::ShiftType::Nothing) + return ReadManip(buffer).fast_read_float(i, formatdata.float_precision); + else + return read_float(i, formatdata.float_precision, formatdata.shift); + } + return ReadManip(buffer).fast_read_float(i, formatdata.float_precision); + } + + public: + template + [[nodiscard]] std::expected read_char_ptr(const CharStr* str, std::size_t sizeContainer, std::size_t sizeToWrite, detail::ShiftInfo shift = detail::ShiftInfo{}) + { + // FIXME + // TODO + return std::unexpected(FMTResult::FunctionNotImpl); + } + + template + [[nodiscard]] inline std::expected read_char_array(const CharStr (&str)[SIZE], detail::ShiftInfo shift = detail::ShiftInfo{}) + { + return read_char_ptr(str, SIZE, 0, shift); + } + template + [[nodiscard]] inline std::expected read_char_bound(const CharStr* begin, const CharStr* end, detail::ShiftInfo shift = detail::ShiftInfo{}) + { + return read_char_ptr(begin, end - begin, 0, shift); + } + }; +} diff --git a/src/stream/fmt/buf/fmt_write_manip.h b/src/stream/fmt/buf/fmt_write_manip.h new file mode 100644 index 00000000..9af282c2 --- /dev/null +++ b/src/stream/fmt/buf/fmt_write_manip.h @@ -0,0 +1,275 @@ +#pragma once + +#include "stream.h" +#include "fmt_manip_io.h" +#include "utils/buffer_shift_manip.h" +#include "manip_io.h" +#include "write_manip.h" + +#include + +namespace stream::fmt::buf +{ + template + class FMTWriteManip + { + public: + FMTWriteManip(FMTStreamIO& buffer) : buffer(buffer) {} + public: + FMTStreamIO& buffer; + + public: + template + [[nodiscard]] std::expected write_integer(T i, detail::ShiftInfo shift = detail::ShiftInfo{}) + { + char old_after = shift.print.after; + if (shift.print.after >= '0' && shift.print.after <= '9') + shift.print.after = ' '; + + std::int32_t nb_digit = WriteUtils::get_number_of_digit_dec(i); + + shift.size -= nb_digit; + if (i < 0) --shift.size; + + if (shift.size <= 0) + { return WriteManip(buffer).fast_write_integer(i); } + + if (!shift.print.before_is_a_digit()) + { SF_TRY(ShiftWriteManip(buffer).write_shift_begin(shift)); } + if (i < 0) + { + SF_TRY(ManipIO(buffer).pushback('-')); + i = -i; + } + if (shift.print.before_is_a_digit()) + { SF_TRY(ShiftWriteManip(buffer).write_shift_right_all(shift)); } + + if (i == 0) + { SF_TRY(ManipIO(buffer).pushback('0')); } + else + { + SF_TRY(ManipIO(buffer).forward(nb_digit)); + std::int32_t nb_digit_ = nb_digit; + while (nb_digit_ > 0) + { + buffer.set(i % 10 + '0'); + SF_TRY(Manip(buffer).backward(nb_digit)); + i /= 10; + nb_digit_--; + } + SF_TRY(ManipIO(buffer).forward(nb_digit)); + } + + SF_TRY(ShiftWriteManip(buffer).write_shift_end(shift)); + + shift.print.after = old_after; + return {}; + } + + public: + template + [[nodiscard]] std::expected write_float(T i, std::int32_t float_precision = 2, detail::ShiftInfo shift = detail::ShiftInfo{}) + { + char old_before = shift.print.before; + if (shift.print.before >= '0' && shift.print.before <= '9') + shift.print.before = ' '; + + std::int32_t nb_digit = WriteUtils::get_number_of_digit_dec(std::trunc(i)); + + shift.size -= nb_digit + float_precision + 1; + if (i < 0) --shift.size; + + if (shift.size <= 0) + { return WriteManip(buffer).fast_write_float(i, float_precision); } + + if (!shift.print.before_is_a_digit()) + { SF_TRY(ShiftWriteManip(buffer).write_shift_begin(shift)); } + if (i < 0) + { + SF_TRY(ManipIO(buffer).pushback('-')); + i = -i; + } + if (shift.print.before_is_a_digit()) + { SF_TRY(ShiftWriteManip(buffer).write_shift_right_all(shift)); } + + T k = std::trunc(i); + if (k == 0) + { SF_TRY(ManipIO(buffer).pushback('0')); } + else + { + SF_TRY(ManipIO(buffer).forward(nb_digit)); + std::int32_t nb_digit_ = nb_digit; + while (nb_digit_ > 0) + { + buffer.set(char(std::fmod(i, 10)) + '0'); + Manip(buffer).backward_force(); + k /= 10; + nb_digit_--; + } + SF_TRY(ManipIO(buffer).forward(nb_digit)); + } + + SF_TRY(ManipIO(buffer).pushback('.')); + i -= k; + while (float_precision-- != 0) + { + T decimal = std::trunc(i *= 10); + SF_TRY(ManipIO(buffer).pushback((char)decimal + '0')); + i -= decimal; + } + + SF_TRY(ShiftWriteManip(buffer).write_shift_end(shift)); + + shift.print.before = old_before; + return {}; + } + + public: + template + [[nodiscard]] std::expected write_integer_h(T i, std::uint8_t digitSize, const TChar* const lut, TChar base_prefix = '\0', detail::ShiftInfo shift = detail::ShiftInfo{}) + { + ManipIO manip(buffer); + + std::int32_t digit_count = sizeof(T) * 8; + { + // Remove leading 0 + std::int32_t last_pos_with_data = 0; + std::int32_t k = digit_count + 1; + T cpyI = i; + while (--k != 0) + { + if ((cpyI & (0b1 << digitSize)) != 0) last_pos_with_data = k; + cpyI = cpyI >> digitSize; + } + digit_count -= last_pos_with_data; + } + + if (base_prefix != '\0') + { + SF_TRY(ManipIO(buffer).pushback('0')); + SF_TRY(ManipIO(buffer).pushback(base_prefix)); + } + + SF_TRY(manip.forward(digit_count)); + std::int32_t k = digit_count + 1; + while (--k != 0) + { + buffer.set(lut[i & (0b1 << digitSize)]); + Manip(buffer).backward_force(); + i = i >> digitSize; + } + SF_TRY(manip.forward(digit_count)); + return {}; + } + + public: + template + [[nodiscard]] std::expected write_integer_format_data(T i, const detail::FormatData& formatdata) + { + if (formatdata.has_spec) + { + switch (formatdata.integer_print) + { + case detail::IntegerPrintBase::Dec: + if (formatdata.shift.type == detail::ShiftInfo::ShiftType::Nothing) + return WriteManip(buffer).fast_write_integer(i); + else + return write_integer(i, formatdata.shift); + case detail::IntegerPrintBase::Bin: + case detail::IntegerPrintBase::BinUpper: + return write_integer_h(i, 1, WriteManip::BIN, formatdata.prefix_suffix ? (char)formatdata.integer_print : '\0', formatdata.shift); + case detail::IntegerPrintBase::Oct: + case detail::IntegerPrintBase::OctUpper: + return write_integer_h(i, 3, WriteManip::OCT, formatdata.prefix_suffix ? (char)formatdata.integer_print : '\0', formatdata.shift); + case detail::IntegerPrintBase::Hex: + return write_integer_h(i, 4, WriteManip::LOWER_HEX, formatdata.prefix_suffix ? (char)formatdata.integer_print : '\0', formatdata.shift); + case detail::IntegerPrintBase::HexUpper: + return write_integer_h(i, 4, WriteManip::UPPER_HEX, formatdata.prefix_suffix ? (char)formatdata.integer_print : '\0', formatdata.shift); + + } + } + return WriteManip(buffer).fast_write_integer(i); + } + template + [[nodiscard]] std::expected write_float_formatdata(T i, const detail::FormatData& formatdata) + { + if (formatdata.has_spec) + { + if (formatdata.shift.type != detail::ShiftInfo::ShiftType::Nothing) + return write_float(i, formatdata.float_precision, formatdata.shift); + } + + return WriteManip(buffer).fast_write_float(i, formatdata.float_precision); + } + + public: + template + [[nodiscard]] inline std::expected write_indent_char_ptr(const CharStr* str, std::size_t size) + { + while (size > 0) + { + const CharStr* const begin = str; + while (size > 0 && *str != '\n') + { + ++str, --size; + } + const CharStr* const end = str; + + SF_TRY(WriteManip(buffer).fast_write_char_array(begin, end - begin)); + + if (size > 0 && *str == '\n') + { + SF_TRY(FMTManipIO(buffer).new_line_indent()); + ++str; + --size; + } + } + return {}; + } + template + [[nodiscard]] inline std::expected write_indent_char_bound(const CharStr* begin, const CharStr* end) + { + return write_indent_char_ptr(begin, end - begin); + } + template + [[nodiscard]] inline std::expected write_indent_string(std::basic_string_view str) + { + return write_indent_char_ptr(str.data(), str.size()); + } + + template + [[nodiscard]] inline std::expected write_char_ptr(const CharStr* str, std::size_t size, detail::ShiftInfo& shift) + { + if (shift.size <= 0) + return WriteManip(buffer).fast_write_char_array(str, size); + + SF_TRY(ManipIO(buffer).reserve(std::max(static_cast(shift.size), size))); + + if (static_cast(shift.size) > size) + { + shift.size -= static_cast(size); + + SF_TRY(ShiftWriteManip(buffer).write_shift_begin(shift)); + + SF_TRY(WriteManip(buffer).fast_write_char_array(str, size)); + + SF_TRY(ShiftWriteManip(buffer).write_shift_end(shift)); + } + else + { + SF_TRY(WriteManip(buffer).fast_write_char_array(str, size)); + } + return {}; + } + template + [[nodiscard]] inline std::expected write_char_bound(const CharStr* begin, const CharStr* end, detail::ShiftInfo& shift) + { + return write_char_ptr(begin, end - begin, shift); + } + template + [[nodiscard]] inline std::expected write_string(std::basic_string_view str, detail::ShiftInfo& shift) + { + return write_char_ptr(str.data(), str.size(), shift); + } + }; +} diff --git a/src/stream/fmt/buf/manip.h b/src/stream/fmt/buf/manip.h new file mode 100644 index 00000000..250ffab8 --- /dev/null +++ b/src/stream/fmt/buf/manip.h @@ -0,0 +1,101 @@ +#pragma once + +#include "stream.h" + +namespace stream::fmt::buf +{ + template + class Access + { + public: + constexpr inline Access(const Stream& buffer) noexcept : buffer(buffer) {} + public: + const Stream& buffer; + + public: + constexpr inline std::size_t get_buffer_total_size() const noexcept { return static_cast(buffer.buffer_end - buffer.buffer); } + constexpr inline std::size_t get_buffer_current_size() const noexcept { return static_cast(buffer.current_pos - buffer.buffer); } + constexpr inline std::size_t get_buffer_remaining_size() const noexcept { return static_cast(buffer.buffer_end - buffer.current_pos); } + + public: + constexpr inline bool can_move_forward(const std::size_t count = 1) const noexcept { return buffer.current_pos + count <= buffer.buffer_end; } + constexpr inline bool can_move_backward(const std::size_t count = 1) const noexcept { return buffer.current_pos - count >= buffer.buffer; } + + constexpr inline bool is_out_of_bound() const noexcept { return buffer.current_pos < buffer.buffer || buffer.current_pos >= buffer.buffer_end; } + constexpr inline bool is_empty() const noexcept { return buffer.current_pos >= buffer.buffer_end; } + constexpr inline bool is_end_of_string() const noexcept { return is_empty() || buffer.get() == 0; } + + [[nodiscard]] constexpr inline std::expected, FMTResult> get_next(const std::size_t count = 1) const + { + if (Access(buffer).can_move_forward(count) == false) + return std::unexpected(FMTResult::Buffer_OutOfBoundAccess); + return Manip(buffer).get_next_force(count); + } + [[nodiscard]] constexpr inline std::expected, FMTResult> get_prev(const std::size_t count = 1) const + { + if (Access(buffer).can_move_backward(count) == false) + return std::unexpected(FMTResult::Buffer_OutOfBoundAccess); + return Manip(buffer).get_prev_force(count); + } + constexpr inline TChar get_next_force(const std::size_t count = 1) const noexcept { return *(buffer.current_pos + count); } + constexpr inline TChar get_prev_force(const std::size_t count = 1) const noexcept { return *(buffer.current_pos - count); } + }; + + template + class Manip + { + public: + constexpr inline Manip(Stream& buffer) noexcept : buffer(buffer) {} + public: + Stream& buffer; + + public: + constexpr inline void reload(TChar* const buffer_, const std::size_t size_) noexcept + { + buffer.buffer = buffer_; + buffer.current_pos = buffer_; + buffer.buffer_end = buffer_ + size_; + } + + constexpr inline void reload(Stream& buffer_) noexcept + { + buffer.buffer = buffer_.buffer; + buffer.current_pos = buffer_.current_pos; + buffer.buffer_end = buffer_.buffer_end; + } + + Access access() { return Access(buffer); } + + public: + constexpr inline void forward_force(const std::size_t count = 1) noexcept { buffer.current_pos += count; } + [[nodiscard]] constexpr inline std::expected forward(const std::size_t count = 1) noexcept + { + if (!access().can_move_forward(count)) + return std::unexpected(FMTResult::Buffer_OutOfBoundAccess); + buffer.current_pos += count; + return {}; + } + + constexpr inline void backward_force(const std::size_t count = 1) noexcept { buffer.current_pos -= count; } + [[nodiscard]] constexpr inline std::expected backward(const std::size_t count = 1) noexcept + { + if (!access().can_move_backward(count)) + return std::unexpected(FMTResult::Buffer_OutOfBoundAccess); + buffer.current_pos -= count; + return {}; + } + + [[nodiscard]] constexpr inline std::expected, FMTResult> get_and_forward() + { + if (Access(buffer).can_move_forward(1) == false) + return std::unexpected(FMTResult::Buffer_OutOfBoundAccess); + return *buffer.current_pos++; + } + [[nodiscard]] constexpr inline std::expected, FMTResult> get_and_backward() + { + if (Access(buffer).can_move_backward(1) == false) + return std::unexpected(FMTResult::Buffer_OutOfBoundAccess); + return *buffer.current_pos--; + } + }; +} diff --git a/src/stream/fmt/buf/manip_io.h b/src/stream/fmt/buf/manip_io.h new file mode 100644 index 00000000..5da3b25c --- /dev/null +++ b/src/stream/fmt/buf/manip_io.h @@ -0,0 +1,83 @@ +#pragma once + +#include "stream.h" +#include "streamio.h" +#include "manip.h" + +#include "streamio_manager/basic_streamio_manager.h" + +namespace stream::fmt::buf +{ + template + class ManipIO + { + public: + constexpr inline ManipIO(StreamIO& buffer) noexcept : buffer(buffer) {} + public: + StreamIO& buffer; + + public: + void compute_generated_size() noexcept { buffer.Manager.compute_generated_size(Access(buffer).get_buffer_current_size()); } + + public: + [[nodiscard]] std::expected add_size(const std::size_t count) noexcept + { + std::size_t currentSize = Access(buffer).get_buffer_current_size(); + SF_TRY(buffer.Manager.add_size(count)) + Manip(buffer).reload(buffer.Manager.get_buffer(), buffer.Manager.get_buffer_size()); + buffer.current_pos = buffer.Manager.get_buffer() + currentSize; + return {}; + } + + [[nodiscard]] inline std::expected reserve(const std::size_t count = 1) noexcept + { + if (buffer.current_pos + count <= buffer.buffer_end) + return {}; + return add_size(static_cast(count)); + } + + [[nodiscard]] inline std::expected forward(const std::size_t count = 1) noexcept + { + SF_TRY(reserve(count)); + buffer.current_pos += count; + return {}; + } + + public: + inline void set(const TChar c) noexcept { *buffer.current_pos = c; } + + [[nodiscard]] inline std::expected pushback(const TChar c) noexcept + { + SF_TRY(reserve(1)); + *buffer.current_pos++ = c; + return {}; + } + inline void pushback_force(const TChar c) noexcept { *buffer.current_pos++ = c; } + + public: + [[nodiscard]] inline std::expected pushback(const TChar c, auto count) noexcept + { + SF_TRY(reserve(count)) + while (count-- > 0) + pushback_force(c); + return {}; + } + + private: + template + inline void pushback_seq_impl(const TChar c, const Rest... rest) noexcept + { + force_pushback(c); + if constexpr (sizeof...(rest) > 0) pushback_seq_impl(rest...); + } + + public: + template + [[nodiscard]] inline std::expected pushback_seq(const CharToPush... ele) noexcept + { + SF_TRY(reserve(sizeof...(ele))) + pushback_seq_impl(ele...); + return {}; + } + }; +} diff --git a/src/stream/fmt/buffer/buffer_read_manip.h b/src/stream/fmt/buf/read_manip.h similarity index 51% rename from src/stream/fmt/buffer/buffer_read_manip.h rename to src/stream/fmt/buf/read_manip.h index 9479da8f..b6ed2cdf 100644 --- a/src/stream/fmt/buffer/buffer_read_manip.h +++ b/src/stream/fmt/buf/read_manip.h @@ -1,33 +1,33 @@ #pragma once -#include "stream/fmt/buffer/buffer_info.h" -#include "stream/fmt/buffer/buffer_manip.h" +#include "stream/fmt/buf/stream.h" +#include "stream/fmt/buf/manip.h" -namespace stream::fmt::detail +namespace stream::fmt::buf { template - class BufferReadManip + class ReadManip { public: - constexpr inline BufferReadManip(BufferInfo& buffer_) noexcept : buffer(buffer_) {} + constexpr inline ReadManip(Stream& buffer_) noexcept : buffer(buffer_) {} public: - BufferInfo& buffer; + Stream& buffer; public: template - [[nodiscard]] constexpr std::expected FastReadInteger(T& t) noexcept + [[nodiscard]] constexpr std::expected fast_read_integer(T& t) noexcept { bool sign = false; if constexpr (std::is_signed_v) - { sign = SF_TRY(BufferTestManip(buffer).IsEqualToForward('-')); } + { sign = SF_TRY(TestManip(buffer).is_equal_to_forward('-')); } - if (!BufferTestAccess(buffer).IsADigit()) + if (!TestAccess(buffer).is_a_digit()) { return std::unexpected(FMTResult::Parse_NonValidDigit); } T value = static_cast(0); - while (BufferTestAccess(buffer).IsADigit()) + while (TestAccess(buffer).is_a_digit()) { - char c = SF_TRY(BufferManip(buffer).GetAndForward()); + char c = SF_TRY(Manip(buffer).get_and_forward()); value = value * static_cast(10) + static_cast(c - static_cast('0')); } @@ -37,41 +37,42 @@ namespace stream::fmt::detail public: template - [[nodiscard]] constexpr inline std::expected FastReadFloat(T& t, std::int32_t floatPrecision = -1) noexcept + [[nodiscard]] constexpr inline std::expected fast_read_float(T& t, std::int32_t float_precision = -1) noexcept { T intpart = static_cast(0); - BufferTestAccess access(buffer); - BufferTestManip manip(buffer); + TestAccess access(buffer); + TestManip manip(buffer); - bool sign = SF_TRY(manip.IsEqualToForward('-')); + bool sign = SF_TRY(manip.is_equal_to_forward('-')); - if (access.IsADigit()) - { SF_TRY(FastReadInteger(intpart)); } - else if (access.IsEqualTo('.')) - { SF_TRY(detail::BufferManip(buffer).Forward()); } + if (access.is_a_digit()) + { SF_TRY(fast_read_integer(intpart)); } + else if (access.is_equal_to('.')) + { SF_TRY(buf::Manip(buffer).forward()); } else { return std::unexpected(FMTResult::Parse_NonValidDigit); } - if (floatPrecision < 0) + if (float_precision < 0) { - while (access.IsADigit() && BufferAccess(buffer).IsEndOfString() == false) - { BufferManip(buffer).ForceForward(); } + while (access.is_a_digit() && Access(buffer).is_end_of_string() == false) + { Manip(buffer).forward_force(); } } else { - while (access.IsADigit() && floatPrecision > 0 && BufferAccess(buffer).IsEndOfString() == false) + while (access.is_a_digit() && float_precision > 0 && Access(buffer).is_end_of_string() == false) { - BufferManip(buffer).ForceForward(); - floatPrecision--; + Manip(buffer).forward_force(); + float_precision--; } } - BufferManip(buffer).ForceBackward(); + Manip(buffer).backward_force(); T dec = static_cast(0); - while (access.IsADigit()) + while (access.is_a_digit()) { - dec += static_cast(BufferManip(buffer).GetAndForceBackward() - '0'); + dec += static_cast(buffer.get() - '0'); + Manip(buffer).backward_force(); dec /= 10; } @@ -83,14 +84,14 @@ namespace stream::fmt::detail template [[nodiscard]] std::expected FastReadCharPtr(const CharPtr* str, std::size_t sizeToCopy, bool isZeroEnded = true) { - if (BufferAccess(buffer).CanMoveForward(sizeToCopy) == false) + if (Access(buffer).can_move_forward(sizeToCopy) == false) { - return BufferReadManip(buffer).FastReadCharPtr(str, BufferAccess(buffer).GetBufferRemainingSize(), isZeroEnded); + return ReadManip(buffer).FastReadCharPtr(str, Access(buffer).get_buffer_remaining_size(), isZeroEnded); } // TODO : Opti with bigger types while (sizeToCopy-- != 0) - { *str++ = SF_TRY(BufferManip(buffer).GetAndForward()); } + { *str++ = SF_TRY(Manip(buffer).get_and_forward()); } if (isZeroEnded) { *str = 0; } return {}; diff --git a/src/stream/fmt/buf/stream.h b/src/stream/fmt/buf/stream.h new file mode 100644 index 00000000..842e2ca6 --- /dev/null +++ b/src/stream/fmt/buf/stream.h @@ -0,0 +1,83 @@ +#pragma once + +#include "stream/fmt/detail/prelude.h" + +namespace stream::fmt::buf +{ + template + class Stream + { + public: + using TChar = CharType; + + public: + TChar* buffer; + TChar* current_pos; + TChar* buffer_end; // Not included + + public: + constexpr inline TChar get() const { return *current_pos; } + + public: + Stream() noexcept + : buffer(nullptr) + , current_pos(nullptr) + , buffer_end(nullptr) + {} + + Stream(TChar* const buffer_, const std::size_t size_) noexcept + : buffer(buffer_) + , current_pos(buffer_) + , buffer_end(buffer_ + size_) + {} + }; + + template + class StreamView : public Stream + { + public: + using typename Stream::TChar; + + using Stream::buffer; + using Stream::current_pos; + using Stream::buffer_end; + + using Stream::get; + + public: + StreamView() noexcept + : Stream() + {} + + template + StreamView(const CharType (&data)[SIZE]) noexcept + : Stream(data, SIZE) + { + while (buffer_end - 1 > buffer && *(buffer_end - 1) == 0) + --buffer_end; + } + + StreamView(std::basic_string_view sv) noexcept + : Stream(sv.data(), sv.size()) + {} + + StreamView(const CharType* const buffer, const std::size_t size) noexcept + : Stream(buffer, size) + {} + + public: + operator Stream() const { return Stream {.buffer = buffer, .current_pos = current_pos, .buffer_end = buffer_end}; } + }; + + template + concept convertible_to_buffer_info = requires(T&& t) + { + Stream(std::forward(t)); + }; + + template + concept convertible_to_buffer_info_view = requires(T&& t) + { + StreamView(std::forward(t)); + }; +} diff --git a/src/stream/fmt/buf/streamio.h b/src/stream/fmt/buf/streamio.h new file mode 100644 index 00000000..fa1e8535 --- /dev/null +++ b/src/stream/fmt/buf/streamio.h @@ -0,0 +1,56 @@ +#pragma once + +#include "stream.h" +#include "manip.h" + +#include "streamio_manager/basic_streamio_manager.h" + +namespace stream::fmt::buf +{ + template + class StreamIO : public Stream + { + public: + using typename Stream::TChar; + + using Stream::buffer; + using Stream::current_pos; + using Stream::buffer_end; + + using Stream::get; + + protected: + StreamIO(BasicStreamIOManager& ostream_manager) noexcept + : Stream() + , Manager(ostream_manager) + {} + + protected: + [[nodiscard]] static std::expected init(StreamIO& in) + { + SF_TRY(in.Manager.BeginContext()); + Manip(in).reload(in.Manager.get_buffer(), in.Manager.get_buffer_size()); + return {}; + } + + public: + [[nodiscard]] static std::expected, FMTResult> create(BasicStreamIOManager& ostream_manager) + { + StreamIO res(ostream_manager); + SF_TRY(init(res)); + return res; + } + + public: + inline void set(const TChar c) noexcept { *current_pos = c; } + + public: + BasicStreamIOManager& Manager; + }; + + template + concept convertible_to_streamio_info = requires(T&& t) + { + StreamIO(std::forward(t)); + }; +} diff --git a/src/stream/fmt/buf/streamio_manager/basic_streamio_manager.h b/src/stream/fmt/buf/streamio_manager/basic_streamio_manager.h new file mode 100644 index 00000000..9b13068e --- /dev/null +++ b/src/stream/fmt/buf/streamio_manager/basic_streamio_manager.h @@ -0,0 +1,52 @@ +#pragma once + +#include "stream/fmt/detail/prelude.h" +#include "stream/fmt/buf/stream.h" + +namespace stream::fmt::buf +{ + template + class BasicStreamIOManager + { + public: + BasicStreamIOManager() = default; + virtual ~BasicStreamIOManager() = default; + BasicStreamIOManager(BasicStreamIOManager&) = delete; + BasicStreamIOManager& operator=(BasicStreamIOManager&) = delete; + + protected: + [[nodiscard]] virtual std::expected begin_context_impl() { return {}; } + virtual void compute_generated_size_impl(const std::size_t /* totalGeneratedLength */) {} + + public: + [[nodiscard]] std::expected BeginContext() { return begin_context_impl(); } + void compute_generated_size(std::size_t totalGeneratedLength) + { + compute_generated_size_impl(totalGeneratedLength); + set_last_generated_data_size(totalGeneratedLength); + } + + public: + virtual CharType* get_buffer() = 0; + virtual const CharType* get_buffer() const = 0; + virtual std::size_t get_buffer_size() const = 0; + + public: + [[nodiscard]] virtual std::expected add_size(const std::size_t count) = 0; + + public: + StreamView get_last_generated_buffer_info_view() const { return StreamView(get_buffer(), m_LastGeneratedDataSize); } + operator StreamView() const { return get_last_generated_buffer_info_view(); } + std::basic_string_view get_last_generated_string_view() const { return std::basic_string_view(get_buffer(), m_LastGeneratedDataSize); } + operator std::basic_string_view() const { return get_last_generated_string_view(); } + + public: + std::size_t get_last_generated_data_size() const { return m_LastGeneratedDataSize; } + + private: + void set_last_generated_data_size(const std::size_t size) { m_LastGeneratedDataSize = size; } + + protected: + std::size_t m_LastGeneratedDataSize{0}; + }; +} diff --git a/src/stream/fmt/buf/streamio_manager/dynamic_streamio_manager.h b/src/stream/fmt/buf/streamio_manager/dynamic_streamio_manager.h new file mode 100644 index 00000000..c9d30df9 --- /dev/null +++ b/src/stream/fmt/buf/streamio_manager/dynamic_streamio_manager.h @@ -0,0 +1,128 @@ +#pragma once + +#include "basic_streamio_manager.h" + +#include +#include +#include + +namespace stream::fmt::buf +{ + template + class DynamicStreamIOManager : public BasicStreamIOManager + { + public: + DynamicStreamIOManager(std::size_t beginSize = DEFAULT_BEGIN_SIZE) + : buffer_size_(beginSize) + {} + + ~DynamicStreamIOManager() override = default; + DynamicStreamIOManager(DynamicStreamIOManager&) = delete; + DynamicStreamIOManager& operator=(DynamicStreamIOManager&) = delete; + + public: + static constexpr std::size_t DEFAULT_BEGIN_SIZE = 128; + static constexpr std::size_t GROW_UP_BUFFER_SIZE = 2; + static constexpr bool DEBUG_RESIZE = false; + + public: + CharType* get_buffer() override { return buffer_.get(); } + const CharType* get_buffer() const override { return buffer_.get(); } + std::size_t get_buffer_size() const override { if (buffer_ == nullptr) return 0; return buffer_size_; } + + public: + [[nodiscard]] std::expected begin_context_impl() final + { + if (buffer_ != nullptr) + return {}; + + CharType* alloc = new CharType[buffer_size_]; + if (alloc == nullptr) + return std::unexpected(FMTResult::Manager_AllocationFailed); + buffer_.reset(alloc); + return {}; + } + + [[nodiscard]] std::expected add_size(const std::size_t count) override { return resize(count + buffer_size_); } + [[nodiscard]] std::expected resize(const std::size_t target_buffer_size); + + protected: + std::unique_ptr buffer_ = nullptr; + std::size_t buffer_size_ = 0; + }; + + template + class ShrinkDynamicStreamIOManager : public DynamicStreamIOManager + { + public: + using Base = DynamicStreamIOManager; + using Base::DEFAULT_BEGIN_SIZE; + using Base::GROW_UP_BUFFER_SIZE; + using Base::DEBUG_RESIZE; + + using Base::get_buffer; + using Base::get_buffer_size; + using Base::resize; + + using Base::buffer_; + using Base::buffer_size_; + + static constexpr float MEAN_SIZE_OVERFLOW = 4.2f; + static constexpr float MEAN_SIZE_RESIZE = 1.4f; + static constexpr float MEAN_CALCFACT_OLD = 5; + static constexpr float MEAN_CALCFACT_LAST = 1; + + public: + ShrinkDynamicStreamIOManager(std::size_t beginSize = DEFAULT_BEGIN_SIZE) + : Base(beginSize) + , m_MeanGeneratedSize(beginSize) + {} + ~ShrinkDynamicStreamIOManager() override = default; + ShrinkDynamicStreamIOManager(ShrinkDynamicStreamIOManager&) = delete; + ShrinkDynamicStreamIOManager& operator=(ShrinkDynamicStreamIOManager&) = delete; + + protected: + void compute_generated_size_impl(std::size_t totalGeneratedLength) override + { + // WTF + m_MeanGeneratedSize = (m_MeanGeneratedSize * MEAN_CALCFACT_OLD + totalGeneratedLength * MEAN_CALCFACT_LAST) / (MEAN_CALCFACT_OLD + MEAN_CALCFACT_LAST); + } + + public: + [[nodiscard]] std::expected shrink_if_needed() + { + if (buffer_size_ > static_cast(m_MeanGeneratedSize * MEAN_SIZE_OVERFLOW)) + return resize(static_cast(m_MeanGeneratedSize * MEAN_SIZE_RESIZE)); + return {}; + } + + private: + std::size_t m_MeanGeneratedSize = 0; + }; + + template + [[nodiscard]] std::expected DynamicStreamIOManager::resize(const std::size_t target_buffer_size) + { + std::size_t new_buffer_size = target_buffer_size; + + if (buffer_size_ < target_buffer_size) + { + new_buffer_size = buffer_size_; + while (new_buffer_size < target_buffer_size) + new_buffer_size *= GROW_UP_BUFFER_SIZE; + } + + CharType* newBuffer = new CharType[new_buffer_size]; + if (newBuffer == nullptr) + return std::unexpected(FMTResult::Manager_AllocationFailed); + + std::memcpy(newBuffer, buffer_.get(), std::min(new_buffer_size, buffer_size_)); + + if constexpr (DEBUG_RESIZE) std::cout << "resize from " << buffer_size_ << " to " << new_buffer_size << std::endl; + + buffer_.reset(newBuffer); + buffer_size_ = new_buffer_size; + + return {}; + } +} diff --git a/src/stream/fmt/buf/streamio_manager/given_streamio_manager.h b/src/stream/fmt/buf/streamio_manager/given_streamio_manager.h new file mode 100644 index 00000000..4387289b --- /dev/null +++ b/src/stream/fmt/buf/streamio_manager/given_streamio_manager.h @@ -0,0 +1,42 @@ +#pragma once + +#include "basic_streamio_manager.h" + +namespace stream::fmt::buf +{ + template + class GivenStreamIOManager : public BasicStreamIOManager + { + public: + template + GivenStreamIOManager(CharType (&buffer)[SIZE]) + : buffer_(buffer) + , buffer_size_(SIZE) + {} + + GivenStreamIOManager(CharType* buffer, std::size_t buffer_size) + : buffer_(buffer) + , buffer_size_(buffer_size) + {} + + ~GivenStreamIOManager() override = default; + + GivenStreamIOManager(GivenStreamIOManager&) = delete; + GivenStreamIOManager& operator=(GivenStreamIOManager&) = delete; + + public: + CharType* get_buffer() override { return buffer_; } + const CharType* get_buffer() const override { return buffer_; } + std::size_t get_buffer_size() const override { return buffer_size_; } + + public: + [[nodiscard]] std::expected add_size(const std::size_t /* count */) override + { + return std::unexpected(FMTResult::Manager_StaticMemory); + } + + private: + CharType* buffer_; + std::size_t buffer_size_; + }; +} diff --git a/src/stream/fmt/buf/streamio_manager/static_streamio_manager.h b/src/stream/fmt/buf/streamio_manager/static_streamio_manager.h new file mode 100644 index 00000000..e97ead51 --- /dev/null +++ b/src/stream/fmt/buf/streamio_manager/static_streamio_manager.h @@ -0,0 +1,29 @@ +#pragma once + +#include "basic_streamio_manager.h" + +namespace stream::fmt::buf +{ + template + class StaticStreamIOManager : public BasicStreamIOManager + { + public: + ~StaticStreamIOManager() override = default; + StaticStreamIOManager(StaticStreamIOManager&) = delete; + StaticStreamIOManager& operator=(StaticStreamIOManager&) = delete; + + public: + CharType* get_buffer() override { return buffer_; } + const CharType* get_buffer() const override { return buffer_; } + std::size_t get_buffer_size() const override { return Count; } + + public: + [[nodiscard]] std::expected add_size(const std::size_t) override + { + return std::unexpected(FMTResult::Manager_StaticMemory); + } + + private: + CharType buffer_[Count]; + }; +} diff --git a/src/stream/fmt/buf/test_manip.h b/src/stream/fmt/buf/test_manip.h new file mode 100644 index 00000000..95df97a6 --- /dev/null +++ b/src/stream/fmt/buf/test_manip.h @@ -0,0 +1,180 @@ +#pragma once + +#include "stream/fmt/buf/stream.h" +#include "stream/fmt/buf/manip.h" + +namespace stream::fmt::buf +{ + template + class TestAccess + { + public: + constexpr inline TestAccess(const Stream& buffer) noexcept : buffer(buffer) {} + public: + const Stream& buffer; + + public: + constexpr inline bool is_equal_to(const TChar c) const noexcept { return buffer.get() == c; } + constexpr inline bool is_not_equal_to(const TChar c) const noexcept { return buffer.get() != c; } + template + constexpr inline bool is_equal_to(const TChar c, const CharToTest... ele) const noexcept + { + return is_equal_to(c) || is_equal_to(ele...); + } + template + constexpr inline bool is_not_equal_to(const TChar c, const CharToTest... ele) const noexcept + { + return is_not_equal_to(c) && is_not_equal_to(ele...); + } + + public: + constexpr inline bool IsLowerCase() const noexcept { return buffer.get() >= 'a' && buffer.get() <= 'z'; } + constexpr inline bool IsUpperCase() const noexcept { return buffer.get() >= 'A' && buffer.get() <= 'Z'; } + constexpr inline bool is_a_digit() const noexcept { return buffer.get() >= '0' && buffer.get() <= '9'; } + + public: + template + constexpr bool is_same(const CharToTest* str, std::size_t size) const noexcept + { + if (size > Access(buffer).get_buffer_remaining_size()) + { return false; } + + const TChar* bufferStr = buffer.current_pos; + bool is_same = true; + while (is_same && size != 0 && *str != 0) + { + is_same = *bufferStr++ == *str++; + --size; + } + if (size != 0) + { return false; } + return is_same; + } + template + constexpr inline bool is_same(std::basic_string_view sv) const noexcept + { + return is_same(sv.data(), sv.size()); + } + }; + + template + class TestManip + { + public: + constexpr inline TestManip(Stream& buffer) noexcept : buffer(buffer) {} + public: + Stream& buffer; + + using TConstChar = std::remove_const_t; + + public: + TestAccess access() const noexcept { return TestAccess(buffer); } + + public: + template + [[nodiscard]] constexpr inline std::expected is_equal_to_forward(const CharToTest... ele) noexcept + { + if (access().is_equal_to(ele...)) + { + SF_TRY(Manip(buffer).forward()); + return true; + } + return false; + } + template + [[nodiscard]] constexpr inline std::expected is_not_equal_forward(const CharToTest... ele) noexcept + { + if (access().is_not_equal_to(ele...)) + { + SF_TRY(Manip(buffer).forward()); + return true; + } + return false; + } + + public: + template + [[nodiscard]] constexpr std::expected is_same_forward(const CharToTest* str, std::size_t size) noexcept + { + if (access().is_same(str, size)) + { + SF_TRY(Manip(buffer).forward(size)); + return true; + } + return false; + } + template + [[nodiscard]] constexpr inline std::expected is_same_forward(std::basic_string_view sv) noexcept + { + if (access().is_same(sv)) + { + SF_TRY(Manip(buffer).forward(sv.size())); + return true; + } + return false; + } + + public: + template + [[nodiscard]] inline std::expected skip_one_of(const CharToTest... ele) noexcept + { + if (access().is_equal_to(ele...)) + { + SF_TRY(Manip(buffer).forward()); + return {}; + } + return std::unexpected(FMTResult::Parse_TokenNotExpected); + } + + template + inline void ignore_one_of(const CharToTest... ele) noexcept + { + if (access().is_equal_to(ele...) && Access(buffer).can_move_forward()) + { Manip(buffer).forward_force(); } + } + + template + inline void ignore_every(const CharToTest... ele) noexcept + { + while (access().is_equal_to(ele...) && Access(buffer).can_move_forward()) + { Manip(buffer).forward_force(); } + } + + public: + [[nodiscard]] inline void IgnoreOneSpace() noexcept { return ignore_one_of(' ', '\t'); } + [[nodiscard]] inline void IgnoreOneBlank() noexcept { return ignore_one_of(' ', '\t', '\n', '\r', '\v'); } + + inline void ignore_every_spaces() noexcept { ignore_every(' ', '\t'); } + inline void IgnoreEveryBlanks() noexcept { ignore_every(' ', '\t', '\n', '\r', '\v'); } + + public: + template + inline void GoTo(const CharToTest... ele) noexcept + { + while (access().is_not_equal_to(ele...) && Access(buffer).can_move_forward()) + Manip(buffer).forward_force(); + } + template + [[nodiscard]] inline std::expected go_to_forward(const CharToTest... ele) noexcept + { + GoTo(ele...); + return Manip(buffer).forward(); + } + + public: + template + [[nodiscard]] std::expected, FMTResult> ViewExec(Func&& func) + { + TChar* begin = buffer.current_pos; + SF_TRY(func()); + TChar* end = buffer.current_pos; + return std::basic_string_view(begin, end - begin); + } + + template + [[nodiscard]] inline std::expected, FMTResult> view_until(CharToTest&&... c) + { + return ViewExec([&] -> std::expected { TestManip(buffer).GoTo(std::forward(c)...); return {}; }); + } + }; +} diff --git a/src/stream/fmt/buf/utils/buffer_globber_manip.h b/src/stream/fmt/buf/utils/buffer_globber_manip.h new file mode 100644 index 00000000..906c761e --- /dev/null +++ b/src/stream/fmt/buf/utils/buffer_globber_manip.h @@ -0,0 +1,129 @@ +#pragma once + +#include "stream/fmt/buf/stream.h" +#include "stream/fmt/buf/manip.h" + +namespace stream::fmt::buf +{ + template + class Globber + { + public: + enum class PatternMatchType + { + MatchBiggest, + MatchSmallest + }; + + private: + [[nodiscard]] static std::expected buffer_exec_glob_(Stream& istream, Stream& glob) + { + if (Access(glob).is_end_of_string()) { return istream.current_pos; } + + if (Access(istream).is_end_of_string()) { return nullptr; } + + if (TestAccess(glob).is_equal_to('?')) + { + SF_TRY(Manip(glob).forward()); + SF_TRY(Manip(istream).forward()); + return buffer_exec_glob_(istream, glob); + } + else if (TestAccess(glob).is_equal_to('*')) + { + SF_TRY(Manip(glob).forward()); + const TChar* further = SF_TRY(buffer_exec_glob_(istream, glob)); + while (Access(istream).can_move_forward()) + { + SF_TRY(Manip(istream).forward()); + const TChar* last = SF_TRY(buffer_exec_glob_(istream, glob)); + if (last > further || further == nullptr) further = last; + } + return further; + } + else if (TestAccess(glob).is_equal_to('[')) + { + SF_TRY(Manip(istream).forward()); + const TChar* begin = glob.current_pos; + SF_TRY(TestManip(glob).go_to_forward(']')); + const TChar* end = glob.current_pos; + + StreamView charSet(begin, end - begin); + + bool is_inverted = SF_TRY(TestManip(glob).is_equal_to_forward('!')); + TChar toMatch = SF_TRY(Manip(istream).get_and_forward()); + bool found = false; + + while (found == false && Access(charSet).can_move_forward()) + { + if (TestAccess(charSet).is_equal_to(toMatch)) + { + found = true; + break; + } + + if (TestAccess(charSet).is_equal_to('-')) + { + TChar beginSubSet = Access(charSet).get_prev_force(); + TChar endSubSet = Access(charSet).get_next_force(); + if (toMatch >= beginSubSet && toMatch <= endSubSet) + { + found = true; + break; + } + } + + Manip(charSet).forward(); + } + + if (found && is_inverted == false) + return buffer_exec_glob_(istream, glob); + else if (found == false && is_inverted == true) + return buffer_exec_glob_(istream, glob); + return nullptr; + } + + if (istream.get() == glob.get()) + { + SF_TRY(Manip(glob).forward()); + SF_TRY(Manip(istream).forward()); + return buffer_exec_glob_(istream, glob); + } + return nullptr; + } + + public: + [[nodiscard]] static std::expected buffer_exec_glob(Stream& istream, Stream& glob, [[maybe_unused]] PatternMatchType patternMatchtype = PatternMatchType::MatchBiggest) + { + const TChar* furtherPointMatched = SF_TRY(buffer_exec_glob_(istream, glob)); + if (furtherPointMatched != nullptr) + istream.current_pos = furtherPointMatched; + return {}; + } + }; + + template + class BufferGlobberManip + { + public: + constexpr inline BufferGlobberManip(Stream& buffer) noexcept : buffer(buffer) {} + public: + Stream& buffer; + + public: + [[nodiscard]] std::expected FastReadCharPtrGlobber(std::basic_string_view globPattern, TChar* str, std::size_t sizeToCopy) + { + Stream globber(globPattern); + const TChar* begin = buffer.current_pos; + Globber::buffer_exec_glob(*this, globber); + const TChar* end = buffer.current_pos; + + Stream subContext(begin, end); + return ReadManip(subContext).FastReadCharPtr(str, sizeToCopy); + } + + [[nodiscard]] std::expected FastReadCharPtrRegex(std::basic_string_view regexPattern, TChar* str, std::size_t sizeToCopy) + { + return std::unexpected(FMTResult::FunctionNotImpl); + } + }; +} diff --git a/src/stream/fmt/buf/utils/buffer_shift_manip.h b/src/stream/fmt/buf/utils/buffer_shift_manip.h new file mode 100644 index 00000000..64e9c3b0 --- /dev/null +++ b/src/stream/fmt/buf/utils/buffer_shift_manip.h @@ -0,0 +1,102 @@ +#pragma once + +#include "stream/fmt/buf/stream.h" +#include "stream/fmt/buf/manip_io.h" + +namespace stream::fmt::buf +{ + template + class ShiftWriteManip + { + public: + ShiftWriteManip(StreamIO& buffer) : buffer(buffer) {} + public: + StreamIO& buffer; + + public: + [[nodiscard]] inline std::expected WriteShiftCenterBegin(detail::ShiftInfo& shift) + { + if (shift.type == detail::ShiftInfo::ShiftType::CenterRight || shift.type == detail::ShiftInfo::ShiftType::CenterLeft) + { + std::int32_t shift_ = shift.size / 2; + if (shift.type == detail::ShiftInfo::ShiftType::CenterLeft) shift_ = (shift.size + 1) / 2; + SF_TRY(ManipIO(buffer).pushback(shift.print.before, shift.size - shift_)); + shift.size = shift_; + } + + return {}; + } + + [[nodiscard]] inline std::expected WriteShiftCenterEnd(detail::ShiftInfo& shift) + { + if (shift.type == detail::ShiftInfo::ShiftType::CenterRight || shift.type == detail::ShiftInfo::ShiftType::CenterLeft) + return ManipIO(buffer).pushback(shift.print.after, shift.size); + return {}; + } + + [[nodiscard]] inline std::expected write_shift_right_all(detail::ShiftInfo& shift) + { + if (shift.type == detail::ShiftInfo::ShiftType::Right) + return ManipIO(buffer).pushback(shift.print.before, shift.size); + return {}; + } + + [[nodiscard]] inline std::expected WriteShiftLeftAll(detail::ShiftInfo& shift) + { + if (shift.type == detail::ShiftInfo::ShiftType::Left) + return ManipIO(buffer).pushback(shift.print.after, shift.size); + return {}; + } + + [[nodiscard]] inline std::expected write_shift_begin(detail::ShiftInfo& shift) + { + SF_TRY(WriteShiftCenterBegin(shift)); + return write_shift_right_all(shift); + } + + [[nodiscard]] inline std::expected write_shift_end(detail::ShiftInfo& shift) + { + SF_TRY(WriteShiftLeftAll(shift)); + return WriteShiftCenterEnd(shift); + } + }; + + template + class ShiftReadManip + { + public: + ShiftReadManip(Stream& buffer) : buffer(buffer) {} + public: + Stream& buffer; + + public: + [[nodiscard]] std::expected ignore_shift_begin_space(detail::ShiftInfo& shift) + { + if (shift.print.before_is_a_digit() == false) + return {}; + if (shift.type == detail::ShiftInfo::ShiftType::Right || shift.type == detail::ShiftInfo::ShiftType::CenterLeft || shift.type == detail::ShiftInfo::ShiftType::CenterRight) + { + + while (buffer.get() == ' ') + { + SF_TRY(Manip(buffer).forward()); + --shift.size; + } + } + return {}; + } + + [[nodiscard]] std::expected ignore_shift_end(detail::ShiftInfo& shift) + { + if (shift.type == detail::ShiftInfo::ShiftType::Left || shift.type == detail::ShiftInfo::ShiftType::CenterLeft || shift.type == detail::ShiftInfo::ShiftType::CenterRight) + { + while (buffer.get() == ' ' && shift.size > 0) + { + SF_TRY(Manip(buffer).forward()); + --shift.size; + } + } + return {}; + } + }; +} diff --git a/src/stream/fmt/buf/utils/buffer_utils.h b/src/stream/fmt/buf/utils/buffer_utils.h new file mode 100644 index 00000000..41856d32 --- /dev/null +++ b/src/stream/fmt/buf/utils/buffer_utils.h @@ -0,0 +1,130 @@ +#pragma once + +#include "stream/fmt/buf/stream.h" +#include "stream/fmt/buf/manip_io.h" +#include "stream/fmt/buf/test_manip.h" +#include "stream/fmt/buf/write_manip.h" +#include "stream/fmt/buf/read_manip.h" + +#include "stream/fmt/buf/streamio_manager/dynamic_streamio_manager.h" +#include "stream/fmt/buf/streamio_manager/given_streamio_manager.h" +#include "stream/fmt/buf/streamio_manager/static_streamio_manager.h" + +namespace stream::fmt::buf +{ + template + class UtilsManip + { + public: + constexpr inline UtilsManip(Stream& buffer_) noexcept : buffer(buffer_) {} + public: + Stream& buffer; + + using TConstChar = std::remove_const_t; + + public: + template + [[nodiscard]] std::expected get_word_from_list(const std::basic_string_view (&data)[SIZE]) + { + for (std::size_t idx = 0; idx < SIZE; ++idx) + { + bool found = SF_TRY(TestManip(buffer).is_same_forward(data[idx])); + if (found) return idx; + } + return std::unexpected(FMTResult::Specifiers_Invalid); + } + + // TODO: use static map ? + template + using DictPairs = std::pair, T>; + + template + [[nodiscard]] std::expected get_word_from_dict_pairs(const DictPairs (&data)[SIZE]) + { + for (std::size_t idx = 0; idx < SIZE; ++idx) + { + bool found = SF_TRY(TestManip(buffer).is_same_forward(data[idx].first)); + if (found) + return data[idx].second; + } + return std::unexpected(FMTResult::Specifiers_Invalid); + } + }; + + namespace utils + { + template + [[nodiscard]] static std::expected parse_escaped_quoted_string(buf::Stream& buffer, buf::StreamIO& stringOut) + { + SF_TRY(buf::TestManip(buffer).skip_one_of('"')); + while (buf::Access(buffer).is_end_of_string() == false) + { + auto view = SF_TRY(buf::TestManip(buffer).view_until('"', '\\')); + SF_TRY(buf::WriteManip(stringOut).fast_write_string(view)); + + if (buf::TestAccess(buffer).is_equal_to('"')) + { break; } + + SF_TRY(buf::TestManip(buffer).skip_one_of('\\')); + switch (buffer.get()) + { + // TODO : Do all others escape char + case '"': + SF_TRY(buf::ManipIO(stringOut).pushback('"')); + break; + case 't': + SF_TRY(buf::ManipIO(stringOut).pushback('\t')); + break; + case 'r': + SF_TRY(buf::ManipIO(stringOut).pushback('\r')); + break; + case 'n': + SF_TRY(buf::ManipIO(stringOut).pushback('\n')); + break; + default: + break; + } + } + SF_TRY(buf::TestManip(buffer).skip_one_of('"')); + + return {}; + } + + template + [[nodiscard]] static std::expected format_escaped_quoted_string(buf::StreamIO& buffer, buf::Stream& string_in) + { + SF_TRY(buf::ManipIO(buffer).pushback('"')); + while (buf::Access(string_in).is_end_of_string() == false) + { + auto view = SF_TRY(buf::TestManip(string_in).view_until('\\')); + SF_TRY(buf::WriteManip(buffer).fast_write_string(view)); + + if (buf::Access(string_in).is_end_of_string()) break; + + // TODO + SF_TRY(buf::TestManip(string_in).skip_one_of('\\')); + switch (string_in.get()) + { + // TODO : Do all others escape char + case '"': + SF_TRY(buf::ManipIO(buffer).pushback('"')); + break; + case 't': + SF_TRY(buf::ManipIO(buffer).pushback('\t')); + break; + case 'r': + SF_TRY(buf::ManipIO(buffer).pushback('\r')); + break; + case 'n': + SF_TRY(buf::ManipIO(buffer).pushback('\n')); + break; + default: + break; + } + } + SF_TRY(buf::ManipIO(buffer).pushback('"')); + + return {}; + } + }; +} diff --git a/src/stream/fmt/buf/write_manip.h b/src/stream/fmt/buf/write_manip.h new file mode 100644 index 00000000..dec65c41 --- /dev/null +++ b/src/stream/fmt/buf/write_manip.h @@ -0,0 +1,172 @@ +#pragma once + +#include "stream.h" +#include "manip.h" +#include "test_manip.h" +#include "manip_io.h" + +#include +#include + +namespace stream::fmt::buf +{ + class WriteUtils + { + public: + template + static std::int32_t get_number_of_digit_dec(T value) + { + if constexpr (std::numeric_limits::is_signed) + { + if (value < 0) value = -value; + } + std::int32_t nb = 0; + while (true) + { + if (value < 10) + return nb + 1; + else if (value < 100) + return nb + 2; + else if (value < 1000) + return nb + 3; + else if (value < 10000) + return nb + 4; + else + { + value /= static_cast(10000); + nb += 4; + } + } + } + }; + + template + class WriteManip + { + public: + constexpr inline WriteManip(StreamIO& buffer) noexcept : buffer(buffer) {} + public: + StreamIO& buffer; + + public: + static constexpr TChar BIN[2] = {'0', '1'}; + static constexpr TChar OCT[8] = {'0', '1', '2', '3', '4', '5', '6', '7'}; + static constexpr TChar UPPER_HEX[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'b', 'C', 'D', 'E', 'F'}; + static constexpr TChar LOWER_HEX[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; + + public: + template + requires std::is_integral_v + [[nodiscard]] constexpr std::expected fast_write_integer(T i) + { + ManipIO manip(buffer); + + if (i == 0) { SF_TRY(manip.pushback('0')); return {}; } + + if constexpr (std::is_signed_v) + { + if (i < 0) { SF_TRY(manip.pushback('-')); i = -i; } + } + + std::int32_t nb_digit = WriteUtils::get_number_of_digit_dec(i); + SF_TRY(manip.forward(nb_digit)); + while (i > 0) + { + ManipIO(buffer).set(i % 10 + '0'); + Manip(buffer).backward_force(); + i /= 10; + } + SF_TRY(manip.forward(nb_digit)); + + return {}; + } + + public: + template + requires std::is_floating_point_v + [[nodiscard]] constexpr std::expected fast_write_float(T i, std::int32_t float_precision = 2) + { + ManipIO manip(buffer); + + if (i == 0) + { SF_TRY(manip.pushback('0')); return {}; } + if (i < 0) + { SF_TRY(manip.pushback('-')); i = -i; } + + T k = std::trunc(i); + i = i - k; + std::int32_t nb_digit = WriteUtils::get_number_of_digit_dec(k); + SF_TRY(manip.forward(nb_digit)); + std::int32_t nb_digit_ = nb_digit; + while (nb_digit_ > 0) + { + buffer.set(char(std::fmod(k, 10)) + '0'); + Manip(buffer).backward_force(); + k /= 10; + nb_digit_--; + } + SF_TRY(manip.forward(nb_digit)); + SF_TRY(manip.pushback('.')); + + while (float_precision-- >= 0) + { + TChar intPart = static_cast(std::trunc(i *= 10)); + SF_TRY(manip.pushback(intPart + '0')); + i -= intPart; + } + + return {}; + } + + public: + template + [[nodiscard]] constexpr std::expected fast_write_char_array(const CharInput* str, std::size_t size) + { + auto reserve = ManipIO(buffer).reserve(size); + if (reserve.has_value() == false) + return fast_write_char_array(str, Access(buffer).get_buffer_remaining_size()); + + // TODO: Opti with bigger types + while (size-- != 0 && *str != 0) + ManipIO(buffer).pushback_force(*str++); + + return {}; + } + template + [[nodiscard]] inline constexpr std::expected fast_write_string(std::basic_string_view sv) + { + return fast_write_char_array(sv.data(), sv.size()); + } + [[nodiscard]] inline std::expected fast_write_string(std::basic_string_view sv) + { + return fast_write_char_array(sv.data(), sv.size()); + } + template + [[nodiscard]] inline std::expected fast_write_string_literal(CharInput (&str)[SIZE]) + { + std::size_t size = SIZE; + while (str[size - 1] == 0) + { --size; } + return fast_write_char_array(str, size); + } + + public: + template + [[nodiscard]] inline std::expected basic_write_type(std::basic_string_view str) { return fast_write_string(str); } + template + [[nodiscard]] inline std::expected basic_write_type(CharInput (&str)[SIZE]) { return fast_write_string_literal(str); } + template requires std::is_integral_v + [[nodiscard]] inline std::expected basic_write_type(T t) { return fast_write_integer(t); } + template requires std::is_floating_point_v + [[nodiscard]] inline std::expected basic_write_type(T t) { return fast_write_float(t); } + + template + [[nodiscard]] inline std::expected basic_write_type(Type&& type, Rest&&... rest) + { + SF_TRY(basic_write_type(type)); + if constexpr (sizeof...(rest) > 0) + SF_TRY(basic_write_type(std::forward(rest)...)); + return {}; + } + }; +} diff --git a/src/stream/fmt/buffer/buffer_info.h b/src/stream/fmt/buffer/buffer_info.h deleted file mode 100644 index 9aca210a..00000000 --- a/src/stream/fmt/buffer/buffer_info.h +++ /dev/null @@ -1,85 +0,0 @@ -#pragma once - -#include "stream/fmt/detail/prelude.h" - -namespace stream::fmt::detail -{ - template - class BufferInfo - { - public: - using TChar = CharType; - - public: - TChar* Buffer; - TChar* CurrentPos; - TChar* BufferEnd; // Not included - - public: - constexpr inline TChar Get() const { return *CurrentPos; } - template typename TManip> constexpr inline TManip Manip() { return TManip(buffer); } - - public: - BufferInfo() noexcept - : Buffer(nullptr) - , CurrentPos(nullptr) - , BufferEnd(nullptr) - {} - - BufferInfo(TChar* const buffer, const std::size_t size) noexcept - : Buffer(buffer) - , CurrentPos(buffer) - , BufferEnd(buffer + size) - {} - }; - - template - class BufferInfoView : public BufferInfo - { - public: - using typename BufferInfo::TChar; - - using BufferInfo::Buffer; - using BufferInfo::CurrentPos; - using BufferInfo::BufferEnd; - - using BufferInfo::Get; - using BufferInfo::Manip; - - public: - BufferInfoView() noexcept - : BufferInfo() - {} - - template - BufferInfoView(const CharType (&data)[SIZE]) noexcept - : BufferInfo(data, SIZE) - { - while (BufferEnd - 1 > Buffer && *(BufferEnd - 1) == 0) - --BufferEnd; - } - - BufferInfoView(std::basic_string_view sv) noexcept - : BufferInfo(sv.data(), sv.size()) - {} - - BufferInfoView(const CharType* const buffer, const std::size_t size) noexcept - : BufferInfo(buffer, size) - {} - - public: - operator BufferInfo() const { return BufferInfo {.buffer = Buffer, .CurrentPos = CurrentPos, .BufferEnd = BufferEnd}; } - }; - - template - concept ConvertibleToBufferInfo = requires(T&& t) - { - BufferInfo(std::forward(t)); - }; - - template - concept ConvertibleToBufferInfoView = requires(T&& t) - { - BufferInfoView(std::forward(t)); - }; -} diff --git a/src/stream/fmt/buffer/buffer_manip.h b/src/stream/fmt/buffer/buffer_manip.h deleted file mode 100644 index 37fa8873..00000000 --- a/src/stream/fmt/buffer/buffer_manip.h +++ /dev/null @@ -1,105 +0,0 @@ -#pragma once - -#include "buffer_info.h" - -namespace stream::fmt::detail -{ - template - class BufferAccess - { - public: - constexpr inline BufferAccess(const BufferInfo& buffer) noexcept : Buffer(buffer) {} - public: - const BufferInfo& Buffer; - - public: - constexpr inline std::size_t GetBufferTotalSize() const noexcept { return static_cast(Buffer.BufferEnd - Buffer.buffer); } - constexpr inline std::size_t GetBufferCurrentSize() const noexcept { return static_cast(Buffer.CurrentPos - Buffer.buffer); } - constexpr inline std::size_t GetBufferRemainingSize() const noexcept { return static_cast(Buffer.BufferEnd - Buffer.CurrentPos); } - - public: - constexpr inline bool CanMoveForward(const std::size_t count = 1) const noexcept { return Buffer.CurrentPos + count <= Buffer.BufferEnd; } - constexpr inline bool CanMoveBackward(const std::size_t count = 1) const noexcept { return Buffer.CurrentPos - count >= Buffer.buffer; } - - constexpr inline bool IsOutOfBound() const noexcept { return Buffer.CurrentPos < Buffer.buffer || Buffer.CurrentPos >= Buffer.BufferEnd; } - constexpr inline bool IsEmpty() const noexcept { return Buffer.CurrentPos >= Buffer.BufferEnd; } - constexpr inline bool IsEndOfString() const noexcept { return IsEmpty() || Buffer.Get() == 0; } - - [[nodiscard]] constexpr inline std::expected, FMTResult> GetNext(const std::size_t count = 1) const - { - if (BufferAccess(buffer).CanMoveForward(count) == false) - return std::unexpected(FMTResult::Buffer_OutOfBoundAccess); - return BufferManip(buffer).GetNextForce(count); - } - [[nodiscard]] constexpr inline std::expected, FMTResult> GetPrev(const std::size_t count = 1) const - { - if (BufferAccess(buffer).CanMoveBackward(count) == false) - return std::unexpected(FMTResult::Buffer_OutOfBoundAccess); - return BufferManip(buffer).GetPrevForce(count); - } - - constexpr inline TChar GetNextForce(const std::size_t count = 1) const noexcept { return *(Buffer.CurrentPos + count); } - constexpr inline TChar GetPrevForce(const std::size_t count = 1) const noexcept { return *(Buffer.CurrentPos - count); } - }; - - template - class BufferManip - { - public: - constexpr inline BufferManip(BufferInfo& buffer) noexcept : Buffer(buffer) {} - public: - BufferInfo& Buffer; - - public: - constexpr inline void Set(TChar* const buffer, const std::size_t size) noexcept - { - Buffer.buffer = buffer; - Buffer.CurrentPos = buffer; - Buffer.BufferEnd = buffer + size; - } - - constexpr inline void Reload(BufferInfo& buffer) noexcept - { - Buffer.buffer = buffer.buffer; - Buffer.CurrentPos = buffer.CurrentPos; - Buffer.BufferEnd = buffer.BufferEnd; - } - - BufferAccess Access() { return BufferAccess(buffer); } - - public: - constexpr inline void ForceForward(const std::size_t count = 1) noexcept { Buffer.CurrentPos += count; } - [[nodiscard]] constexpr inline std::expected Forward(const std::size_t count = 1) noexcept - { - if (!Access().CanMoveForward(count)) - return std::unexpected(FMTResult::Buffer_OutOfBoundAccess); - Buffer.CurrentPos += count; - return {}; - } - - constexpr inline void ForceBackward(const std::size_t count = 1) noexcept { Buffer.CurrentPos -= count; } - [[nodiscard]] constexpr inline std::expected Backward(const std::size_t count = 1) noexcept - { - if (!Access().CanMoveBackward(count)) - return std::unexpected(FMTResult::Buffer_OutOfBoundAccess); - Buffer.CurrentPos -= count; - return {}; - } - - [[nodiscard]] constexpr inline std::expected, FMTResult> GetAndForward() - { - if (BufferAccess(buffer).CanMoveForward(1) == false) - return std::unexpected(FMTResult::Buffer_OutOfBoundAccess); - return *Buffer.CurrentPos++; - } - [[nodiscard]] constexpr inline std::expected, FMTResult> GetAndBackward() - { - if (BufferAccess(buffer).CanMoveBackward(1) == false) - return std::unexpected(FMTResult::Buffer_OutOfBoundAccess); - return *Buffer.CurrentPos--; - } - - constexpr inline TChar GetAndForceForward() noexcept { return *Buffer.CurrentPos++; } - constexpr inline TChar GetAndForceBackward() noexcept { return *Buffer.CurrentPos--; } - }; -} diff --git a/src/stream/fmt/buffer/buffer_out_manager/basic_buffer_out_manager.h b/src/stream/fmt/buffer/buffer_out_manager/basic_buffer_out_manager.h deleted file mode 100644 index 2d714756..00000000 --- a/src/stream/fmt/buffer/buffer_out_manager/basic_buffer_out_manager.h +++ /dev/null @@ -1,55 +0,0 @@ -#pragma once - -#include "stream/fmt/detail/prelude.h" -#include "stream/fmt/buffer/buffer_info.h" - -namespace stream::fmt::detail -{ - template - class BasicBufferOutManager - { - public: - BasicBufferOutManager() = default; - virtual ~BasicBufferOutManager() = default; - BasicBufferOutManager(BasicBufferOutManager&) = delete; - BasicBufferOutManager& operator=(BasicBufferOutManager&) = delete; - - protected: - [[nodiscard]] virtual std::expected BeginContextImpl() { return {}; } - virtual void ComputeGeneratedSizeImpl(const std::size_t /* totalGeneratedLength */) {} - - public: - [[nodiscard]] std::expected BeginContext() { return BeginContextImpl(); } - void ComputeGeneratedSize(std::size_t totalGeneratedLength) - { - ComputeGeneratedSizeImpl(totalGeneratedLength); - SetLastGeneratedDataSize(totalGeneratedLength); - } - - public: - virtual CharType* GetBuffer() = 0; - virtual const CharType* GetBuffer() const = 0; - virtual std::size_t GetBufferSize() const = 0; - - public: - [[nodiscard]] virtual std::expected AddSize(const std::size_t count) = 0; - - public: - BufferInfoView GetLastGeneratedBufferInfoView() const { return BufferInfoView(GetBuffer(), m_LastGeneratedDataSize); } - operator BufferInfoView() const { return GetLastGeneratedBufferInfoView(); } - - std::basic_string_view GetLastGeneratedStringView() const { return std::basic_string_view(GetBuffer(), m_LastGeneratedDataSize); } - operator std::basic_string_view() const { return GetLastGeneratedStringView(); } - std::basic_string GetLastGeneratedString() const { return std::basic_string(GetBuffer(), m_LastGeneratedDataSize); } - operator std::basic_string() const { return GetLastGeneratedString(); } - - public: - std::size_t GetLastGeneratedDataSize() const { return m_LastGeneratedDataSize; } - - private: - void SetLastGeneratedDataSize(const std::size_t size) { m_LastGeneratedDataSize = size; } - - protected: - std::size_t m_LastGeneratedDataSize{0}; - }; -} diff --git a/src/stream/fmt/buffer/buffer_out_manager/dynamic_buffer_out_manager.h b/src/stream/fmt/buffer/buffer_out_manager/dynamic_buffer_out_manager.h deleted file mode 100644 index fbe81d12..00000000 --- a/src/stream/fmt/buffer/buffer_out_manager/dynamic_buffer_out_manager.h +++ /dev/null @@ -1,128 +0,0 @@ -#pragma once - -#include "basic_buffer_out_manager.h" - -#include -#include -#include - -namespace stream::fmt::detail -{ - template - class DynamicBufferOutManager : public BasicBufferOutManager - { - public: - DynamicBufferOutManager(std::size_t beginSize = DEFAULT_BEGIN_SIZE) - : m_BufferSize(beginSize) - {} - - ~DynamicBufferOutManager() override = default; - DynamicBufferOutManager(DynamicBufferOutManager&) = delete; - DynamicBufferOutManager& operator=(DynamicBufferOutManager&) = delete; - - public: - static constexpr std::size_t DEFAULT_BEGIN_SIZE = 128; - static constexpr std::size_t GROW_UP_BUFFER_SIZE = 2; - static constexpr bool DEBUG_RESIZE = false; - - public: - CharType* GetBuffer() override { return m_Buffer.get(); } - const CharType* GetBuffer() const override { return m_Buffer.get(); } - std::size_t GetBufferSize() const override { if (m_Buffer == nullptr) return 0; return m_BufferSize; } - - public: - [[nodiscard]] std::expected BeginContextImpl() final - { - if (m_Buffer != nullptr) - return {}; - - CharType* alloc = new CharType[m_BufferSize]; - if (alloc == nullptr) - return std::unexpected(FMTResult::Manager_AllocationFailed); - m_Buffer.reset(alloc); - return {}; - } - - [[nodiscard]] std::expected AddSize(const std::size_t count) override { return Resize(count + m_BufferSize); } - [[nodiscard]] std::expected Resize(const std::size_t targetBufferSize); - - protected: - std::unique_ptr m_Buffer = nullptr; - std::size_t m_BufferSize = 0; - }; - - template - class ShrinkDynamicBufferOutManager : public DynamicBufferOutManager - { - public: - using Base = DynamicBufferOutManager; - using Base::DEFAULT_BEGIN_SIZE; - using Base::GROW_UP_BUFFER_SIZE; - using Base::DEBUG_RESIZE; - - using Base::GetBuffer; - using Base::GetBufferSize; - using Base::Resize; - - using Base::m_Buffer; - using Base::m_BufferSize; - - static constexpr float MEAN_SIZE_OVERFLOW = 4.2f; - static constexpr float MEAN_SIZE_RESIZE = 1.4f; - static constexpr float MEAN_CALCFACT_OLD = 5; - static constexpr float MEAN_CALCFACT_LAST = 1; - - public: - ShrinkDynamicBufferOutManager(std::size_t beginSize = DEFAULT_BEGIN_SIZE) - : Base(beginSize) - , m_MeanGeneratedSize(beginSize) - {} - ~ShrinkDynamicBufferOutManager() override = default; - ShrinkDynamicBufferOutManager(ShrinkDynamicBufferOutManager&) = delete; - ShrinkDynamicBufferOutManager& operator=(ShrinkDynamicBufferOutManager&) = delete; - - protected: - void ComputeGeneratedSizeImpl(std::size_t totalGeneratedLength) override - { - // WTF - m_MeanGeneratedSize = (m_MeanGeneratedSize * MEAN_CALCFACT_OLD + totalGeneratedLength * MEAN_CALCFACT_LAST) / (MEAN_CALCFACT_OLD + MEAN_CALCFACT_LAST); - } - - public: - [[nodiscard]] std::expected ShrinkIfNeeded() - { - if (m_BufferSize > static_cast(m_MeanGeneratedSize * MEAN_SIZE_OVERFLOW)) - return Resize(static_cast(m_MeanGeneratedSize * MEAN_SIZE_RESIZE)); - return {}; - } - - private: - std::size_t m_MeanGeneratedSize = 0; - }; - - template - [[nodiscard]] std::expected DynamicBufferOutManager::Resize(const std::size_t targetBufferSize) - { - std::size_t newBufferSize = targetBufferSize; - - if (m_BufferSize < targetBufferSize) - { - newBufferSize = m_BufferSize; - while (newBufferSize < targetBufferSize) - newBufferSize *= GROW_UP_BUFFER_SIZE; - } - - CharType* newBuffer = new CharType[newBufferSize]; - if (newBuffer == nullptr) - return std::unexpected(FMTResult::Manager_AllocationFailed); - - std::memcpy(newBuffer, m_Buffer.get(), std::min(newBufferSize, m_BufferSize)); - - if constexpr (DEBUG_RESIZE) std::cout << "Resize from " << m_BufferSize << " to " << newBufferSize << std::endl; - - m_Buffer.reset(newBuffer); - m_BufferSize = newBufferSize; - - return {}; - } -} diff --git a/src/stream/fmt/buffer/buffer_out_manager/given_buffer_out_manager.h b/src/stream/fmt/buffer/buffer_out_manager/given_buffer_out_manager.h deleted file mode 100644 index 70949cae..00000000 --- a/src/stream/fmt/buffer/buffer_out_manager/given_buffer_out_manager.h +++ /dev/null @@ -1,42 +0,0 @@ -#pragma once - -#include "basic_buffer_out_manager.h" - -namespace stream::fmt::detail -{ - template - class GivenBufferOutManager : public BasicBufferOutManager - { - public: - template - GivenBufferOutManager(CharType (&buffer)[SIZE]) - : m_Buffer(buffer) - , m_BufferSize(SIZE) - {} - - GivenBufferOutManager(CharType* buffer, std::size_t bufferSize) - : m_Buffer(buffer) - , m_BufferSize(bufferSize) - {} - - ~GivenBufferOutManager() override = default; - - GivenBufferOutManager(GivenBufferOutManager&) = delete; - GivenBufferOutManager& operator=(GivenBufferOutManager&) = delete; - - public: - CharType* GetBuffer() override { return m_Buffer; } - const CharType* GetBuffer() const override { return m_Buffer; } - std::size_t GetBufferSize() const override { return m_BufferSize; } - - public: - [[nodiscard]] std::expected AddSize(const std::size_t /* count */) override - { - return std::unexpected(FMTResult::Manager_StaticMemory); - } - - private: - CharType* m_Buffer; - std::size_t m_BufferSize; - }; -} diff --git a/src/stream/fmt/buffer/buffer_out_manager/static_buffer_out_manager.h b/src/stream/fmt/buffer/buffer_out_manager/static_buffer_out_manager.h deleted file mode 100644 index 4b1859f9..00000000 --- a/src/stream/fmt/buffer/buffer_out_manager/static_buffer_out_manager.h +++ /dev/null @@ -1,29 +0,0 @@ -#pragma once - -#include "basic_buffer_out_manager.h" - -namespace stream::fmt::detail -{ - template - class StaticBufferOutManager : public BasicBufferOutManager - { - public: - ~StaticBufferOutManager() override = default; - StaticBufferOutManager(StaticBufferOutManager&) = delete; - StaticBufferOutManager& operator=(StaticBufferOutManager&) = delete; - - public: - CharType* GetBuffer() override { return m_Buffer; } - const CharType* GetBuffer() const override { return m_Buffer; } - std::size_t GetBufferSize() const override { return Count; } - - public: - [[nodiscard]] std::expected AddSize(const std::size_t) override - { - return std::unexpected(FMTResult::Manager_StaticMemory); - } - - private: - CharType m_Buffer[Count]; - }; -} diff --git a/src/stream/fmt/buffer/buffer_out_manip.h b/src/stream/fmt/buffer/buffer_out_manip.h deleted file mode 100644 index 542e131a..00000000 --- a/src/stream/fmt/buffer/buffer_out_manip.h +++ /dev/null @@ -1,139 +0,0 @@ -#pragma once - -#include "buffer_info.h" -#include "buffer_manip.h" - -#include "buffer_out_manager/basic_buffer_out_manager.h" - -namespace stream::fmt::detail -{ - template - class BufferOutInfo : public BufferInfo - { - public: - using typename BufferInfo::TChar; - - using BufferInfo::Buffer; - using BufferInfo::CurrentPos; - using BufferInfo::BufferEnd; - - using BufferInfo::Get; - using BufferInfo::Manip; - - protected: - BufferOutInfo(BasicBufferOutManager& bufferOutManager) noexcept - : BufferInfo() - , Manager(bufferOutManager) - {} - - protected: - [[nodiscard]] static std::expected Init(BufferOutInfo& in) - { - SF_TRY(in.Manager.BeginContext()); - BufferManip(in).Set(in.Manager.GetBuffer(), in.Manager.GetBufferSize()); - return {}; - } - - public: - [[nodiscard]] static std::expected, FMTResult> Create(BasicBufferOutManager& bufferOutManager) - { - BufferOutInfo res(bufferOutManager); - SF_TRY(Init(res)); - return res; - } - - public: - BasicBufferOutManager& Manager; - }; - - template - concept ConvertibleToBufferOutInfo = requires(T&& t) - { - BufferOutInfo(std::forward(t)); - }; - - template - class BufferOutManip - { - public: - constexpr inline BufferOutManip(BufferOutInfo& buffer) noexcept : Buffer(buffer) {} - public: - BufferOutInfo& Buffer; - - public: - void ComputeGeneratedSize() noexcept { Buffer.Manager.ComputeGeneratedSize(BufferAccess(buffer).GetBufferCurrentSize()); } - - public: - [[nodiscard]] std::expected AddSize(const std::size_t count) noexcept - { - std::size_t currentSize = BufferAccess(buffer).GetBufferCurrentSize(); - SF_TRY(Buffer.Manager.AddSize(count)) - BufferManip(buffer).Set(Buffer.Manager.GetBuffer(), Buffer.Manager.GetBufferSize()); - Buffer.CurrentPos = Buffer.Manager.GetBuffer() + currentSize; - return {}; - } - - [[nodiscard]] inline std::expected Reserve(const std::size_t count = 1) noexcept - { - if (Buffer.CurrentPos + count <= Buffer.BufferEnd) - return {}; - return AddSize(static_cast(count)); - } - - [[nodiscard]] inline std::expected Forward(const std::size_t count = 1) noexcept - { - SF_TRY(Reserve(count)); - Buffer.CurrentPos += count; - return {}; - } - - public: - inline void SetChar(const TChar c) noexcept { *Buffer.CurrentPos = c; } - [[nodiscard]] inline std::expected Pushback(const TChar c) noexcept - { - SF_TRY(Reserve(1)); - *Buffer.CurrentPos++ = c; - return {}; - } - [[nodiscard]] inline std::expected SetInverse(const TChar c) noexcept - { - SF_TRY(BufferAccess(buffer).CanMoveBackward(1)); - *--Buffer.CurrentPos = c; - return {}; - } - inline void ForcePushback(const TChar c) noexcept { *Buffer.CurrentPos++ = c; } - inline void ForceSetInverse(const TChar c) noexcept { *--Buffer.CurrentPos = c; } - - public: - [[nodiscard]] inline std::expected Pushback(const TChar c, auto count) noexcept - { - SF_TRY(Reserve(count)) - while (count-- > 0) - ForcePushback(c); - return {}; - } - - public: - [[nodiscard]] inline std::expected AddSpaces(const auto count) noexcept - { - return Pushback(' ', count); - } - - private: - template - inline void PushbackSeqImpl(const TChar c, const Rest... rest) noexcept - { - ForcePushback(c); - if constexpr (sizeof...(rest) > 0) PushbackSeqImpl(rest...); - } - - public: - template - [[nodiscard]] inline std::expected PushbackSeq(const CharToPush... ele) noexcept - { - SF_TRY(Reserve(sizeof...(ele))) - PushbackSeqImpl(ele...); - return {}; - } - }; -} diff --git a/src/stream/fmt/buffer/buffer_test_manip.h b/src/stream/fmt/buffer/buffer_test_manip.h deleted file mode 100644 index fd36d4e3..00000000 --- a/src/stream/fmt/buffer/buffer_test_manip.h +++ /dev/null @@ -1,185 +0,0 @@ -#pragma once - -#include "stream/fmt/buffer/buffer_info.h" -#include "stream/fmt/buffer/buffer_manip.h" - -namespace stream::fmt::detail -{ - template - class BufferTestAccess - { - public: - constexpr inline BufferTestAccess(const BufferInfo& buffer) noexcept : Buffer(buffer) {} - public: - const BufferInfo& Buffer; - - public: - constexpr inline bool IsEqualTo(const TChar c) const noexcept { return Buffer.Get() == c; } - constexpr inline bool IsNotEqualTo(const TChar c) const noexcept { return Buffer.Get() != c; } - template - constexpr inline bool IsEqualTo(const TChar c, const CharToTest... ele) const noexcept - { - return IsEqualTo(c) || IsEqualTo(ele...); - } - template - constexpr inline bool IsNotEqualTo(const TChar c, const CharToTest... ele) const noexcept - { - return IsNotEqualTo(c) && IsNotEqualTo(ele...); - } - - constexpr inline bool NextIsEqualTo(const TChar c) const noexcept { return BufferAccess(buffer).GetNextForce() + 1 == c; } - constexpr inline bool NextIsNotEqualTo(const TChar c) const noexcept { return BufferAccess(buffer).GetNextForce() + 1 != c; } - constexpr inline bool PrevIsEqualTo(const TChar c) const noexcept { return BufferAccess(buffer).GetPrevForce() - 1 == c; } - constexpr inline bool PrevIsNotEqualTo(const TChar c) const noexcept { return BufferAccess(buffer).GetPrevForce() - 1 != c; } - - public: - constexpr inline bool IsLowerCase() const noexcept { return Buffer.Get() >= 'a' && Buffer.Get() <= 'z'; } - constexpr inline bool IsUpperCase() const noexcept { return Buffer.Get() >= 'A' && Buffer.Get() <= 'Z'; } - constexpr inline bool IsADigit() const noexcept { return Buffer.Get() >= '0' && Buffer.Get() <= '9'; } - - public: - template - constexpr bool IsSame(const CharToTest* str, std::size_t size) const noexcept - { - if (size > BufferAccess(buffer).GetBufferRemainingSize()) - { return false; } - - const TChar* bufferStr = Buffer.CurrentPos; - bool isSame = true; - while (isSame && size != 0 && *str != 0) - { - isSame = *bufferStr++ == *str++; - --size; - } - if (size != 0) - { return false; } - return isSame; - } - template - constexpr inline bool IsSame(std::basic_string_view sv) const noexcept - { - return IsSame(sv.data(), sv.size()); - } - }; - - template - class BufferTestManip - { - public: - constexpr inline BufferTestManip(BufferInfo& buffer) noexcept : Buffer(buffer) {} - public: - BufferInfo& Buffer; - - using TConstChar = std::remove_const_t; - - public: - BufferTestAccess Access() const noexcept { return BufferTestAccess(buffer); } - - public: - template - [[nodiscard]] constexpr inline std::expected IsEqualToForward(const CharToTest... ele) noexcept - { - if (Access().IsEqualTo(ele...)) - { - SF_TRY(BufferManip(buffer).Forward()); - return true; - } - return false; - } - template - [[nodiscard]] constexpr inline std::expected IsNotEqualForward(const CharToTest... ele) noexcept - { - if (Access().IsNotEqualTo(ele...)) - { - SF_TRY(BufferManip(buffer).Forward()); - return true; - } - return false; - } - - public: - template - [[nodiscard]] constexpr std::expected is_same_forward(const CharToTest* str, std::size_t size) noexcept - { - if (Access().IsSame(str, size)) - { - SF_TRY(BufferManip(buffer).Forward(size)); - return true; - } - return false; - } - template - [[nodiscard]] constexpr inline std::expected is_same_forward(std::basic_string_view sv) noexcept - { - if (Access().IsSame(sv)) - { - SF_TRY(BufferManip(buffer).Forward(sv.size())); - return true; - } - return false; - } - - public: - template - [[nodiscard]] inline std::expected SkipOneOf(const CharToTest... ele) noexcept - { - if (Access().IsEqualTo(ele...)) - { - SF_TRY(BufferManip(buffer).Forward()); - return {}; - } - return std::unexpected(FMTResult::Parse_TokenNotExpected); - } - - template - inline void IgnoreOneOf(const CharToTest... ele) noexcept - { - if (Access().IsEqualTo(ele...) && BufferAccess(buffer).CanMoveForward()) - { BufferManip(buffer).ForceForward(); } - } - - template - inline void IgnoreEvery(const CharToTest... ele) noexcept - { - while (Access().IsEqualTo(ele...) && BufferAccess(buffer).CanMoveForward()) - { BufferManip(buffer).ForceForward(); } - } - - public: - [[nodiscard]] inline void IgnoreOneSpace() noexcept { return IgnoreOneOf(' ', '\t'); } - [[nodiscard]] inline void IgnoreOneBlank() noexcept { return IgnoreOneOf(' ', '\t', '\n', '\r', '\v'); } - - inline void IgnoreEverySpaces() noexcept { IgnoreEvery(' ', '\t'); } - inline void IgnoreEveryBlanks() noexcept { IgnoreEvery(' ', '\t', '\n', '\r', '\v'); } - - public: - template - inline void GoTo(const CharToTest... ele) noexcept - { - while (Access().IsNotEqualTo(ele...) && BufferAccess(buffer).CanMoveForward()) - BufferManip(buffer).ForceForward(); - } - template - [[nodiscard]] inline std::expected GoToForward(const CharToTest... ele) noexcept - { - GoTo(ele...); - return BufferManip(buffer).Forward(); - } - - public: - template - [[nodiscard]] std::expected, FMTResult> ViewExec(Func&& func) - { - TChar* begin = Buffer.CurrentPos; - SF_TRY(func()); - TChar* end = Buffer.CurrentPos; - return std::basic_string_view(begin, end - begin); - } - - template - [[nodiscard]] inline std::expected, FMTResult> ViewUntil(CharToTest&&... c) - { - return ViewExec([&] -> std::expected { BufferTestManip(buffer).GoTo(std::forward(c)...); return {}; }); - } - }; -} diff --git a/src/stream/fmt/buffer/buffer_write_manip.h b/src/stream/fmt/buffer/buffer_write_manip.h deleted file mode 100644 index 6edf6d60..00000000 --- a/src/stream/fmt/buffer/buffer_write_manip.h +++ /dev/null @@ -1,170 +0,0 @@ -#pragma once - -#include "buffer_info.h" -#include "buffer_manip.h" -#include "buffer_test_manip.h" -#include "buffer_out_manip.h" - -#include -#include - -namespace stream::fmt::detail -{ - class BufferWriteUtils - { - public: - template - static std::int32_t GetNumberOfDigitDec(T value) - { - if constexpr (std::numeric_limits::is_signed) - { - if (value < 0) value = -value; - } - std::int32_t nb = 0; - while (true) - { - if (value < 10) - return nb + 1; - else if (value < 100) - return nb + 2; - else if (value < 1000) - return nb + 3; - else if (value < 10000) - return nb + 4; - else - { - value /= static_cast(10000); - nb += 4; - } - } - } - }; - - template - class BufferWriteManip - { - public: - constexpr inline BufferWriteManip(BufferOutInfo& buffer) noexcept : Buffer(buffer) {} - public: - BufferOutInfo& Buffer; - - public: - static constexpr TChar BIN[2] = {'0', '1'}; - static constexpr TChar OCT[8] = {'0', '1', '2', '3', '4', '5', '6', '7'}; - static constexpr TChar UPPER_HEX[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; - static constexpr TChar LOWER_HEX[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; - - public: - template - requires std::is_integral_v - [[nodiscard]] constexpr std::expected FastWriteInteger(T i) - { - BufferOutManip manip(buffer); - - if (i == 0) { SF_TRY(manip.Pushback('0')); return {}; } - - if constexpr (std::is_signed_v) - { - if (i < 0) { SF_TRY(manip.Pushback('-')); i = -i; } - } - - std::int32_t nbDigit = BufferWriteUtils::GetNumberOfDigitDec(i); - SF_TRY(manip.Forward(nbDigit)); - while (i > 0) - { - manip.ForceSetInverse(i % 10 + '0'); - i /= 10; - } - SF_TRY(manip.Forward(nbDigit)); - - return {}; - } - - public: - template - requires std::is_floating_point_v - [[nodiscard]] constexpr std::expected FastWriteFloat(T i, std::int32_t floatPrecision = 2) - { - BufferOutManip manip(buffer); - - if (i == 0) - { SF_TRY(manip.Pushback('0')); return {}; } - if (i < 0) - { SF_TRY(manip.Pushback('-')); i = -i; } - - T k = std::trunc(i); - i = i - k; - std::int32_t nbDigit = BufferWriteUtils::GetNumberOfDigitDec(k); - SF_TRY(manip.Forward(nbDigit)); - std::int32_t nbDigit_ = nbDigit; - while (nbDigit_ > 0) - { - manip.ForceSetInverse(char(std::fmod(k, 10)) + '0'); - k /= 10; - nbDigit_--; - } - SF_TRY(manip.Forward(nbDigit)); - SF_TRY(manip.Pushback('.')); - - while (floatPrecision-- >= 0) - { - TChar intPart = static_cast(std::trunc(i *= 10)); - SF_TRY(manip.Pushback(intPart + '0')); - i -= intPart; - } - - return {}; - } - - public: - template - [[nodiscard]] constexpr std::expected FastWriteCharArray(const CharInput* str, std::size_t size) - { - auto reserve = BufferOutManip(buffer).Reserve(size); - if (reserve.has_value() == false) - return FastWriteCharArray(str, BufferAccess(buffer).GetBufferRemainingSize()); - - // TODO: Opti with bigger types - while (size-- != 0 && *str != 0) - BufferOutManip(buffer).ForcePushback(*str++); - - return {}; - } - template - [[nodiscard]] inline constexpr std::expected FastWriteString(std::basic_string_view sv) - { - return FastWriteCharArray(sv.data(), sv.size()); - } - [[nodiscard]] inline std::expected FastWriteString(std::basic_string_view sv) - { - return FastWriteCharArray(sv.data(), sv.size()); - } - template - [[nodiscard]] inline std::expected FastWriteStringLitteral(CharInput (&str)[SIZE]) - { - std::size_t size = SIZE; - while (str[size - 1] == 0) - { --size; } - return FastWriteCharArray(str, size); - } - - public: - template - [[nodiscard]] inline std::expected BasicWriteType(std::basic_string_view str) { return FastWriteString(str); } - template - [[nodiscard]] inline std::expected BasicWriteType(CharInput (&str)[SIZE]) { return FastWriteStringLitteral(str); } - template requires std::is_integral_v - [[nodiscard]] inline std::expected BasicWriteType(T t) { return FastWriteInteger(t); } - template requires std::is_floating_point_v - [[nodiscard]] inline std::expected BasicWriteType(T t) { return FastWriteFloat(t); } - - template - [[nodiscard]] inline std::expected BasicWriteType(Type&& type, Rest&&... rest) - { - SF_TRY(BasicWriteType(type)); - if constexpr (sizeof...(rest) > 0) - SF_TRY(BasicWriteType(std::forward(rest)...)); - return {}; - } - }; -} diff --git a/src/stream/fmt/buffer/fmt_buffer_out_manip.h b/src/stream/fmt/buffer/fmt_buffer_out_manip.h deleted file mode 100644 index c90113b8..00000000 --- a/src/stream/fmt/buffer/fmt_buffer_out_manip.h +++ /dev/null @@ -1,119 +0,0 @@ -#pragma once - -#include "buffer_info.h" -#include "buffer_out_manip.h" -#include "buffer_test_manip.h" - -namespace stream::fmt::detail -{ - template - class FMTBufferOutInfo : public BufferOutInfo - { - public: - using typename BufferOutInfo::TChar; - - using BufferOutInfo::Buffer; - using BufferOutInfo::CurrentPos; - using BufferOutInfo::BufferEnd; - - using BufferOutInfo::Get; - using BufferOutInfo::Manip; - - using BufferOutInfo::Manager; - - protected: - FMTBufferOutInfo(BasicBufferOutManager& bufferOutManager) noexcept - : BufferOutInfo(bufferOutManager) - {} - - public: - [[nodiscard]] static std::expected, FMTResult> Create(BasicBufferOutManager& bufferOutManager) - { - FMTBufferOutInfo res(bufferOutManager); - SF_TRY(BufferOutInfo::Init(res)); - return res; - } - - public: - std::size_t NoStride = 0; - std::size_t Indent = 0; - }; - - template - class FMTBufferOutManip - { - public: - FMTBufferOutManip(FMTBufferOutInfo& buffer) : Buffer(buffer) {} - public: - FMTBufferOutInfo& Buffer; - - public: - constexpr inline void AddNoStride(const std::size_t noStride) noexcept { Buffer.NoStride += noStride; } - - constexpr inline void AddIndent(const std::size_t indent) noexcept { Buffer.Indent += indent; } - constexpr inline void RemoveIndent(const std::size_t indent) noexcept { Buffer.Indent -= indent; } - constexpr inline void SetIndent() noexcept { Buffer.Indent = BufferManip(buffer).GetBufferCurrentSize() - Buffer.NoStride; } - - public: - [[nodiscard]] constexpr inline std::expected NewLineIndent() - { - SF_TRY(BufferOutManip(buffer).Pushback('\n')); - return BufferOutManip(buffer).Pushback(' ', Buffer.Indent); - } - - [[nodiscard]] constexpr inline std::expected PushbackCheckIndent(const TChar c) - { - SF_TRY(BufferOutManip(buffer).Pushback(c)); - if (c == '\n') - { return BufferOutManip(buffer).Pushback(' ', Buffer.Indent); } - return {}; - } - }; - - template - class FMTBufferParamsManip - { - public: - FMTBufferParamsManip(BufferInfo& buffer) : Buffer(buffer) {} - public: - BufferInfo& Buffer; - - public: - template - inline void ParamGoTo(const CharToTest... ele) - { - BufferTestManip(buffer).GoTo(ele..., '}'); - } - template - [[nodiscard]] inline std::expected ParamGoToForward(const CharToTest... ele) - { - return BufferTestManip(buffer).GoToForward(ele..., '}'); - } - - inline bool IsBeginOfParameter() - { - return BufferTestAccess(buffer).IsEqualTo('{'); - } - inline bool IsEndOfParameter() - { - return BufferTestAccess(buffer).IsEqualTo('}'); - } - - public: - template - [[nodiscard]] std::expected NextIsNamedArgs(const std::basic_string_view& sv) - { - BufferTestAccess access(buffer); - BufferTestManip manip(buffer); - - TChar* const oldpos = Buffer.CurrentPos; - auto isSame = SF_TRY(manip.is_same_forward(sv)); - if (isSame && (access.IsEqualTo(':') || access.IsEqualTo('}'))) - { - return true; - } - Buffer.CurrentPos = oldpos; - return false; - } - }; -} diff --git a/src/stream/fmt/buffer/fmt_buffer_read_manip.h b/src/stream/fmt/buffer/fmt_buffer_read_manip.h deleted file mode 100644 index 050bdd91..00000000 --- a/src/stream/fmt/buffer/fmt_buffer_read_manip.h +++ /dev/null @@ -1,238 +0,0 @@ -#pragma once - -#include "stream/fmt/buffer/buffer_info.h" -#include "stream/fmt/buffer/utils/BufferShiftManip.h" -#include "stream/fmt/buffer/buffer_manip.h" -#include "stream/fmt/buffer/buffer_test_manip.h" -#include "stream/fmt/buffer/buffer_read_manip.h" - -namespace stream::fmt::detail -{ - template - class FMTBufferReadManip - { - public: - FMTBufferReadManip(BufferInfo& buffer) : Buffer(buffer) {} - public: - BufferInfo& Buffer; - - public: - template - [[nodiscard]] std::expected ReadInteger(T& i, ShiftInfo shift = ShiftInfo{}) - { - BufferShiftReadManip shiftManip(buffer); - detail::BufferTestAccess access(buffer); - detail::BufferTestManip manip(buffer); - - SF_TRY(shiftManip.IgnoreShiftBeginSpace(shift)); - - bool sign = false; - if constexpr (std::is_signed_v) - { - sign = SF_TRY(manip.IsEqualToForward('-')); - if (sign) --shift.Size; - } - - access.IsADigit(); - - T res = (T)0; - while (access.IsADigit()) - { - char c = SF_TRY(BufferManip(buffer).GetAndForward()); - res = res * 10 + (c - '0'); - --shift.Size; - } - - SF_TRY(shiftManip.IgnoreShiftEnd(shift)); - - i = sign ? -res : res; - return {}; - } - public: - template - [[nodiscard]] std::expected ReadFloat(T& t, std::int32_t floatPrecision = -1, ShiftInfo shift = ShiftInfo{}) - { - BufferShiftReadManip shiftManip(buffer); - detail::BufferTestAccess access(buffer); - detail::BufferTestManip manip(buffer); - - SF_TRY(shiftManip.IgnoreShiftBeginSpace(shift)); - - bool sign = SF_TRY(manip.IsEqualToForward('-')); - if (sign) --shift.Size; - - T intpart = static_cast(0); - if (access.IsADigit()) - { - while (access.IsADigit()) - { - char c = SF_TRY(BufferManip(buffer).GetAndForward()); - intpart = intpart * 10 + (c - '0'); - --shift.Size; - } - } - else if (access.IsEqualTo('.')) - { SF_TRY(detail::BufferManip(buffer).Forward()); } - else - { return std::unexpected(FMTResult::Parse_NonValidDigit); } - - if (floatPrecision <= 0) - while (access.IsADigit() && access.IsEndOfString() == false) - { - BufferManip(buffer).ForceForward(); - --shift.Size; - } - else - { - while (BufferAccess(buffer).IsADigit() && floatPrecision > 0 && BufferAccess(buffer).IsEndOfString() == false) - { - BufferManip(buffer).ForceForward(); - floatPrecision--; - --shift.Size; - } - } - BufferManip(buffer).ForceBackward(); - - T dec = (T)0; - while (access.IsADigit()) - { - dec += static_cast(BufferManip(buffer).GetAndForceBackward() - '0'); - dec /= 10; - } - - SF_TRY(shiftManip.IgnoreShiftEnd(shift)); - - t = sign ? - intpart - dec : intpart + dec; - return {}; - } - - public: - template - [[nodiscard]] std::expected ReadIntegerH(T& i, std::uint8_t digitSize, std::uint8_t (&digitLUT)(TChar), TChar base_prefix = '\0', ShiftInfo shift = ShiftInfo{}) - { - BufferShiftReadManip shiftManip(buffer); - detail::BufferTestAccess access(buffer); - detail::BufferTestManip manip(buffer); - - shift.Size -= sizeof(T) * 8; - if (base_prefix != '\0') shift.Size -= 2; - - SF_TRY(shiftManip.IgnoreShiftBeginSpace(shift)); - - if (base_prefix != '\0') - { - SF_TRY(manip.SkipOneOf('0')); - SF_TRY(manip.SkipOneOf(base_prefix)); - } - - T res = (T)0; - while (digitLUT(Buffer.Get()) != std::numeric_limits::max()) - { - res = res << digitSize; - res += digitLUT(Buffer.Get()); - BufferManip(buffer).ForceForward(); - } - - SF_TRY(shiftManip.IgnoreShiftEnd(shift)); - - i = res; - return {}; - } - - protected: - static constexpr std::uint8_t DigitLUT_BIN(TChar in) - { - if (in == '0') return 0; - if (in == '1') return 1; - return std::numeric_limits::max(); - } - static constexpr std::uint8_t DigitLUT_OCT(TChar in) - { - if (in >= '0' && in <= '7') - return in - '0'; - return std::numeric_limits::max(); - } - static constexpr std::uint8_t DigitLUT_DEC(TChar in) - { - if (in >= '0' && in <= '9') - return in - '0'; - return std::numeric_limits::max(); - } - static constexpr std::uint8_t DigitLUT_HEXUPPER(TChar in) - { - if (in >= '0' && in <= '9') - return in - '0'; - if (in >= 'A' && in <= 'F') - return in - 'A'; - return std::numeric_limits::max(); - } - static constexpr std::uint8_t DigitLUT_HEXLOWER(TChar in) - { - if (in >= '0' && in <= '9') - return in - '0'; - if (in >= 'a' && in <= 'f') - return in - 'a'; - return std::numeric_limits::max(); - } - - public: - template - [[nodiscard]] std::expected ReadIntegerFormatData(T& i, const FormatData& formatData) - { - if (formatData.HasSpec) - { - switch (formatData.IntegerPrint) - { - case IntegerPrintBase::Dec: - if (formatData.Shift.Type == ShiftInfo::ShiftType::Nothing) - return BufferReadManip(buffer).FastReadInteger(i); - else - return ReadInteger(i, formatData.Shift); - case IntegerPrintBase::Bin: - case IntegerPrintBase::BinUpper: - return ReadIntegerH(i, 1, DigitLUT_BIN, formatData.PrefixSuffix ? (char)formatData.IntegerPrint : '\0', formatData.Shift); - case IntegerPrintBase::Oct: - case IntegerPrintBase::OctUpper: - return ReadIntegerH(i, 3, DigitLUT_OCT, formatData.PrefixSuffix ? (char)formatData.IntegerPrint : '\0', formatData.Shift); - case IntegerPrintBase::Hex: - return ReadIntegerH(i, 4, DigitLUT_HEXLOWER, formatData.PrefixSuffix ? (char)formatData.IntegerPrint : '\0', formatData.Shift); - case IntegerPrintBase::HexUpper: - return ReadIntegerH(i, 4, DigitLUT_HEXUPPER, formatData.PrefixSuffix ? (char)formatData.IntegerPrint : '\0', formatData.Shift); - } - } - return BufferReadManip(buffer).FastReadInteger(i); - } - template - [[nodiscard]] std::expected ReadFloatFormatData(T& i, const FormatData& formatData) - { - if (formatData.HasSpec) - { - if (formatData.ShiftType == ShiftInfo::ShiftType::Nothing) - return BufferReadManip(buffer).FastReadFloat(i, formatData.FloatPrecision); - else - return ReadFloat(i, formatData.FloatPrecision, formatData.Shift); - } - return BufferReadManip(buffer).FastReadFloat(i, formatData.FloatPrecision); - } - - public: - template - [[nodiscard]] std::expected ReadCharPtr(const CharStr* str, std::size_t sizeContainer, std::size_t sizeToWrite, ShiftInfo shift = ShiftInfo{}) - { - // FIXME - // TODO - return std::unexpected(FMTResult::FunctionNotImpl); - } - - template - [[nodiscard]] inline std::expected ReadCharArray(const CharStr (&str)[SIZE], ShiftInfo shift = ShiftInfo{}) - { - return ReadCharPtr(str, SIZE, 0, shift); - } - template - [[nodiscard]] inline std::expected ReadCharBound(const CharStr* begin, const CharStr* end, ShiftInfo shift = ShiftInfo{}) - { - return ReadCharPtr(begin, end - begin, 0, shift); - } - }; -} diff --git a/src/stream/fmt/buffer/fmt_buffer_write_manip.h b/src/stream/fmt/buffer/fmt_buffer_write_manip.h deleted file mode 100644 index 3f292eb3..00000000 --- a/src/stream/fmt/buffer/fmt_buffer_write_manip.h +++ /dev/null @@ -1,272 +0,0 @@ -#pragma once - -#include "buffer_info.h" -#include "fmt_buffer_out_manip.h" -#include "utils/BufferShiftManip.h" -#include "buffer_out_manip.h" -#include "buffer_write_manip.h" - -#include - -namespace stream::fmt::detail -{ - template - class FMTBufferWriteManip - { - public: - FMTBufferWriteManip(FMTBufferOutInfo& buffer) : Buffer(buffer) {} - public: - FMTBufferOutInfo& Buffer; - - public: - template - [[nodiscard]] std::expected WriteInteger(T i, detail::ShiftInfo shift = detail::ShiftInfo{}) - { - char oldAfter = shift.Print.After; - if (shift.Print.After >= '0' && shift.Print.After <= '9') - shift.Print.After = ' '; - - std::int32_t nbDigit = BufferWriteUtils::GetNumberOfDigitDec(i); - - shift.Size -= nbDigit; - if (i < 0) --shift.Size; - - if (shift.Size <= 0) - { return BufferWriteManip(buffer).FastWriteInteger(i); } - - if (!shift.Print.BeforeIsADigit()) - { SF_TRY(BufferShiftWriteManip(buffer).WriteShiftBegin(shift)); } - if (i < 0) - { - SF_TRY(BufferOutManip(buffer).Pushback('-')); - i = -i; - } - if (shift.Print.BeforeIsADigit()) - { SF_TRY(BufferShiftWriteManip(buffer).WriteShiftRightAll(shift)); } - - if (i == 0) - { SF_TRY(BufferOutManip(buffer).Pushback('0')); } - else - { - SF_TRY(BufferOutManip(buffer).Forward(nbDigit)); - std::int32_t nbDigit_ = nbDigit; - while (nbDigit_ > 0) - { - BufferOutManip(buffer).ForceSetInverse(i % 10 + '0'); - i /= 10; - nbDigit_--; - } - SF_TRY(BufferOutManip(buffer).Forward(nbDigit)); - } - - SF_TRY(BufferShiftWriteManip(buffer).WriteShiftEnd(shift)); - - shift.Print.After = oldAfter; - return {}; - } - - public: - template - [[nodiscard]] std::expected WriteFloat(T i, std::int32_t floatPrecision = 2, detail::ShiftInfo shift = detail::ShiftInfo{}) - { - char oldBefore = shift.Print.Before; - if (shift.Print.Before >= '0' && shift.Print.Before <= '9') - shift.Print.Before = ' '; - - std::int32_t nbDigit = BufferWriteUtils::GetNumberOfDigitDec(std::trunc(i)); - - shift.Size -= nbDigit + floatPrecision + 1; - if (i < 0) --shift.Size; - - if (shift.Size <= 0) - { return BufferWriteManip(buffer).FastWriteFloat(i, floatPrecision); } - - if (!shift.Print.BeforeIsADigit()) - { SF_TRY(BufferShiftWriteManip(buffer).WriteShiftBegin(shift)); } - if (i < 0) - { - SF_TRY(BufferOutManip(buffer).Pushback('-')); - i = -i; - } - if (shift.Print.BeforeIsADigit()) - { SF_TRY(BufferShiftWriteManip(buffer).WriteShiftRightAll(shift)); } - - T k = std::trunc(i); - if (k == 0) - { SF_TRY(BufferOutManip(buffer).Pushback('0')); } - else - { - SF_TRY(BufferOutManip(buffer).Forward(nbDigit)); - std::int32_t nbDigit_ = nbDigit; - while (nbDigit_ > 0) - { - BufferOutManip(buffer).ForceSetInverse(char(std::fmod(i, 10)) + '0'); - k /= 10; - nbDigit_--; - } - SF_TRY(BufferOutManip(buffer).Forward(nbDigit)); - } - - SF_TRY(BufferOutManip(buffer).Pushback('.')); - i -= k; - while (floatPrecision-- != 0) - { - T decimal = std::trunc(i *= 10); - SF_TRY(BufferOutManip(buffer).Pushback((char)decimal + '0')); - i -= decimal; - } - - SF_TRY(BufferShiftWriteManip(buffer).WriteShiftEnd(shift)); - - shift.Print.Before = oldBefore; - return {}; - } - - public: - template - [[nodiscard]] std::expected WriteIntegerH(T i, std::uint8_t digitSize, const TChar* const lut, TChar base_prefix = '\0', ShiftInfo shift = ShiftInfo{}) - { - BufferOutManip manip(buffer); - - std::int32_t digitCount = sizeof(T) * 8; - { - // Remove leading 0 - std::int32_t lastPosWithData = 0; - std::int32_t k = digitCount + 1; - T cpyI = i; - while (--k != 0) - { - if ((cpyI & (0b1 << digitSize)) != 0) lastPosWithData = k; - cpyI = cpyI >> digitSize; - } - digitCount -= lastPosWithData; - } - - if (base_prefix != '\0') - { - SF_TRY(BufferOutManip(buffer).Pushback('0')); - SF_TRY(BufferOutManip(buffer).Pushback(base_prefix)); - } - - SF_TRY(manip.Forward(digitCount)); - std::int32_t k = digitCount + 1; - while (--k != 0) - { - manip.ForceSetInverse(lut[i & (0b1 << digitSize)]); - i = i >> digitSize; - } - SF_TRY(manip.Forward(digitCount)); - return {}; - } - - public: - template - [[nodiscard]] std::expected WriteIntegerFormatData(T i, const FormatData& formatData) - { - if (formatData.HasSpec) - { - switch (formatData.IntegerPrint) - { - case IntegerPrintBase::Dec: - if (formatData.Shift.Type == ShiftInfo::ShiftType::Nothing) - return BufferWriteManip(buffer).FastWriteInteger(i); - else - return WriteInteger(i, formatData.Shift); - case IntegerPrintBase::Bin: - case IntegerPrintBase::BinUpper: - return WriteIntegerH(i, 1, BufferWriteManip::BIN, formatData.PrefixSuffix ? (char)formatData.IntegerPrint : '\0', formatData.Shift); - case IntegerPrintBase::Oct: - case IntegerPrintBase::OctUpper: - return WriteIntegerH(i, 3, BufferWriteManip::OCT, formatData.PrefixSuffix ? (char)formatData.IntegerPrint : '\0', formatData.Shift); - case IntegerPrintBase::Hex: - return WriteIntegerH(i, 4, BufferWriteManip::LOWER_HEX, formatData.PrefixSuffix ? (char)formatData.IntegerPrint : '\0', formatData.Shift); - case IntegerPrintBase::HexUpper: - return WriteIntegerH(i, 4, BufferWriteManip::UPPER_HEX, formatData.PrefixSuffix ? (char)formatData.IntegerPrint : '\0', formatData.Shift); - - } - } - return BufferWriteManip(buffer).FastWriteInteger(i); - } - template - [[nodiscard]] std::expected WriteFloatFormatData(T i, const FormatData& formatData) - { - if (formatData.HasSpec) - { - if (formatData.Shift.Type != ShiftInfo::ShiftType::Nothing) - return WriteFloat(i, formatData.FloatPrecision, formatData.Shift); - } - - return BufferWriteManip(buffer).FastWriteFloat(i, formatData.FloatPrecision); - } - - public: - template - [[nodiscard]] inline std::expected WriteIndentCharPtr(const CharStr* str, std::size_t size) - { - while (size > 0) - { - const CharStr* const begin = str; - while (size > 0 && *str != '\n') - { - ++str, --size; - } - const CharStr* const end = str; - - SF_TRY(BufferWriteManip(buffer).FastWriteCharArray(begin, end - begin)); - - if (size > 0 && *str == '\n') - { - SF_TRY(FMTBufferOutManip(buffer).NewLineIndent()); - ++str; - --size; - } - } - return {}; - } - template - [[nodiscard]] inline std::expected WriteIndentCharBound(const CharStr* begin, const CharStr* end) - { - return WriteIndentCharPtr(begin, end - begin); - } - template - [[nodiscard]] inline std::expected WriteIndentString(std::basic_string_view str) - { - return WriteIndentCharPtr(str.data(), str.size()); - } - - template - [[nodiscard]] inline std::expected WriteCharPtr(const CharStr* str, std::size_t size, ShiftInfo& shift) - { - if (shift.Size <= 0) - return BufferWriteManip(buffer).FastWriteCharArray(str, size); - - SF_TRY(BufferOutManip(buffer).Reserve(std::max(static_cast(shift.Size), size))); - - if (static_cast(shift.Size) > size) - { - shift.Size -= static_cast(size); - - SF_TRY(BufferShiftWriteManip(buffer).WriteShiftBegin(shift)); - - SF_TRY(BufferWriteManip(buffer).FastWriteCharArray(str, size)); - - SF_TRY(BufferShiftWriteManip(buffer).WriteShiftEnd(shift)); - } - else - { - SF_TRY(BufferWriteManip(buffer).FastWriteCharArray(str, size)); - } - return {}; - } - template - [[nodiscard]] inline std::expected WriteCharBound(const CharStr* begin, const CharStr* end, ShiftInfo& shift) - { - return WriteCharPtr(begin, end - begin, shift); - } - template - [[nodiscard]] inline std::expected WriteString(std::basic_string_view str, ShiftInfo& shift) - { - return WriteCharPtr(str.data(), str.size(), shift); - } - }; -} diff --git a/src/stream/fmt/buffer/utils/buffer_globber_manip.h b/src/stream/fmt/buffer/utils/buffer_globber_manip.h deleted file mode 100644 index 9f33eb42..00000000 --- a/src/stream/fmt/buffer/utils/buffer_globber_manip.h +++ /dev/null @@ -1,129 +0,0 @@ -#pragma once - -#include "stream/fmt/buffer/buffer_info.h" -#include "stream/fmt/buffer/buffer_manip.h" - -namespace stream::fmt::detail -{ - template - class Globber - { - public: - enum class PatternMatchType - { - MatchBiggest, - MatchSmallest - }; - - private: - [[nodiscard]] static std::expected BufferInExecGlob_(BufferInfo& bufferIn, BufferInfo& glob) - { - if (BufferAccess(glob).IsEndOfString()) { return bufferIn.CurrentPos; } - - if (BufferAccess(bufferIn).IsEndOfString()) { return nullptr; } - - if (BufferTestAccess(glob).IsEqualTo('?')) - { - SF_TRY(BufferManip(glob).Forward()); - SF_TRY(BufferManip(bufferIn).Forward()); - return BufferInExecGlob_(bufferIn, glob); - } - else if (BufferTestAccess(glob).IsEqualTo('*')) - { - SF_TRY(BufferManip(glob).Forward()); - const TChar* further = SF_TRY(BufferInExecGlob_(bufferIn, glob)); - while (BufferAccess(bufferIn).CanMoveForward()) - { - SF_TRY(BufferManip(bufferIn).Forward()); - const TChar* last = SF_TRY(BufferInExecGlob_(bufferIn, glob)); - if (last > further || further == nullptr) further = last; - } - return further; - } - else if (BufferTestAccess(glob).IsEqualTo('[')) - { - SF_TRY(BufferManip(bufferIn).Forward()); - const TChar* begin = glob.CurrentPos; - SF_TRY(BufferTestManip(glob).GoToForward(']')); - const TChar* end = glob.CurrentPos; - - BufferInfoView charSet(begin, end - begin); - - bool is_inverted = SF_TRY(BufferTestManip(glob).IsEqualToForward('!')); - TChar toMatch = SF_TRY(BufferManip(bufferIn).GetAndForward()); - bool found = false; - - while (found == false && BufferAccess(charSet).CanMoveForward()) - { - if (BufferTestAccess(charSet).IsEqualTo(toMatch)) - { - found = true; - break; - } - - if (BufferTestAccess(charSet).IsEqualTo('-')) - { - TChar beginSubSet = BufferAccess(charSet).GetPrevForce(); - TChar endSubSet = BufferAccess(charSet).GetNextForce(); - if (toMatch >= beginSubSet && toMatch <= endSubSet) - { - found = true; - break; - } - } - - BufferManip(charSet).Forward(); - } - - if (found && is_inverted == false) - return BufferInExecGlob_(bufferIn, glob); - else if (found == false && is_inverted == true) - return BufferInExecGlob_(bufferIn, glob); - return nullptr; - } - - if (bufferIn.Get() == glob.Get()) - { - SF_TRY(BufferManip(glob).Forward()); - SF_TRY(BufferManip(bufferIn).Forward()); - return BufferInExecGlob_(bufferIn, glob); - } - return nullptr; - } - - public: - [[nodiscard]] static std::expected BufferInExecGlob(BufferInfo& bufferIn, BufferInfo& glob, [[maybe_unused]] PatternMatchType patternMatchtype = PatternMatchType::MatchBiggest) - { - const TChar* furtherPointMatched = SF_TRY(BufferInExecGlob_(bufferIn, glob)); - if (furtherPointMatched != nullptr) - bufferIn.CurrentPos = furtherPointMatched; - return {}; - } - }; - - template - class BufferGlobberManip - { - public: - constexpr inline BufferGlobberManip(BufferInfo& buffer) noexcept : Buffer(buffer) {} - public: - BufferInfo& Buffer; - - public: - [[nodiscard]] std::expected FastReadCharPtrGlobber(std::basic_string_view globPattern, TChar* str, std::size_t sizeToCopy) - { - BufferInfo globber(globPattern); - const TChar* begin = Buffer.CurrentPos; - Globber::BufferInExecGlob(*this, globber); - const TChar* end = Buffer.CurrentPos; - - BufferInfo subContext(begin, end); - return BufferReadManip(subContext).FastReadCharPtr(str, sizeToCopy); - } - - [[nodiscard]] std::expected FastReadCharPtrRegex(std::basic_string_view regexPattern, TChar* str, std::size_t sizeToCopy) - { - return std::unexpected(FMTResult::FunctionNotImpl); - } - }; -} diff --git a/src/stream/fmt/buffer/utils/buffer_shift_manip.h b/src/stream/fmt/buffer/utils/buffer_shift_manip.h deleted file mode 100644 index 6b0958a0..00000000 --- a/src/stream/fmt/buffer/utils/buffer_shift_manip.h +++ /dev/null @@ -1,102 +0,0 @@ -#pragma once - -#include "stream/fmt/buffer/buffer_info.h" -#include "stream/fmt/buffer/buffer_out_manip.h" - -namespace stream::fmt::detail -{ - template - class BufferShiftWriteManip - { - public: - BufferShiftWriteManip(BufferOutInfo& buffer) : Buffer(buffer) {} - public: - BufferOutInfo& Buffer; - - public: - [[nodiscard]] inline std::expected WriteShiftCenterBegin(detail::ShiftInfo& shift) - { - if (shift.Type == detail::ShiftInfo::ShiftType::CenterRight || shift.Type == detail::ShiftInfo::ShiftType::CenterLeft) - { - std::int32_t shift_ = shift.Size / 2; - if (shift.Type == detail::ShiftInfo::ShiftType::CenterLeft) shift_ = (shift.Size + 1) / 2; - SF_TRY(BufferOutManip(buffer).Pushback(shift.Print.Before, shift.Size - shift_)); - shift.Size = shift_; - } - - return {}; - } - - [[nodiscard]] inline std::expected WriteShiftCenterEnd(detail::ShiftInfo& shift) - { - if (shift.Type == detail::ShiftInfo::ShiftType::CenterRight || shift.Type == detail::ShiftInfo::ShiftType::CenterLeft) - return BufferOutManip(buffer).Pushback(shift.Print.After, shift.Size); - return {}; - } - - [[nodiscard]] inline std::expected WriteShiftRightAll(detail::ShiftInfo& shift) - { - if (shift.Type == detail::ShiftInfo::ShiftType::Right) - return BufferOutManip(buffer).Pushback(shift.Print.Before, shift.Size); - return {}; - } - - [[nodiscard]] inline std::expected WriteShiftLeftAll(detail::ShiftInfo& shift) - { - if (shift.Type == detail::ShiftInfo::ShiftType::Left) - return BufferOutManip(buffer).Pushback(shift.Print.After, shift.Size); - return {}; - } - - [[nodiscard]] inline std::expected WriteShiftBegin(detail::ShiftInfo& shift) - { - SF_TRY(WriteShiftCenterBegin(shift)); - return WriteShiftRightAll(shift); - } - - [[nodiscard]] inline std::expected WriteShiftEnd(detail::ShiftInfo& shift) - { - SF_TRY(WriteShiftLeftAll(shift)); - return WriteShiftCenterEnd(shift); - } - }; - - template - class BufferShiftReadManip - { - public: - BufferShiftReadManip(BufferInfo& buffer) : Buffer(buffer) {} - public: - BufferInfo& Buffer; - - public: - [[nodiscard]] std::expected IgnoreShiftBeginSpace(detail::ShiftInfo& shift) - { - if (shift.Print.BeforeIsADigit() == false) - return {}; - if (shift.Type == detail::ShiftInfo::ShiftType::Right || shift.Type == detail::ShiftInfo::ShiftType::CenterLeft || shift.Type == detail::ShiftInfo::ShiftType::CenterRight) - { - - while (Buffer.Get() == ' ') - { - SF_TRY(BufferManip(buffer).Forward()); - --shift.Size; - } - } - return {}; - } - - [[nodiscard]] std::expected IgnoreShiftEnd(detail::ShiftInfo& shift) - { - if (shift.Type == detail::ShiftInfo::ShiftType::Left || shift.Type == detail::ShiftInfo::ShiftType::CenterLeft || shift.Type == detail::ShiftInfo::ShiftType::CenterRight) - { - while (Buffer.Get() == ' ' && shift.Size > 0) - { - SF_TRY(BufferManip(buffer).Forward()); - --shift.Size; - } - } - return {}; - } - }; -} diff --git a/src/stream/fmt/buffer/utils/buffer_utils.h b/src/stream/fmt/buffer/utils/buffer_utils.h deleted file mode 100644 index 8066ac8d..00000000 --- a/src/stream/fmt/buffer/utils/buffer_utils.h +++ /dev/null @@ -1,131 +0,0 @@ -#pragma once - -#include "stream/fmt/buffer/buffer_info.h" -#include "stream/fmt/buffer/buffer_out_manip.h" -#include "stream/fmt/buffer/buffer_test_manip.h" -#include "stream/fmt/buffer/buffer_write_manip.h" -#include "stream/fmt/buffer/buffer_read_manip.h" - -#include "stream/fmt/buffer/buffer_out_manager/dynamic_buffer_out_manager.h" -#include "stream/fmt/buffer/buffer_out_manager/given_buffer_out_manager.h" -#include "stream/fmt/buffer/buffer_out_manager/static_buffer_out_manager.h" - -namespace stream::fmt::detail -{ - template - class BufferUtilsManip - { - public: - constexpr inline BufferUtilsManip(BufferInfo& buffer_) noexcept : buffer(buffer_) {} - public: - BufferInfo& buffer; - - using TConstChar = std::remove_const_t; - - public: - template - [[nodiscard]] std::expected get_word_from_list(const std::basic_string_view (&data)[SIZE]) - { - for (std::size_t idx = 0; idx < SIZE; ++idx) - { - bool found = SF_TRY(BufferTestManip(buffer).is_same_forward(data[idx])); - if (found) return idx; - } - return std::unexpected(FMTResult::Specifers_Invalid); - } - - // TODO: use static map ? - template - using DictPairs = std::pair, T>; - - template - [[nodiscard]] std::expected get_word_from_dict_pairs(const DictPairs (&data)[SIZE]) - { - for (std::size_t idx = 0; idx < SIZE; ++idx) - { - bool found = SF_TRY(BufferTestManip(buffer).is_same_forward(data[idx].first)); - if (found) - return data[idx].second; - } - return std::unexpected(FMTResult::Specifers_Invalid); - } - }; - - class BufferUtils - { - public: - template - [[nodiscard]] static std::expected parse_escaped_quoted_string(detail::BufferInfo& buffer, detail::BufferOutInfo& stringOut) - { - SF_TRY(detail::BufferTestManip(buffer).SkipOneOf('"')); - while (detail::BufferAccess(buffer).IsEndOfString() == false) - { - auto view = SF_TRY(detail::BufferTestManip(buffer).ViewUntil('"', '\\')); - SF_TRY(detail::BufferWriteManip(stringOut).FastWriteString(view)); - - if (detail::BufferTestAccess(buffer).IsEqualTo('"')) - { break; } - - SF_TRY(detail::BufferTestManip(buffer).SkipOneOf('\\')); - switch (buffer.Get()) - { - // TODO : Do all others escape char - case '"': - SF_TRY(detail::BufferOutManip(stringOut).Pushback('"')); - break; - case 't': - SF_TRY(detail::BufferOutManip(stringOut).Pushback('\t')); - break; - case 'r': - SF_TRY(detail::BufferOutManip(stringOut).Pushback('\r')); - break; - case 'n': - SF_TRY(detail::BufferOutManip(stringOut).Pushback('\n')); - break; - default: - break; - } - } - SF_TRY(detail::BufferTestManip(buffer).SkipOneOf('"')); - - return {}; - } - - template - [[nodiscard]] static std::expected FormatEscapedQuotedString(detail::BufferOutInfo& buffer, detail::BufferInfo& stringIn) - { - SF_TRY(detail::BufferOutManip(buffer).Pushback('"')); - while (detail::BufferAccess(stringIn).IsEndOfString() == false) - { - auto view = SF_TRY(detail::BufferTestManip(stringIn).ViewUntil('\\')); - SF_TRY(detail::BufferWriteManip(buffer).FastWriteString(view)); - - if (detail::BufferAccess(stringIn).IsEndOfString()) break; - - // TODO - SF_TRY(detail::BufferTestManip(stringIn).SkipOneOf('\\')); - switch (stringIn.Get()) - { - // TODO : Do all others escape char - case '"': - SF_TRY(detail::BufferOutManip(buffer).Pushback('"')); - break; - case 't': - SF_TRY(detail::BufferOutManip(buffer).Pushback('\t')); - break; - case 'r': - SF_TRY(detail::BufferOutManip(buffer).Pushback('\r')); - break; - case 'n': - SF_TRY(detail::BufferOutManip(buffer).Pushback('\n')); - break; - default: - break; - } - } - SF_TRY(detail::BufferOutManip(buffer).Pushback('"')); - - return {}; - } - }; -} diff --git a/src/stream/fmt/context/basic_context/basic_args_interface.h b/src/stream/fmt/context/basic_context/basic_args_interface.h index 208023a5..fca22751 100644 --- a/src/stream/fmt/context/basic_context/basic_args_interface.h +++ b/src/stream/fmt/context/basic_context/basic_args_interface.h @@ -2,7 +2,7 @@ #include "stream/fmt/detail/convert_traits.h" #include "stream/fmt/detail/prelude.h" -#include "stream/fmt/buffer/buffer_info.h" +#include "stream/fmt/buf/stream.h" #include #include @@ -14,15 +14,15 @@ namespace stream::fmt::context class BasicContext; template - class ContextExecutor; + class context_executor; } namespace stream::fmt::detail { struct PointerID { - const std::type_info& TypeInfo; - void* Ptr = nullptr; + const std::type_info& type_info; + void* ptr = nullptr; }; template @@ -33,29 +33,29 @@ namespace stream::fmt::detail virtual ~BasicArgsInterface() = default; public: - virtual size_t Size() = 0; + virtual size_t size() = 0; public: - [[nodiscard]] virtual std::expected GetPointerIDAt(std::int32_t idx) = 0; - [[nodiscard]] virtual std::expected RunTypeAtIndex(std::int32_t idx) = 0; - [[nodiscard]] virtual std::expected GetIndexOfCurrentNamedArg(BufferInfoView& format) = 0; - [[nodiscard]] virtual std::expected, FMTResult> GetStringAt(std::int32_t idx) = 0; - [[nodiscard]] virtual std::expected GetIntAt(std::int32_t idx) = 0; + [[nodiscard]] virtual std::expected get_pointerid_at(std::int32_t idx) = 0; + [[nodiscard]] virtual std::expected run_type_at(std::int32_t idx) = 0; + [[nodiscard]] virtual std::expected get_index_of_current_named_arg(buf::StreamView& format) = 0; + [[nodiscard]] virtual std::expected, FMTResult> get_string_at(std::int32_t idx) = 0; + [[nodiscard]] virtual std::expected get_int_at(std::int32_t idx) = 0; public: template - [[nodiscard]] std::expected GetTypeAt(std::int32_t idx) + [[nodiscard]] std::expected get_type_at(std::int32_t idx) { - PointerID ptr = SF_TRY(GetPointerIDAt(idx)); - if (ptr.TypeInfo != typeid(T)) + PointerID ptr = SF_TRY(get_pointerid_at(idx)); + if (ptr.type_info != typeid(T)) { return std::unexpected(FMTResult::ArgsInterface_InvalidTypeID); } - return reinterpret_cast(ptr.Ptr); + return reinterpret_cast(ptr.ptr); } template - [[nodiscard]] std::expected RunFuncFromTypeAtIndex(std::int32_t idx, std::function(const T&)> func) + [[nodiscard]] std::expected run_func_from_type_at(std::int32_t idx, std::function(const T&)> func) { - const T* value = SF_TRY(GetTypeAt(idx)); + const T* value = SF_TRY(get_type_at(idx)); SF_TRY(func(*value)); return {}; } @@ -69,13 +69,13 @@ namespace stream::fmt::detail ~EmptyContextArgsTupleInterface() override = default; public: - size_t Size() override { return 0; } + size_t size() override { return 0; } public: - [[nodiscard]] std::expected GetPointerIDAt(std::int32_t) override { return std::unexpected(FMTResult::ArgsInterface_Unavaible); } - [[nodiscard]] std::expected RunTypeAtIndex(std::int32_t) override { return std::unexpected(FMTResult::ArgsInterface_Unavaible); } - [[nodiscard]] std::expected GetIndexOfCurrentNamedArg(BufferInfoView&) override { return std::unexpected(FMTResult::ArgsInterface_Unavaible); } - [[nodiscard]] std::expected, FMTResult> GetStringAt(std::int32_t) override { return std::unexpected(FMTResult::ArgsInterface_Unavaible); } - [[nodiscard]] std::expected GetIntAt(std::int32_t) override { return std::unexpected(FMTResult::ArgsInterface_Unavaible); } + [[nodiscard]] std::expected get_pointerid_at(std::int32_t) override { return std::unexpected(FMTResult::ArgsInterface_Unavaible); } + [[nodiscard]] std::expected run_type_at(std::int32_t) override { return std::unexpected(FMTResult::ArgsInterface_Unavaible); } + [[nodiscard]] std::expected get_index_of_current_named_arg(buf::StreamView&) override { return std::unexpected(FMTResult::ArgsInterface_Unavaible); } + [[nodiscard]] std::expected, FMTResult> get_string_at(std::int32_t) override { return std::unexpected(FMTResult::ArgsInterface_Unavaible); } + [[nodiscard]] std::expected get_int_at(std::int32_t) override { return std::unexpected(FMTResult::ArgsInterface_Unavaible); } }; } diff --git a/src/stream/fmt/context/basic_context/basic_context.h b/src/stream/fmt/context/basic_context/basic_context.h index 01214e9c..11c048ba 100644 --- a/src/stream/fmt/context/basic_context/basic_context.h +++ b/src/stream/fmt/context/basic_context/basic_context.h @@ -4,10 +4,10 @@ #include "stream/fmt/detail/prelude.h" #include "stream/fmt/detail/specifiers.h" -#include "stream/fmt/buffer/buffer_info.h" -#include "stream/fmt/buffer/buffer_manip.h" -#include "stream/fmt/buffer/buffer_test_manip.h" -#include "stream/fmt/buffer/buffer_read_manip.h" +#include "stream/fmt/buf/stream.h" +#include "stream/fmt/buf/manip.h" +#include "stream/fmt/buf/test_manip.h" +#include "stream/fmt/buf/read_manip.h" #include "basic_args_interface.h" @@ -20,21 +20,21 @@ namespace stream::fmt::context class BasicContext; template - class ContextExecutor + class context_executor { public: - ContextExecutor(detail::ITextPropertiesExecutor& textPropertiesExecutor) - : Data{} - , TextManager{textPropertiesExecutor} + context_executor(detail::ITextPropertiesExecutor& text_properties_executor) + : data{} + , TextManager{text_properties_executor} {} - virtual ~ContextExecutor() = default; + virtual ~context_executor() = default; public: - [[nodiscard]] virtual std::expected ExecSettings() = 0; - [[nodiscard]] virtual std::expected ExecRawString(std::basic_string_view) = 0; + [[nodiscard]] virtual std::expected exec_settings() = 0; + [[nodiscard]] virtual std::expected exec_raw_string(std::basic_string_view) = 0; public: - detail::FormatData Data; + detail::FormatData data; detail::TextPropertiesManager TextManager; }; @@ -46,21 +46,21 @@ namespace stream::fmt::context public: BasicContext( - ContextExecutor& executor, - detail::BufferInfoView format, - detail::BasicArgsInterface& argsInterface + context_executor& executor, + buf::StreamView fmtstream, + detail::BasicArgsInterface& args_interface ); virtual ~BasicContext() = default; public: - ContextExecutor& Executor; + context_executor& executor; - detail::BufferInfoView Format; - detail::BasicArgsInterface& ArgsInterface; - std::int32_t ValuesIndex; + buf::StreamView fmtstream; + detail::BasicArgsInterface& args_interface; + std::int32_t values_index; public: - [[nodiscard]] std::expected Run(); + [[nodiscard]] std::expected run(); private: [[nodiscard]] std::expected GetFormatIndex_Number(); @@ -70,19 +70,19 @@ namespace stream::fmt::context public: [[nodiscard]] std::expected GetFormatIndex(); template - [[nodiscard]] std::expected FormatReadParameter(const T& defaultValue); + [[nodiscard]] std::expected format_read_parameter(const T& default_value); protected: - void FormatDataApplyNextOverride(); + void formatdata_apply_next_override(); protected: - [[nodiscard]] std::expected, FMTResult> ParseNextOverrideFormatData(); + [[nodiscard]] std::expected, FMTResult> parse_next_override_format_data(); - [[nodiscard]] std::expected ParseFormatDataBase(); - [[nodiscard]] std::expected ParseFormatDataSpecial(); - [[nodiscard]] std::expected ParseFormatDataSpecial_ShiftType(const detail::ShiftInfo::ShiftType type); - [[nodiscard]] std::expected ParseFormatDataCustom(); - [[nodiscard]] std::expected ParseFormatData(); + [[nodiscard]] std::expected parse_format_data_base(); + [[nodiscard]] std::expected parse_format_dataSpecial(); + [[nodiscard]] std::expected parse_format_dataSpecial_ShiftType(const detail::ShiftInfo::ShiftType type); + [[nodiscard]] std::expected parse_format_dataCustom(); + [[nodiscard]] std::expected parse_format_data(); [[nodiscard]] std::expected ParseVariable(std::int32_t formatIdx); [[nodiscard]] std::expected parse(); @@ -91,12 +91,12 @@ namespace stream::fmt::context template inline void ExecNextFormatData(Func&& func, Args&&... args) { - if (Executor.Data.NextOverride.size() == 0) + if (executor.data.next_override.size() == 0) return func(std::forward(args)...); - detail::FormatData formatDataCopy = Executor.Data; - FormatDataApplyNextOverride(); + detail::FormatData format_data_copy = executor.data; + formatdata_apply_next_override(); func(std::forward(args)...); - Executor.Data = formatDataCopy; + executor.data = format_data_copy; } }; } @@ -105,31 +105,31 @@ namespace stream::fmt::context { template BasicContext::BasicContext( - ContextExecutor& executor, - detail::BufferInfoView format, - detail::BasicArgsInterface& argsInterface + context_executor& executor, + buf::StreamView format, + detail::BasicArgsInterface& args_interface ) - : Executor(executor) - , Format{format} - , ArgsInterface{argsInterface} - , ValuesIndex{0} + : executor(executor) + , fmtstream{format} + , args_interface{args_interface} + , values_index{0} {} template - [[nodiscard]] std::expected BasicContext::Run() + [[nodiscard]] std::expected BasicContext::run() { - while (!detail::BufferAccess(Format).IsEndOfString()) + while (!buf::Access(fmtstream).is_end_of_string()) { - const TChar* beginContinousString = Format.CurrentPos; - std::size_t sizeContinousString = 0; - while (detail::BufferAccess(Format).IsEndOfString() == false && detail::BufferTestAccess(Format).IsEqualTo('{') == false) + const TChar* begin_continuous_string = fmtstream.current_pos; + std::size_t size_continuous_string = 0; + while (buf::Access(fmtstream).is_end_of_string() == false && buf::TestAccess(fmtstream).is_equal_to('{') == false) { - ++sizeContinousString; - SF_TRY(detail::BufferManip(Format).Forward()); + ++size_continuous_string; + SF_TRY(buf::Manip(fmtstream).forward()); } - SF_TRY(Executor.ExecRawString(std::basic_string_view(beginContinousString, sizeContinousString))); + SF_TRY(executor.exec_raw_string(std::basic_string_view(begin_continuous_string, size_continuous_string))); - if (detail::BufferAccess(Format).IsEndOfString() == false && detail::BufferTestAccess(Format).IsEqualTo('{')) + if (buf::Access(fmtstream).is_end_of_string() == false && buf::TestAccess(fmtstream).is_equal_to('{')) { SF_TRY(parse()); } @@ -139,39 +139,39 @@ namespace stream::fmt::context } template - void BasicContext::FormatDataApplyNextOverride() + void BasicContext::formatdata_apply_next_override() { - if (Executor.Data.NextOverride.size() == 0) + if (executor.data.next_override.size() == 0) { return; } - detail::BufferInfoView overridePos(Executor.Data.NextOverride); - detail::BufferInfoView formatPos = Format; - Format = overridePos; - ParseFormatData(); - Format = formatPos; + buf::StreamView overridePos(executor.data.next_override); + buf::StreamView format_pos = fmtstream; + fmtstream = overridePos; + parse_format_data(); + fmtstream = format_pos; } template template - [[nodiscard]] std::expected BasicContext::FormatReadParameter(const T& defaultValue) + [[nodiscard]] std::expected BasicContext::format_read_parameter(const T& default_value) { - if (!detail::BufferTestAccess(Format).IsEqualTo('{')) + if (!buf::TestAccess(fmtstream).is_equal_to('{')) { T t; - SF_TRY(detail::BufferReadManip(Format).FastReadInteger(t)); + SF_TRY(buf::ReadManip(fmtstream).fast_read_integer(t)); return t; } // SubIndex - SF_TRY(detail::BufferTestManip(Format).SkipOneOf('}')); + SF_TRY(buf::TestManip(fmtstream).skip_one_of('}')); std::int32_t formatIdx = SF_TRY(GetFormatIndex()); if constexpr (std::is_convertible_v) - return ArgsInterface.GetIntAt(formatIdx); + return args_interface.get_int_at(formatIdx); else if constexpr (std::is_convertible_v>) - return ArgsInterface.GetStringAt(formatIdx); + return args_interface.get_string_at(formatIdx); return std::unexpected(FMTResult::Context_ArgumentIndexExpected); } } -#include "BasicContextParse-impl.h" +#include "basic_context_parse_impl.h" diff --git a/src/stream/fmt/context/basic_context/basic_context_parse_impl.h b/src/stream/fmt/context/basic_context/basic_context_parse_impl.h index 33b8b5b4..969ab717 100644 --- a/src/stream/fmt/context/basic_context/basic_context_parse_impl.h +++ b/src/stream/fmt/context/basic_context/basic_context_parse_impl.h @@ -2,177 +2,177 @@ #include "basic_context.h" -#include "stream/fmt/buffer/buffer_manip.h" -#include "stream/fmt/buffer/buffer_test_manip.h" -#include "stream/fmt/buffer/buffer_write_manip.h" -#include "stream/fmt/buffer/buffer_read_manip.h" -#include "stream/fmt/buffer/fmt_buffer_out_manip.h" -#include "stream/fmt/buffer/FMTBufferReadManip.h" +#include "stream/fmt/buf/manip.h" +#include "stream/fmt/buf/test_manip.h" +#include "stream/fmt/buf/write_manip.h" +#include "stream/fmt/buf/read_manip.h" +#include "stream/fmt/buf/fmt_manip_io.h" +#include "stream/fmt/buf/fmt_read_manip.h" namespace stream::fmt::context { template - [[nodiscard]] std::expected, FMTResult> BasicContext::ParseNextOverrideFormatData() + [[nodiscard]] std::expected, FMTResult> BasicContext::parse_next_override_format_data() { // TODO: check that function - detail::BufferTestAccess access(Format); - detail::BufferTestManip manip(Format); - - manip.IgnoreEverySpaces(); - detail::FMTBufferParamsManip(Format).ParamGoTo('{', '=', ':'); - manip.IgnoreEverySpaces(); - manip.IgnoreOneOf('=', ':'); - manip.IgnoreEverySpaces(); - detail::FMTBufferParamsManip(Format).ParamGoTo('{'); - - const TChar* begin = Format.CurrentPos; - SF_TRY(manip.SkipOneOf('{')); + buf::TestAccess access(fmtstream); + buf::TestManip manip(fmtstream); + + manip.ignore_every_spaces(); + buf::FMTParamsManip(fmtstream).param_go_to('{', '=', ':'); + manip.ignore_every_spaces(); + manip.ignore_one_of('=', ':'); + manip.ignore_every_spaces(); + buf::FMTParamsManip(fmtstream).param_go_to('{'); + + const TChar* begin = fmtstream.current_pos; + SF_TRY(manip.skip_one_of('{')); int scopes = 0; - while (detail::FMTBufferParamsManip(Format).IsEndOfParameter() == false || scopes > 0) + while (buf::FMTParamsManip(fmtstream).is_end_of_parameter() == false || scopes > 0) { manip.GoTo('\'', '}', '{'); - if (access.IsEqualTo('\'')) + if (access.is_equal_to('\'')) { - SF_TRY(detail::BufferManip(Format).Forward()); - manip.GoToForward('\''); + SF_TRY(buf::Manip(fmtstream).forward()); + manip.go_to_forward('\''); } - else if (access.IsEqualTo('{')) + else if (access.is_equal_to('{')) { - SF_TRY(detail::BufferManip(Format).Forward()); + SF_TRY(buf::Manip(fmtstream).forward()); scopes++; } - else if (scopes > 0 && access.IsEqualTo('}')) + else if (scopes > 0 && access.is_equal_to('}')) { - SF_TRY(detail::BufferManip(Format).Forward()); + SF_TRY(buf::Manip(fmtstream).forward()); scopes--; } } - manip.SkipOneOf('}'); - const TChar* end = Format.CurrentPos; + manip.skip_one_of('}'); + const TChar* end = fmtstream.current_pos; return std::basic_string_view(begin, end - begin); } template - [[nodiscard]] std::expected BasicContext::ParseFormatDataBase() + [[nodiscard]] std::expected BasicContext::parse_format_data_base() { - detail::BufferTestAccess access(Format); + buf::TestAccess access(fmtstream); - if (access.IsEqualTo('C')) + if (access.is_equal_to('C')) { - SF_TRY(detail::BufferManip(Format).Forward()); - SF_TRY(Executor.TextManager.ParseColor(*this)); + SF_TRY(buf::Manip(fmtstream).forward()); + SF_TRY(executor.TextManager.parse_color(*this)); } - else if (access.IsEqualTo('S')) + else if (access.is_equal_to('S')) { - SF_TRY(detail::BufferManip(Format).Forward()); - SF_TRY(Executor.TextManager.ParseStyle(*this)); + SF_TRY(buf::Manip(fmtstream).forward()); + SF_TRY(executor.TextManager.parse_style(*this)); } - else if (access.IsEqualTo('F')) + else if (access.is_equal_to('F')) { - SF_TRY(detail::BufferManip(Format).Forward()); - SF_TRY(Executor.TextManager.ParseFront(*this)); + SF_TRY(buf::Manip(fmtstream).forward()); + SF_TRY(executor.TextManager.parse_front(*this)); } - else if (access.IsEqualTo('K')) + else if (access.is_equal_to('K')) { - SF_TRY(detail::BufferManip(Format).Forward()); - Executor.Data.KeepNewStyle = true; + SF_TRY(buf::Manip(fmtstream).forward()); + executor.data.keep_new_style = true; } - else if (access.IsEqualTo('N')) + else if (access.is_equal_to('N')) { - SF_TRY(detail::BufferManip(Format).Forward()); - Executor.Data.NextOverride = SF_TRY(ParseNextOverrideFormatData()); + SF_TRY(buf::Manip(fmtstream).forward()); + executor.data.next_override = SF_TRY(parse_next_override_format_data()); } return {}; } template - [[nodiscard]] std::expected BasicContext::ParseFormatDataSpecial_ShiftType(const detail::ShiftInfo::ShiftType type) + [[nodiscard]] std::expected BasicContext::parse_format_dataSpecial_ShiftType(const detail::ShiftInfo::ShiftType type) { - Executor.Data.Shift.Type = type; - Executor.Data.Shift.Size = SF_TRY(FormatReadParameter(-1)); - if (detail::BufferTestAccess(Format).IsEqualTo(':')) + executor.data.shift.type = type; + executor.data.shift.size = SF_TRY(format_read_parameter(-1)); + if (buf::TestAccess(fmtstream).is_equal_to(':')) { - SF_TRY(detail::BufferManip(Format).Forward()); - Executor.Data.Shift.Print.Before = SF_TRY(detail::BufferManip(Format).GetAndForward()); - Executor.Data.Shift.Print.After = Executor.Data.Shift.Print.Before; - if (detail::BufferTestAccess(Format).IsEqualTo('|')) + SF_TRY(buf::Manip(fmtstream).forward()); + executor.data.shift.print.before = SF_TRY(buf::Manip(fmtstream).get_and_forward()); + executor.data.shift.print.after = executor.data.shift.print.before; + if (buf::TestAccess(fmtstream).is_equal_to('|')) { - SF_TRY(detail::BufferManip(Format).Forward()); - Executor.Data.Shift.Print.After = SF_TRY(detail::BufferManip(Format).GetAndForward()); + SF_TRY(buf::Manip(fmtstream).forward()); + executor.data.shift.print.after = SF_TRY(buf::Manip(fmtstream).get_and_forward()); } } return {}; } template - [[nodiscard]] std::expected BasicContext::ParseFormatDataSpecial() + [[nodiscard]] std::expected BasicContext::parse_format_dataSpecial() { - detail::BufferTestAccess access(Format); - detail::BufferTestManip manip(Format); + buf::TestAccess access(fmtstream); + buf::TestManip manip(fmtstream); - if (access.IsEqualTo('{')) + if (access.is_equal_to('{')) { - SF_TRY(detail::BufferManip(Format).Forward()); + SF_TRY(buf::Manip(fmtstream).forward()); std::int32_t formatIndex = SF_TRY(GetFormatIndex()); - bool ableToApply = false; + bool ableToapply = false; - auto applyFormatData = SF_TRY(ArgsInterface.template GetTypeAt>(formatIndex)); - ableToApply |= Executor.Data.TestApply(applyFormatData); - auto applyFormatSpecifier = SF_TRY(ArgsInterface.template GetTypeAt>(formatIndex)); - ableToApply |= Executor.Data.TestApply(applyFormatSpecifier); - auto applyIntegerPrintBase = SF_TRY(ArgsInterface.template GetTypeAt(formatIndex)); - ableToApply |= Executor.Data.TestApply(applyIntegerPrintBase); - auto applyShiftInfo = SF_TRY(ArgsInterface.template GetTypeAt(formatIndex)); - ableToApply |= Executor.Data.TestApply(applyShiftInfo); - - if (not ableToApply) - { return std::unexpected(FMTResult::Context_CannotApplyType); } - SF_TRY(manip.SkipOneOf('}')); + auto applyFormatData = SF_TRY(args_interface.template get_type_at>(formatIndex)); + ableToapply |= executor.data.testapply(applyFormatData); + auto applyFormatSpecifier = SF_TRY(args_interface.template get_type_at>(formatIndex)); + ableToapply |= executor.data.testapply(applyFormatSpecifier); + auto applyIntegerPrintBase = SF_TRY(args_interface.template get_type_at(formatIndex)); + ableToapply |= executor.data.testapply(applyIntegerPrintBase); + auto applyShiftInfo = SF_TRY(args_interface.template get_type_at(formatIndex)); + ableToapply |= executor.data.testapply(applyShiftInfo); + + if (not ableToapply) + { return std::unexpected(FMTResult::Context_CannotapplyType); } + SF_TRY(manip.skip_one_of('}')); } - else if (access.IsEqualTo('.')) + else if (access.is_equal_to('.')) { - SF_TRY(detail::BufferManip(Format).Forward()); - Executor.Data.FloatPrecision = SF_TRY(FormatReadParameter(-1)); + SF_TRY(buf::Manip(fmtstream).forward()); + executor.data.float_precision = SF_TRY(format_read_parameter(-1)); } - else if (access.IsEqualTo('d', 'b', 'B', 'o', 'O', 'x', 'X')) + else if (access.is_equal_to('d', 'b', 'b', 'o', 'O', 'x', 'X')) { - auto get = SF_TRY(detail::BufferManip(Format).GetAndForward()); - Executor.Data.IntegerPrint = static_cast(get); + auto get = SF_TRY(buf::Manip(fmtstream).get_and_forward()); + executor.data.integer_print = static_cast(get); } - else if (access.IsEqualTo('#')) + else if (access.is_equal_to('#')) { - SF_TRY(detail::BufferManip(Format).Forward()); - Executor.Data.PrefixSuffix = true; + SF_TRY(buf::Manip(fmtstream).forward()); + executor.data.prefix_suffix = true; } - else if (access.IsEqualTo('>')) + else if (access.is_equal_to('>')) { - SF_TRY(detail::BufferManip(Format).Forward()); - SF_TRY(ParseFormatDataSpecial_ShiftType(detail::ShiftInfo::ShiftType::Right)); + SF_TRY(buf::Manip(fmtstream).forward()); + SF_TRY(parse_format_dataSpecial_ShiftType(detail::ShiftInfo::ShiftType::Right)); } - else if (access.IsEqualTo('<')) + else if (access.is_equal_to('<')) { - SF_TRY(detail::BufferManip(Format).Forward()); - SF_TRY(ParseFormatDataSpecial_ShiftType(detail::ShiftInfo::ShiftType::Left)); + SF_TRY(buf::Manip(fmtstream).forward()); + SF_TRY(parse_format_dataSpecial_ShiftType(detail::ShiftInfo::ShiftType::Left)); } - else if (access.IsEqualTo('^')) + else if (access.is_equal_to('^')) { - SF_TRY(detail::BufferManip(Format).Forward()); - if (access.IsEqualTo('<')) + SF_TRY(buf::Manip(fmtstream).forward()); + if (access.is_equal_to('<')) { - SF_TRY(detail::BufferManip(Format).Forward()); - SF_TRY(ParseFormatDataSpecial_ShiftType(detail::ShiftInfo::ShiftType::CenterLeft)); + SF_TRY(buf::Manip(fmtstream).forward()); + SF_TRY(parse_format_dataSpecial_ShiftType(detail::ShiftInfo::ShiftType::CenterLeft)); } else { - manip.IgnoreOneOf('>'); - SF_TRY(ParseFormatDataSpecial_ShiftType(detail::ShiftInfo::ShiftType::CenterRight)); + manip.ignore_one_of('>'); + SF_TRY(parse_format_dataSpecial_ShiftType(detail::ShiftInfo::ShiftType::CenterRight)); } } @@ -180,41 +180,41 @@ namespace stream::fmt::context } template - [[nodiscard]] std::expected BasicContext::ParseFormatDataCustom() + [[nodiscard]] std::expected BasicContext::parse_format_dataCustom() { - detail::BufferTestAccess access(Format); - detail::BufferTestManip manip(Format); + buf::TestAccess access(fmtstream); + buf::TestManip manip(fmtstream); std::basic_string_view name = SF_TRY(manip.ViewExec( - [&] -> std::expected { detail::FMTBufferParamsManip(Format).ParamGoTo(' ', '=', '\'', '{', ','); return {}; } + [&] -> std::expected { buf::FMTParamsManip(fmtstream).param_go_to(' ', '=', '\'', '{', ','); return {}; } )); - detail::FMTBufferParamsManip(Format).ParamGoTo('=', '\'', '{', ','); - manip.IgnoreOneOf('='); - manip.IgnoreEverySpaces(); + buf::FMTParamsManip(fmtstream).param_go_to('=', '\'', '{', ','); + manip.ignore_one_of('='); + manip.ignore_every_spaces(); - if (access.IsEqualTo('\'')) + if (access.is_equal_to('\'')) { - SF_TRY(detail::BufferManip(Format).Forward()); - std::basic_string_view value = SF_TRY(detail::BufferTestManip(Format).ViewUntil('\'')); - SF_TRY(Executor.Data.Specifiers.Concat(detail::FormatSpecifier{name, value})); + SF_TRY(buf::Manip(fmtstream).forward()); + std::basic_string_view value = SF_TRY(buf::TestManip(fmtstream).view_until('\'')); + SF_TRY(executor.data.specifiers.concat(detail::FormatSpecifier{name, value})); } - else if (access.IsADigit()) + else if (access.is_a_digit()) { std::int32_t value = 0; - SF_TRY(detail::BufferReadManip(Format).FastReadInteger(value)); - SF_TRY(Executor.Data.Specifiers.Concat(detail::FormatSpecifier{name, value})); + SF_TRY(buf::ReadManip(fmtstream).fast_read_integer(value)); + SF_TRY(executor.data.specifiers.concat(detail::FormatSpecifier{name, value})); } - else if (access.IsEqualTo('{')) + else if (access.is_equal_to('{')) { - SF_TRY(detail::BufferManip(Format).Forward()); + SF_TRY(buf::Manip(fmtstream).forward()); std::int32_t idx = SF_TRY(GetFormatIndex()); // TODO / FIXME - // Executor.Data.Specifiers.Concat(detail::FormatSpecifier{name, GetTypeAtIndexAuto(idx)}); - SF_TRY(manip.SkipOneOf('}')); + // executor.data.specifiers.concat(detail::FormatSpecifier{name, GetTypeAtIndexAuto(idx)}); + SF_TRY(manip.skip_one_of('}')); } - else if (access.IsEqualTo(',', '}')) + else if (access.is_equal_to(',', '}')) { - SF_TRY(Executor.Data.Specifiers.Concat(detail::FormatSpecifier{name})); + SF_TRY(executor.data.specifiers.concat(detail::FormatSpecifier{name})); } return {}; @@ -222,25 +222,25 @@ namespace stream::fmt::context /////---------- Impl ----------///// template - [[nodiscard]] std::expected BasicContext::ParseFormatData() + [[nodiscard]] std::expected BasicContext::parse_format_data() { - detail::BufferTestAccess access(Format); - detail::BufferTestManip manip(Format); + buf::TestAccess access(fmtstream); + buf::TestManip manip(fmtstream); - Executor.Data.HasSpec = true; - while (detail::BufferAccess(Format).IsEndOfString() == false && detail::FMTBufferParamsManip(Format).IsEndOfParameter() == false) + executor.data.has_spec = true; + while (buf::Access(fmtstream).is_end_of_string() == false && buf::FMTParamsManip(fmtstream).is_end_of_parameter() == false) { - manip.IgnoreEverySpaces(); + manip.ignore_every_spaces(); if (access.IsUpperCase()) - { SF_TRY(ParseFormatDataBase()); } + { SF_TRY(parse_format_data_base()); } else if (!access.IsLowerCase()) - { SF_TRY(ParseFormatDataSpecial()); } + { SF_TRY(parse_format_dataSpecial()); } else - { SF_TRY(ParseFormatDataCustom()); } + { SF_TRY(parse_format_dataCustom()); } - detail::FMTBufferParamsManip(Format).ParamGoTo(','); - detail::BufferTestManip(Format).IgnoreOneOf(','); + buf::FMTParamsManip(fmtstream).param_go_to(','); + buf::TestManip(fmtstream).ignore_one_of(','); } return {}; } @@ -250,11 +250,11 @@ namespace stream::fmt::context [[nodiscard]] std::expected BasicContext::GetFormatIndex_Number() { std::int32_t index = -1; - SF_TRY(detail::BufferReadManip(Format).FastReadInteger(index)); + SF_TRY(buf::ReadManip(fmtstream).fast_read_integer(index)); - if (detail::BufferTestAccess(Format).IsEqualTo(':') || detail::BufferTestAccess(Format).IsEqualTo('}')) + if (buf::TestAccess(fmtstream).is_equal_to(':') || buf::TestAccess(fmtstream).is_equal_to('}')) { - if (index >= 0 && index < ArgsInterface.Size()) + if (index >= 0 && index < args_interface.size()) { return index; } } @@ -263,10 +263,10 @@ namespace stream::fmt::context template [[nodiscard]] std::expected BasicContext::GetFormatIndex_Name() { - std::int32_t index = SF_TRY(ArgsInterface.GetIndexOfCurrentNamedArg(Format)); - if (detail::BufferTestAccess(Format).IsEqualTo(':') || detail::BufferTestAccess(Format).IsEqualTo('}')) + std::int32_t index = SF_TRY(args_interface.get_index_of_current_named_arg(fmtstream)); + if (buf::TestAccess(fmtstream).is_equal_to(':') || buf::TestAccess(fmtstream).is_equal_to('}')) { - if (index >= 0 && index < ArgsInterface.Size()) + if (index >= 0 && index < args_interface.size()) { return index; } } @@ -275,21 +275,21 @@ namespace stream::fmt::context template [[nodiscard]] std::expected BasicContext::GetFormatIndex_SubIndex() { - detail::BufferTestAccess access(Format); - detail::BufferTestManip manip(Format); + buf::TestAccess access(fmtstream); + buf::TestManip manip(fmtstream); - if (access.IsEqualTo('{')) + if (access.is_equal_to('{')) { - SF_TRY(detail::BufferManip(Format).Forward()); + SF_TRY(buf::Manip(fmtstream).forward()); std::int32_t recIndex = SF_TRY(GetFormatIndex()); - if (access.IsEqualTo('}') && recIndex >= 0 && recIndex < ArgsInterface.Size()) + if (access.is_equal_to('}') && recIndex >= 0 && recIndex < args_interface.size()) { - SF_TRY(detail::BufferManip(Format).Forward()); - manip.IgnoreEverySpaces(); - if (access.IsEqualTo(':', '}')) + SF_TRY(buf::Manip(fmtstream).forward()); + manip.ignore_every_spaces(); + if (access.is_equal_to(':', '}')) { - std::int32_t finalRecIndex = (std::int32_t)SF_TRY(ArgsInterface.GetIntAt(recIndex)); - if (finalRecIndex >= 0 && finalRecIndex < ArgsInterface.Size()) + std::int32_t finalRecIndex = (std::int32_t)SF_TRY(args_interface.get_int_at(recIndex)); + if (finalRecIndex >= 0 && finalRecIndex < args_interface.size()) return finalRecIndex; } } @@ -300,15 +300,15 @@ namespace stream::fmt::context template [[nodiscard]] std::expected BasicContext::GetFormatIndex() { - detail::BufferTestAccess access(Format); + buf::TestAccess access(fmtstream); // I : if there is no number specified : ':' or '}' - if (access.IsEqualTo(':') || access.IsEqualTo('}')) - if (ValuesIndex < ArgsInterface.Size()) - { return ValuesIndex++; } + if (access.is_equal_to(':') || access.is_equal_to('}')) + if (values_index < args_interface.size()) + { return values_index++; } // II: A number(idx) - if (access.IsADigit()) + if (access.is_a_digit()) { return SF_FORWARD(GetFormatIndex_Number()); } @@ -320,13 +320,13 @@ namespace stream::fmt::context } // VI : { which is a idx to an argument - if (access.IsEqualTo('{')) + if (access.is_equal_to('{')) { - const TChar* oldPos = Format.CurrentPos; + const TChar* oldPos = fmtstream.current_pos; std::expected res = GetFormatIndex_SubIndex(); if (res.has_value() == false && res.error() == FMTResult::Context_ArgumentIndexResolution) { - Format.CurrentPos = oldPos; + fmtstream.current_pos = oldPos; return std::unexpected(FMTResult::Context_ArgumentIndexResolution); } return SF_FORWARD(res); @@ -338,22 +338,22 @@ namespace stream::fmt::context template [[nodiscard]] std::expected BasicContext::ParseVariable(std::int32_t formatIdx) { - detail::FormatData saveFormatData = Executor.Data; - Executor.Data = detail::FormatData{}; - detail::TextProperties::Properties saveTextProperties = Executor.TextManager.Save(); + detail::FormatData saveFormatData = executor.data; + executor.data = detail::FormatData{}; + detail::TextProperties::Properties saveTextProperties = executor.TextManager.save(); - if (detail::BufferTestAccess(Format).IsEqualTo(':', '{')) + if (buf::TestAccess(fmtstream).is_equal_to(':', '{')) { - SF_TRY(detail::BufferManip(Format).Forward()); - SF_TRY(ParseFormatData()); + SF_TRY(buf::Manip(fmtstream).forward()); + SF_TRY(parse_format_data()); } - SF_TRY(ArgsInterface.RunTypeAtIndex(formatIdx)); + SF_TRY(args_interface.run_type_at(formatIdx)); - if (Executor.Data.KeepNewStyle == false) - { SF_TRY(Executor.TextManager.Reload(saveTextProperties)); } + if (executor.data.keep_new_style == false) + { SF_TRY(executor.TextManager.reload(saveTextProperties)); } - Executor.Data = saveFormatData; + executor.data = saveFormatData; return {}; } @@ -361,25 +361,25 @@ namespace stream::fmt::context template [[nodiscard]] std::expected BasicContext::parse() { - detail::BufferManip(Format).Forward(); // Ignore { + buf::Manip(fmtstream).forward(); // Ignore { - if (detail::BufferTestAccess(Format).IsUpperCase()) + if (buf::TestAccess(fmtstream).IsUpperCase()) { - SF_TRY(ParseFormatData()); - return detail::FMTBufferParamsManip(Format).ParamGoToForward(); // Ignore } + SF_TRY(parse_format_data()); + return buf::FMTParamsManip(fmtstream).param_go_to_forward(); // Ignore } } auto formatIdx = GetFormatIndex(); if (formatIdx.has_value()) { - if (formatIdx.value() >= 0 && formatIdx.value() < ArgsInterface.Size()) + if (formatIdx.value() >= 0 && formatIdx.value() < args_interface.size()) { SF_TRY(ParseVariable(formatIdx.value())); - return detail::FMTBufferParamsManip(Format).ParamGoToForward(); // Ignore } + return buf::FMTParamsManip(fmtstream).param_go_to_forward(); // Ignore } } } - SF_TRY(Executor.ExecRawString("{")); + SF_TRY(executor.exec_raw_string("{")); return {}; } } diff --git a/src/stream/fmt/context/basic_context/text_properties_executor.h b/src/stream/fmt/context/basic_context/text_properties_executor.h index 23976091..b9ccaed8 100644 --- a/src/stream/fmt/context/basic_context/text_properties_executor.h +++ b/src/stream/fmt/context/basic_context/text_properties_executor.h @@ -30,10 +30,10 @@ namespace stream::fmt::detail public: [[nodiscard]] virtual std::expected reset_front() = 0; - [[nodiscard]] virtual std::expected ExecuteFront(const TextProperties::TextFront::FrontID& t) = 0; + [[nodiscard]] virtual std::expected execute_front(const TextProperties::TextFront::FrontID& t) = 0; public: - [[nodiscard]] virtual std::expected ResetStyle() = 0; + [[nodiscard]] virtual std::expected reset_style() = 0; [[nodiscard]] virtual std::expected execute_style(const TextProperties::TextStyle::Intensity& t) = 0; [[nodiscard]] virtual std::expected execute_style(const TextProperties::TextStyle::Italic& t) = 0; [[nodiscard]] virtual std::expected execute_style(const TextProperties::TextStyle::Underline& t) = 0; diff --git a/src/stream/fmt/context/basic_context/text_properties_manager.cpp b/src/stream/fmt/context/basic_context/text_properties_manager.cpp index 9aad21eb..73556045 100644 --- a/src/stream/fmt/context/basic_context/text_properties_manager.cpp +++ b/src/stream/fmt/context/basic_context/text_properties_manager.cpp @@ -2,151 +2,151 @@ namespace stream::fmt::detail { - [[nodiscard]] std::expected TextPropertiesApplyManager::ReloadColorFG(const TextProperties::TextColor::ColorFG& target) + [[nodiscard]] std::expected TextPropertiesapplyManager::reload_color_fg(const TextProperties::TextColor::ColorFG& target) { - if (target.Type != m_CurrentContextProperties.color.Fg.Type) + if (target.type != current_context_properties_.color.fg.type) { - switch (target.Type) + switch (target.type) { case TextProperties::TextColor::ColorType::BasicColor: - return ApplyColor(target.Data.BasicColor); + return apply_color(target.data.basic_color); case TextProperties::TextColor::ColorType::ColorCube: - return ApplyColor(target.Data.ColorCube); + return apply_color(target.data.color_cube); case TextProperties::TextColor::ColorType::Color24b: - return ApplyColor(target.Data.Color24b); + return apply_color(target.data.color24b); } } else { - switch (target.Type) + switch (target.type) { case TextProperties::TextColor::ColorType::BasicColor: - if (m_CurrentContextProperties.color.Fg.Data.BasicColor != target.Data.BasicColor) - return ApplyColor(target.Data.BasicColor); + if (current_context_properties_.color.fg.data.basic_color != target.data.basic_color) + return apply_color(target.data.basic_color); break; case TextProperties::TextColor::ColorType::ColorCube: - if (m_CurrentContextProperties.color.Fg.Data.ColorCube != target.Data.ColorCube) - return ApplyColor(target.Data.ColorCube); + if (current_context_properties_.color.fg.data.color_cube != target.data.color_cube) + return apply_color(target.data.color_cube); break; case TextProperties::TextColor::ColorType::Color24b: - if (m_CurrentContextProperties.color.Fg.Data.Color24b != target.Data.Color24b) - return ApplyColor(target.Data.Color24b); + if (current_context_properties_.color.fg.data.color24b != target.data.color24b) + return apply_color(target.data.color24b); break; } } return {}; } - [[nodiscard]] std::expected TextPropertiesApplyManager::ReloadColorBG(const TextProperties::TextColor::ColorBG& target) + [[nodiscard]] std::expected TextPropertiesapplyManager::reload_color_bg(const TextProperties::TextColor::ColorBG& target) { - if (target.Type != m_CurrentContextProperties.color.Bg.Type) + if (target.type != current_context_properties_.color.bg.type) { - switch (target.Type) + switch (target.type) { case TextProperties::TextColor::ColorType::BasicColor: - return ApplyColor(target.Data.BasicColor); + return apply_color(target.data.basic_color); case TextProperties::TextColor::ColorType::ColorCube: - return ApplyColor(target.Data.ColorCube); + return apply_color(target.data.color_cube); case TextProperties::TextColor::ColorType::Color24b: - return ApplyColor(target.Data.Color24b); + return apply_color(target.data.color24b); } } else { - switch (target.Type) + switch (target.type) { case TextProperties::TextColor::ColorType::BasicColor: - if (m_CurrentContextProperties.color.Bg.Data.BasicColor != target.Data.BasicColor) - return ApplyColor(target.Data.BasicColor); + if (current_context_properties_.color.bg.data.basic_color != target.data.basic_color) + return apply_color(target.data.basic_color); break; case TextProperties::TextColor::ColorType::ColorCube: - if (m_CurrentContextProperties.color.Bg.Data.ColorCube != target.Data.ColorCube) - return ApplyColor(target.Data.ColorCube); + if (current_context_properties_.color.bg.data.color_cube != target.data.color_cube) + return apply_color(target.data.color_cube); break; case TextProperties::TextColor::ColorType::Color24b: - if (m_CurrentContextProperties.color.Bg.Data.Color24b != target.Data.Color24b) - return ApplyColor(target.Data.Color24b); + if (current_context_properties_.color.bg.data.color24b != target.data.color24b) + return apply_color(target.data.color24b); break; } } return {}; } - [[nodiscard]] std::expected TextPropertiesApplyManager::ReloadStyle(const TextProperties::TextStyle::Style& target) + [[nodiscard]] std::expected TextPropertiesapplyManager::reload_style(const TextProperties::TextStyle::Style& target) { - if (target.Intensity != m_CurrentContextProperties.style.Intensity) + if (target.intensity != current_context_properties_.style.intensity) { - SF_TRY(ApplyStyle(target.Intensity)); - m_CurrentContextProperties.style.Intensity = target.Intensity; + SF_TRY(apply_style(target.intensity)); + current_context_properties_.style.intensity = target.intensity; } - if (target.Italic != m_CurrentContextProperties.style.Italic) + if (target.italic != current_context_properties_.style.italic) { - SF_TRY(ApplyStyle(target.Italic)); - m_CurrentContextProperties.style.Italic = target.Italic; + SF_TRY(apply_style(target.italic)); + current_context_properties_.style.italic = target.italic; } - if (target.Blink != m_CurrentContextProperties.style.Blink) + if (target.blink != current_context_properties_.style.blink) { - SF_TRY(ApplyStyle(target.Blink)); - m_CurrentContextProperties.style.Blink = target.Blink; + SF_TRY(apply_style(target.blink)); + current_context_properties_.style.blink = target.blink; } - if (target.Inverted != m_CurrentContextProperties.style.Inverted) + if (target.inverted != current_context_properties_.style.inverted) { - SF_TRY(ApplyStyle(target.Inverted)); - m_CurrentContextProperties.style.Inverted = target.Inverted; + SF_TRY(apply_style(target.inverted)); + current_context_properties_.style.inverted = target.inverted; } - if (target.Ideogram != m_CurrentContextProperties.style.Ideogram) + if (target.ideogram != current_context_properties_.style.ideogram) { - SF_TRY(ApplyStyle(target.Ideogram)); - m_CurrentContextProperties.style.Ideogram = target.Ideogram; + SF_TRY(apply_style(target.ideogram)); + current_context_properties_.style.ideogram = target.ideogram; } - if (target.Script != m_CurrentContextProperties.style.Script) + if (target.script != current_context_properties_.style.script) { - SF_TRY(ApplyStyle(target.Script)); - m_CurrentContextProperties.style.Script = target.Script; + SF_TRY(apply_style(target.script)); + current_context_properties_.style.script = target.script; } - if (target.Underline != m_CurrentContextProperties.style.Underline) + if (target.underline != current_context_properties_.style.underline) { - SF_TRY(ApplyStyle(target.Underline)); - m_CurrentContextProperties.style.Underline = target.Underline; + SF_TRY(apply_style(target.underline)); + current_context_properties_.style.underline = target.underline; } - if (target.UnderlineColor.Type != m_CurrentContextProperties.style.UnderlineColor.Type) + if (target.underline_color.type != current_context_properties_.style.underline_color.type) { - switch (target.UnderlineColor.Type) + switch (target.underline_color.type) { case TextProperties::TextStyle::UnderlineColor::ColorType::Default: - SF_TRY(ApplyStyle(TextProperties::TextStyle::UnderlineColor::ColorCube{TextProperties::TextStyle::UnderlineColor::ColorCube::Default})); + SF_TRY(apply_style(TextProperties::TextStyle::UnderlineColor::ColorCube{TextProperties::TextStyle::UnderlineColor::ColorCube::Default})); break; case TextProperties::TextStyle::UnderlineColor::ColorType::ColorCube: - SF_TRY(ApplyStyle(target.UnderlineColor.Data.ColorCube)); - m_CurrentContextProperties.style.UnderlineColor.Data.ColorCube = target.UnderlineColor.Data.ColorCube; + SF_TRY(apply_style(target.underline_color.data.color_cube)); + current_context_properties_.style.underline_color.data.color_cube = target.underline_color.data.color_cube; break; case TextProperties::TextStyle::UnderlineColor::ColorType::Color24b: - SF_TRY(ApplyStyle(target.UnderlineColor.Data.Color24b)); - m_CurrentContextProperties.style.UnderlineColor.Data.Color24b = target.UnderlineColor.Data.Color24b; + SF_TRY(apply_style(target.underline_color.data.color24b)); + current_context_properties_.style.underline_color.data.color24b = target.underline_color.data.color24b; break; } - m_CurrentContextProperties.style.UnderlineColor.Type = target.UnderlineColor.Type; + current_context_properties_.style.underline_color.type = target.underline_color.type; } else { - switch (target.UnderlineColor.Type) + switch (target.underline_color.type) { case TextProperties::TextStyle::UnderlineColor::ColorType::Default: break; case TextProperties::TextStyle::UnderlineColor::ColorType::ColorCube: - if (m_CurrentContextProperties.style.UnderlineColor.Data.ColorCube != target.UnderlineColor.Data.ColorCube) + if (current_context_properties_.style.underline_color.data.color_cube != target.underline_color.data.color_cube) { - SF_TRY(ApplyStyle(target.UnderlineColor.Data.ColorCube)); - m_CurrentContextProperties.style.UnderlineColor.Data.ColorCube = target.UnderlineColor.Data.ColorCube; + SF_TRY(apply_style(target.underline_color.data.color_cube)); + current_context_properties_.style.underline_color.data.color_cube = target.underline_color.data.color_cube; } break; case TextProperties::TextStyle::UnderlineColor::ColorType::Color24b: - if (m_CurrentContextProperties.style.UnderlineColor.Data.Color24b != target.UnderlineColor.Data.Color24b) + if (current_context_properties_.style.underline_color.data.color24b != target.underline_color.data.color24b) { - SF_TRY(ApplyStyle(target.UnderlineColor.Data.Color24b)); - m_CurrentContextProperties.style.UnderlineColor.Data.Color24b = target.UnderlineColor.Data.Color24b; + SF_TRY(apply_style(target.underline_color.data.color24b)); + current_context_properties_.style.underline_color.data.color24b = target.underline_color.data.color24b; } break; } @@ -154,13 +154,13 @@ namespace stream::fmt::detail return {}; } - [[nodiscard]] std::expected TextPropertiesApplyManager::ReloadFront(const TextProperties::TextFront::Front& target) + [[nodiscard]] std::expected TextPropertiesapplyManager::reload_front(const TextProperties::TextFront::Front& target) { - if (m_CurrentContextProperties.front == target) + if (current_context_properties_.front == target) return {}; - SF_TRY(ApplyFront(target.CurrentID)); - m_CurrentContextProperties.front = target; + SF_TRY(apply_front(target.CurrentID)); + current_context_properties_.front = target; return {}; } } diff --git a/src/stream/fmt/context/basic_context/text_properties_manager.h b/src/stream/fmt/context/basic_context/text_properties_manager.h index 8f4371a6..59693bd4 100644 --- a/src/stream/fmt/context/basic_context/text_properties_manager.h +++ b/src/stream/fmt/context/basic_context/text_properties_manager.h @@ -3,208 +3,208 @@ #include "stream/fmt/detail/prelude.h" #include "text_properties_executor.h" #include "basic_args_interface.h" -#include "stream/fmt/buffer/buffer_info.h" -#include "stream/fmt/buffer/buffer_test_manip.h" -#include "stream/fmt/buffer/utils/buffer_utils.h" +#include "stream/fmt/buf/stream.h" +#include "stream/fmt/buf/test_manip.h" +#include "stream/fmt/buf/utils/buffer_utils.h" namespace stream::fmt::detail { - class TextPropertiesApplyManager + class TextPropertiesapplyManager { public: - TextPropertiesApplyManager(ITextPropertiesExecutor& textPropertiesExecutor) - : m_TextPropertiesExecutor{textPropertiesExecutor} - , m_CurrentContextProperties{} + TextPropertiesapplyManager(ITextPropertiesExecutor& text_properties_executor) + : text_properties_executor_{text_properties_executor} + , current_context_properties_{} {} - [[nodiscard]] std::expected Terminate() { return ReloadDefault(); } + [[nodiscard]] std::expected terminate() { return reload_default(); } public: template - requires detail::TextPropertiesColorCanApply - [[nodiscard]] std::expected ApplyColor(const T& modif) + requires detail::text_properties_color_can_apply + [[nodiscard]] std::expected apply_color(const T& modif) { - m_CurrentContextProperties.color.Apply(modif); - return m_TextPropertiesExecutor.execute_color(modif); + current_context_properties_.color.apply(modif); + return text_properties_executor_.execute_color(modif); } template - requires detail::TextPropertiesStyleCanApply - [[nodiscard]] std::expected ApplyStyle(const T& modif) + requires detail::text_properties_style_can_apply + [[nodiscard]] std::expected apply_style(const T& modif) { - m_CurrentContextProperties.style.Apply(modif); - return m_TextPropertiesExecutor.execute_style(modif); + current_context_properties_.style.apply(modif); + return text_properties_executor_.execute_style(modif); } template - requires detail::TextPropertiesFrontCanApply - [[nodiscard]] std::expected ApplyFront(const T& modif) + requires detail::text_properties_front_can_apply + [[nodiscard]] std::expected apply_front(const T& modif) { - m_CurrentContextProperties.front.Apply(modif); - return m_TextPropertiesExecutor.ExecuteFront(modif); + current_context_properties_.front.apply(modif); + return text_properties_executor_.execute_front(modif); } [[nodiscard]] std::expected all_properties_reset() { - SF_TRY(ApplyColorReset()); - SF_TRY(ApplyStyleReset()); - return ApplyFrontReset(); + SF_TRY(apply_color_reset()); + SF_TRY(apply_style_reset()); + return apply_front_reset(); } - [[nodiscard]] std::expected ApplyColorReset() + [[nodiscard]] std::expected apply_color_reset() { - m_CurrentContextProperties.color.ModifyReset(); - return m_TextPropertiesExecutor.reset_color(); + current_context_properties_.color.modify_reset(); + return text_properties_executor_.reset_color(); } - [[nodiscard]] std::expected ApplyStyleReset() + [[nodiscard]] std::expected apply_style_reset() { - m_CurrentContextProperties.style.ModifyReset(); - return m_TextPropertiesExecutor.ResetStyle(); + current_context_properties_.style.modify_reset(); + return text_properties_executor_.reset_style(); } - [[nodiscard]] std::expected ApplyFrontReset() + [[nodiscard]] std::expected apply_front_reset() { - m_CurrentContextProperties.front.ModifyReset(); - return m_TextPropertiesExecutor.reset_front(); + current_context_properties_.front.modify_reset(); + return text_properties_executor_.reset_front(); } public: - detail::TextProperties::Properties Save() { return m_CurrentContextProperties; } + detail::TextProperties::Properties save() { return current_context_properties_; } public: - [[nodiscard]] std::expected ReloadDefault() + [[nodiscard]] std::expected reload_default() { - SF_TRY(ReloadDefaultColor()); - SF_TRY(ReloadDefaultStyle()); - return ReloadDefaultFront(); + SF_TRY(reload_defaultColor()); + SF_TRY(reload_default_style()); + return reload_default_front(); } - [[nodiscard]] std::expected ReloadDefaultColor() + [[nodiscard]] std::expected reload_defaultColor() { - SF_TRY(ReloadDefaultColorFG()); - return ReloadDefaultColorBG(); + SF_TRY(reload_default_color_fg()); + return reload_default_color_bg(); } - [[nodiscard]] std::expected ReloadDefaultColorFG() { return ReloadColorFG(detail::TextProperties::TextColor::ColorFG{}); } - [[nodiscard]] std::expected ReloadDefaultColorBG() { return ReloadColorBG(detail::TextProperties::TextColor::ColorBG{}); } - [[nodiscard]] std::expected ReloadDefaultStyle() { return ReloadStyle(detail::TextProperties::TextStyle::Style{}); } - [[nodiscard]] std::expected ReloadDefaultFront() { return ReloadFront(detail::TextProperties::TextFront::Front{}); } + [[nodiscard]] std::expected reload_default_color_fg() { return reload_color_fg(detail::TextProperties::TextColor::ColorFG{}); } + [[nodiscard]] std::expected reload_default_color_bg() { return reload_color_bg(detail::TextProperties::TextColor::ColorBG{}); } + [[nodiscard]] std::expected reload_default_style() { return reload_style(detail::TextProperties::TextStyle::Style{}); } + [[nodiscard]] std::expected reload_default_front() { return reload_front(detail::TextProperties::TextFront::Front{}); } - [[nodiscard]] std::expected Reload(const detail::TextProperties::Properties& target) + [[nodiscard]] std::expected reload(const detail::TextProperties::Properties& target) { - SF_TRY(ReloadColor(target.color)); - SF_TRY(ReloadStyle(target.style)); - return ReloadFront(target.front); + SF_TRY(reload_color(target.color)); + SF_TRY(reload_style(target.style)); + return reload_front(target.front); } - [[nodiscard]] std::expected ReloadColor(const detail::TextProperties::TextColor::Color& target) + [[nodiscard]] std::expected reload_color(const detail::TextProperties::TextColor::Color& target) { - SF_TRY(ReloadColorFG(target.Fg)); - return ReloadColorBG(target.Bg); + SF_TRY(reload_color_fg(target.fg)); + return reload_color_bg(target.bg); } - [[nodiscard]] std::expected ReloadColorFG(const detail::TextProperties::TextColor::ColorFG& target); - [[nodiscard]] std::expected ReloadColorBG(const detail::TextProperties::TextColor::ColorBG& target); - [[nodiscard]] std::expected ReloadStyle(const detail::TextProperties::TextStyle::Style& target); - [[nodiscard]] std::expected ReloadFront(const detail::TextProperties::TextFront::Front& target); + [[nodiscard]] std::expected reload_color_fg(const detail::TextProperties::TextColor::ColorFG& target); + [[nodiscard]] std::expected reload_color_bg(const detail::TextProperties::TextColor::ColorBG& target); + [[nodiscard]] std::expected reload_style(const detail::TextProperties::TextStyle::Style& target); + [[nodiscard]] std::expected reload_front(const detail::TextProperties::TextFront::Front& target); public: - ITextPropertiesExecutor& GetTextPropertiesExecutor() { return m_TextPropertiesExecutor; } - detail::TextProperties::Properties& GetCurrentContextProperties() { return m_CurrentContextProperties; } + ITextPropertiesExecutor& get_text_properties_executor() { return text_properties_executor_; } + detail::TextProperties::Properties& get_current_context_properties() { return current_context_properties_; } protected: - ITextPropertiesExecutor& m_TextPropertiesExecutor; - detail::TextProperties::Properties m_CurrentContextProperties; + ITextPropertiesExecutor& text_properties_executor_; + detail::TextProperties::Properties current_context_properties_; public: template - requires detail::TextPropertiesColorCanApply - [[nodiscard]] inline std::expected AskApplyColor(const T& modif) + requires detail::text_properties_color_can_apply + [[nodiscard]] inline std::expected ask_apply_color(const T& modif) { - if (m_CurrentContextProperties.color.NeedModif(modif)) - return ApplyColor(modif); + if (current_context_properties_.color.need_modif(modif)) + return apply_color(modif); return {}; } template - requires detail::TextPropertiesStyleCanApply - [[nodiscard]] inline std::expected AskApplyStyle(const T& modif) + requires detail::text_properties_style_can_apply + [[nodiscard]] inline std::expected ask_apply_style(const T& modif) { - if (m_CurrentContextProperties.style.NeedModif(modif)) - return ApplyStyle(modif); + if (current_context_properties_.style.need_modif(modif)) + return apply_style(modif); return {}; } template - requires detail::TextPropertiesFrontCanApply - [[nodiscard]] inline std::expected AskApplyFront(const T& modif) + requires detail::text_properties_front_can_apply + [[nodiscard]] inline std::expected ask_apply_front(const T& modif) { - if (m_CurrentContextProperties.front.NeedModif(modif)) - return ApplyFront(modif); + if (current_context_properties_.front.need_modif(modif)) + return apply_front(modif); return {}; } - [[nodiscard]] std::expected AskApplyColor(const detail::TextProperties::TextColor::BasicColor& modif) + [[nodiscard]] std::expected ask_apply_color(const detail::TextProperties::TextColor::BasicColor& modif) { - if (m_CurrentContextProperties.color.NeedModif(modif.Fg)) + if (current_context_properties_.color.need_modif(modif.fg)) { - if (m_CurrentContextProperties.color.NeedModif(modif.Bg)) - return ApplyColor(modif); - return ApplyColor(modif.Fg); + if (current_context_properties_.color.need_modif(modif.bg)) + return apply_color(modif); + return apply_color(modif.fg); } - if (m_CurrentContextProperties.color.NeedModif(modif.Fg)) - return ApplyColor(modif.Bg); + if (current_context_properties_.color.need_modif(modif.fg)) + return apply_color(modif.bg); return {}; } - [[nodiscard]] std::expected AskApplyColor(const detail::TextProperties::TextColor::ColorCube& modif) + [[nodiscard]] std::expected ask_apply_color(const detail::TextProperties::TextColor::ColorCube& modif) { - if (m_CurrentContextProperties.color.NeedModif(modif.Fg)) + if (current_context_properties_.color.need_modif(modif.fg)) { - if (m_CurrentContextProperties.color.NeedModif(modif)) - return ApplyColor(modif); - return ApplyColor(modif.Fg); + if (current_context_properties_.color.need_modif(modif)) + return apply_color(modif); + return apply_color(modif.fg); } - if (m_CurrentContextProperties.color.NeedModif(modif.Fg)) - return ApplyColor(modif.Bg); + if (current_context_properties_.color.need_modif(modif.fg)) + return apply_color(modif.bg); return {}; } - [[nodiscard]] std::expected AskApplyColor(const detail::TextProperties::TextColor::Color24b& modif) + [[nodiscard]] std::expected ask_apply_color(const detail::TextProperties::TextColor::Color24b& modif) { - if (m_CurrentContextProperties.color.NeedModif(modif.Fg)) + if (current_context_properties_.color.need_modif(modif.fg)) { - if (m_CurrentContextProperties.color.NeedModif(modif)) - return ApplyColor(modif); - return ApplyColor(modif.Fg); + if (current_context_properties_.color.need_modif(modif)) + return apply_color(modif); + return apply_color(modif.fg); } - if (m_CurrentContextProperties.color.NeedModif(modif.Fg)) - return ApplyColor(modif.Bg); + if (current_context_properties_.color.need_modif(modif.fg)) + return apply_color(modif.bg); return {}; } - [[nodiscard]] std::expected AskApplyColor(const detail::TextProperties::TextColor::ColorFG& modif) { return ReloadColorFG(modif); } - [[nodiscard]] std::expected AskApplyColor(const detail::TextProperties::TextColor::ColorBG& modif) { return ReloadColorBG(modif); } - [[nodiscard]] std::expected AskApplyColor(const detail::TextProperties::TextColor::Color& modif) { return ReloadColor(modif); } + [[nodiscard]] std::expected ask_apply_color(const detail::TextProperties::TextColor::ColorFG& modif) { return reload_color_fg(modif); } + [[nodiscard]] std::expected ask_apply_color(const detail::TextProperties::TextColor::ColorBG& modif) { return reload_color_bg(modif); } + [[nodiscard]] std::expected ask_apply_color(const detail::TextProperties::TextColor::Color& modif) { return reload_color(modif); } }; template - class TextPropertiesManager : public TextPropertiesApplyManager + class TextPropertiesManager : public TextPropertiesapplyManager { public: - TextPropertiesManager(ITextPropertiesExecutor& textPropertiesExecutor) - : TextPropertiesApplyManager(textPropertiesExecutor) + TextPropertiesManager(ITextPropertiesExecutor& text_properties_executor) + : TextPropertiesapplyManager(text_properties_executor) {} public: - [[nodiscard]] std::expected ApplyColorOnIndex(Context::BasicContext& context, std::int32_t index); - [[nodiscard]] std::expected ApplyStyleOnIndex(Context::BasicContext& context, std::int32_t index); - [[nodiscard]] std::expected ApplyFrontOnIndex(Context::BasicContext& context, std::int32_t index); + [[nodiscard]] std::expected apply_colorOnIndex(context::BasicContext& context, std::int32_t index); + [[nodiscard]] std::expected apply_styleOnIndex(context::BasicContext& context, std::int32_t index); + [[nodiscard]] std::expected apply_frontOnIndex(context::BasicContext& context, std::int32_t index); public: - [[nodiscard]] std::expected ParseColor(Context::BasicContext& context); - [[nodiscard]] std::expected ParseStyle(Context::BasicContext& context); - [[nodiscard]] std::expected ParseFront(Context::BasicContext& context); + [[nodiscard]] std::expected parse_color(context::BasicContext& context); + [[nodiscard]] std::expected parse_style(context::BasicContext& context); + [[nodiscard]] std::expected parse_front(context::BasicContext& context); private: template - [[nodiscard]] std::expected GetColorCode(BufferInfoView& format); - [[nodiscard]] std::expected ParseStyleNamed(BufferInfoView& format); - [[nodiscard]] std::expected SelectUnderlinedColorStyle(BufferInfoView& format); + [[nodiscard]] std::expected get_color_code(buf::StreamView& format); + [[nodiscard]] std::expected parse_style_named(buf::StreamView& format); + [[nodiscard]] std::expected select_underlined_color_style(buf::StreamView& format); }; } @@ -212,15 +212,15 @@ namespace stream::fmt::detail { template template - [[nodiscard]] std::expected detail::TextPropertiesManager::GetColorCode(BufferInfoView& format) + [[nodiscard]] std::expected detail::TextPropertiesManager::get_color_code(buf::StreamView& format) { static constexpr std::string_view colorCode[] = {"black", "red", "green", "yellow", "blue", "magenta", "cyan", "white", " ", "default"}; - bool bright = SF_TRY(BufferTestManip(format).IsEqualToForward('+')); + bool bright = SF_TRY(buf::TestManip(format).is_equal_to_forward('+')); std::uint8_t step = static_cast(bright ? T::BaseBStep : T::BaseStep); - std::uint8_t code = (std::uint8_t)SF_TRY(BufferUtilsManip(format).get_word_from_list(colorCode));; + std::uint8_t code = (std::uint8_t)SF_TRY(buf::UtilsManip(format).get_word_from_list(colorCode));; return static_cast(code + step); } } -#include "TextPropertiesManager-impl.h" +#include "text_properties_manager_impl.h" diff --git a/src/stream/fmt/context/basic_context/text_properties_manager_impl.h b/src/stream/fmt/context/basic_context/text_properties_manager_impl.h index 5d9629cf..4f555e1b 100644 --- a/src/stream/fmt/context/basic_context/text_properties_manager_impl.h +++ b/src/stream/fmt/context/basic_context/text_properties_manager_impl.h @@ -2,153 +2,153 @@ #include "text_properties_manager.h" -#include "stream/fmt/buffer/buffer_manip.h" -#include "stream/fmt/buffer/buffer_out_manip.h" -#include "stream/fmt/buffer/buffer_test_manip.h" -#include "stream/fmt/buffer/fmt_buffer_out_manip.h" -#include "stream/fmt/buffer/utils/buffer_utils.h" +#include "stream/fmt/buf/manip.h" +#include "stream/fmt/buf/manip_io.h" +#include "stream/fmt/buf/test_manip.h" +#include "stream/fmt/buf/fmt_manip_io.h" +#include "stream/fmt/buf/utils/buffer_utils.h" namespace stream::fmt::detail { template - [[nodiscard]] std::expected detail::TextPropertiesManager::ApplyColorOnIndex(Context::BasicContext& context, std::int32_t index) + [[nodiscard]] std::expected detail::TextPropertiesManager::apply_colorOnIndex(context::BasicContext& context, std::int32_t index) { - SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const detail::TextProperties::TextColor::Color& data) -> std::expected { this->ReloadColor(data); return {}; })); - SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const detail::TextProperties::TextColor::BasicColorFG& data) -> std::expected { this->AskApplyColor(data); return {}; })); - SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const detail::TextProperties::TextColor::BasicColorBG& data) -> std::expected { this->AskApplyColor(data); return {}; })); - SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const detail::TextProperties::TextColor::ColorCubeFG& data) -> std::expected { this->AskApplyColor(data); return {}; })); - SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const detail::TextProperties::TextColor::ColorCubeBG& data) -> std::expected { this->AskApplyColor(data); return {}; })); - SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const detail::TextProperties::TextColor::Color24bFG& data) -> std::expected { this->AskApplyColor(data); return {}; })); - SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const detail::TextProperties::TextColor::Color24bBG& data) -> std::expected { this->AskApplyColor(data); return {}; })); + SF_TRY(context.args_interface.template run_func_from_type_at( + index, [this](const detail::TextProperties::TextColor::Color& data) -> std::expected { this->reload_color(data); return {}; })); + SF_TRY(context.args_interface.template run_func_from_type_at( + index, [this](const detail::TextProperties::TextColor::BasicColorFG& data) -> std::expected { this->ask_apply_color(data); return {}; })); + SF_TRY(context.args_interface.template run_func_from_type_at( + index, [this](const detail::TextProperties::TextColor::BasicColorBG& data) -> std::expected { this->ask_apply_color(data); return {}; })); + SF_TRY(context.args_interface.template run_func_from_type_at( + index, [this](const detail::TextProperties::TextColor::ColorCubeFG& data) -> std::expected { this->ask_apply_color(data); return {}; })); + SF_TRY(context.args_interface.template run_func_from_type_at( + index, [this](const detail::TextProperties::TextColor::ColorCubeBG& data) -> std::expected { this->ask_apply_color(data); return {}; })); + SF_TRY(context.args_interface.template run_func_from_type_at( + index, [this](const detail::TextProperties::TextColor::Color24bFG& data) -> std::expected { this->ask_apply_color(data); return {}; })); + SF_TRY(context.args_interface.template run_func_from_type_at( + index, [this](const detail::TextProperties::TextColor::Color24bBG& data) -> std::expected { this->ask_apply_color(data); return {}; })); return {}; } template - [[nodiscard]] std::expected detail::TextPropertiesManager::ApplyFrontOnIndex(Context::BasicContext& context, std::int32_t index) + [[nodiscard]] std::expected detail::TextPropertiesManager::apply_frontOnIndex(context::BasicContext& context, std::int32_t index) { - SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const detail::TextProperties::TextFront::Front& data) -> std::expected { this->ReloadFront(data); return {}; })); - SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const detail::TextProperties::TextFront::FrontID& data) -> std::expected { this->AskApplyFront(data); return {}; })); + SF_TRY(context.args_interface.template run_func_from_type_at( + index, [this](const detail::TextProperties::TextFront::Front& data) -> std::expected { this->reload_front(data); return {}; })); + SF_TRY(context.args_interface.template run_func_from_type_at( + index, [this](const detail::TextProperties::TextFront::FrontID& data) -> std::expected { this->ask_apply_front(data); return {}; })); return {}; } template - [[nodiscard]] std::expected detail::TextPropertiesManager::ApplyStyleOnIndex(Context::BasicContext& context, std::int32_t index) + [[nodiscard]] std::expected detail::TextPropertiesManager::apply_styleOnIndex(context::BasicContext& context, std::int32_t index) { - SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const detail::TextProperties::TextStyle::Style& data) -> std::expected { return this->ReloadStyle(data); return {}; })); - SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const detail::TextProperties::TextStyle::Intensity& data) -> std::expected { return this->AskApplyStyle(data); return {}; })); - SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const detail::TextProperties::TextStyle::Italic& data) -> std::expected { return this->AskApplyStyle(data); return {}; })); - SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const detail::TextProperties::TextStyle::Underline& data) -> std::expected { return this->AskApplyStyle(data); return {}; })); - SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const detail::TextProperties::TextStyle::Blink& data) -> std::expected { return this->AskApplyStyle(data); return {}; })); - SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const detail::TextProperties::TextStyle::Inverted& data) -> std::expected { return this->AskApplyStyle(data); return {}; })); - SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const detail::TextProperties::TextStyle::Ideogram& data) -> std::expected { return this->AskApplyStyle(data); return {}; })); - SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const detail::TextProperties::TextStyle::Script& data) -> std::expected { return this->AskApplyStyle(data); return {}; })); - - SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const detail::TextProperties::TextStyle::UnderlineColor::ColorCube& data) -> std::expected { this->AskApplyStyle(data); return {}; })); - SF_TRY(context.ArgsInterface.template RunFuncFromTypeAtIndex( - index, [this](const detail::TextProperties::TextStyle::UnderlineColor::Color24b& data) -> std::expected { this->AskApplyStyle(data); return {}; })); + SF_TRY(context.args_interface.template run_func_from_type_at( + index, [this](const detail::TextProperties::TextStyle::Style& data) -> std::expected { return this->reload_style(data); return {}; })); + SF_TRY(context.args_interface.template run_func_from_type_at( + index, [this](const detail::TextProperties::TextStyle::Intensity& data) -> std::expected { return this->ask_apply_style(data); return {}; })); + SF_TRY(context.args_interface.template run_func_from_type_at( + index, [this](const detail::TextProperties::TextStyle::Italic& data) -> std::expected { return this->ask_apply_style(data); return {}; })); + SF_TRY(context.args_interface.template run_func_from_type_at( + index, [this](const detail::TextProperties::TextStyle::Underline& data) -> std::expected { return this->ask_apply_style(data); return {}; })); + SF_TRY(context.args_interface.template run_func_from_type_at( + index, [this](const detail::TextProperties::TextStyle::Blink& data) -> std::expected { return this->ask_apply_style(data); return {}; })); + SF_TRY(context.args_interface.template run_func_from_type_at( + index, [this](const detail::TextProperties::TextStyle::Inverted& data) -> std::expected { return this->ask_apply_style(data); return {}; })); + SF_TRY(context.args_interface.template run_func_from_type_at( + index, [this](const detail::TextProperties::TextStyle::Ideogram& data) -> std::expected { return this->ask_apply_style(data); return {}; })); + SF_TRY(context.args_interface.template run_func_from_type_at( + index, [this](const detail::TextProperties::TextStyle::Script& data) -> std::expected { return this->ask_apply_style(data); return {}; })); + + SF_TRY(context.args_interface.template run_func_from_type_at( + index, [this](const detail::TextProperties::TextStyle::UnderlineColor::ColorCube& data) -> std::expected { this->ask_apply_style(data); return {}; })); + SF_TRY(context.args_interface.template run_func_from_type_at( + index, [this](const detail::TextProperties::TextStyle::UnderlineColor::Color24b& data) -> std::expected { this->ask_apply_style(data); return {}; })); return {}; } template - [[nodiscard]] std::expected detail::TextPropertiesManager::ParseColor(Context::BasicContext& context) + [[nodiscard]] std::expected detail::TextPropertiesManager::parse_color(context::BasicContext& context) { - if (BufferTestAccess(context.Format).IsEqualTo(':')) + if (buf::TestAccess(context.fmtstream).is_equal_to(':')) { - SF_TRY(BufferManip(context.Format).Forward()); - BufferTestManip(context.Format).IgnoreEverySpaces(); - if (BufferTestAccess(context.Format).IsEqualTo('{')) + SF_TRY(buf::Manip(context.fmtstream).forward()); + buf::TestManip(context.fmtstream).ignore_every_spaces(); + if (buf::TestAccess(context.fmtstream).is_equal_to('{')) { - SF_TRY(BufferManip(context.Format).Forward()); + SF_TRY(buf::Manip(context.fmtstream).forward()); std::int32_t idx = SF_TRY(context.GetFormatIndex()); - SF_TRY(ApplyColorOnIndex(context, idx)); - SF_TRY(BufferTestManip(context.Format).SkipOneOf('}')); + SF_TRY(apply_colorOnIndex(context, idx)); + SF_TRY(buf::TestManip(context.fmtstream).skip_one_of('}')); } else { - auto colorFg = GetColorCode(context.Format); - FMTBufferParamsManip(context.Format).ParamGoTo('-', ','); - if (BufferTestAccess(context.Format).IsEqualTo('-')) + auto color_fg = get_color_code(context.fmtstream); + buf::FMTParamsManip(context.fmtstream).param_go_to('-', ','); + if (buf::TestAccess(context.fmtstream).is_equal_to('-')) { - SF_TRY(BufferManip(context.Format).Forward()); - BufferTestManip(context.Format).IgnoreEverySpaces(); - auto colorBg = GetColorCode(context.Format); - if (colorBg.has_value() && colorFg.has_value()) - { return AskApplyColor(detail::TextProperties::TextColor::BasicColor{colorFg.value(), colorBg.value()}); } + SF_TRY(buf::Manip(context.fmtstream).forward()); + buf::TestManip(context.fmtstream).ignore_every_spaces(); + auto color_bg = get_color_code(context.fmtstream); + if (color_bg.has_value() && color_fg.has_value()) + { return ask_apply_color(detail::TextProperties::TextColor::BasicColor{color_fg.value(), color_bg.value()}); } else - { return ReloadDefaultColor(); } + { return reload_defaultColor(); } } else { - if (colorFg.has_value()) - { return AskApplyColor(colorFg.value()); } + if (color_fg.has_value()) + { return ask_apply_color(color_fg.value()); } else - { return ReloadDefaultColor(); } + { return reload_defaultColor(); } } } } else - { return ReloadDefaultColor(); } + { return reload_defaultColor(); } return {}; } template - [[nodiscard]] std::expected detail::TextPropertiesManager::ParseStyle(Context::BasicContext& context) + [[nodiscard]] std::expected detail::TextPropertiesManager::parse_style(context::BasicContext& context) { - if (BufferTestAccess(context.Format).IsEqualTo(':')) + if (buf::TestAccess(context.fmtstream).is_equal_to(':')) { - SF_TRY(BufferManip(context.Format).Forward()); - if (!BufferTestAccess(context.Format).IsEqualTo('}', ',')) + SF_TRY(buf::Manip(context.fmtstream).forward()); + if (!buf::TestAccess(context.fmtstream).is_equal_to('}', ',')) { bool loop = true; while (loop) { - BufferTestManip(context.Format).IgnoreEverySpaces(); - if (BufferTestAccess(context.Format).IsEqualTo('{')) + buf::TestManip(context.fmtstream).ignore_every_spaces(); + if (buf::TestAccess(context.fmtstream).is_equal_to('{')) { - SF_TRY(BufferManip(context.Format).Forward()); + SF_TRY(buf::Manip(context.fmtstream).forward()); std::int32_t idx = SF_TRY(context.GetFormatIndex()); - ApplyStyleOnIndex(context, idx); - BufferTestManip(context.Format).SkipOneOf('}'); + apply_styleOnIndex(context, idx); + buf::TestManip(context.fmtstream).skip_one_of('}'); } else { - ParseStyleNamed(context.Format); + parse_style_named(context.fmtstream); } - FMTBufferParamsManip(context.Format).ParamGoTo('|', ','); - loop = SF_TRY(BufferTestManip(context.Format).IsEqualToForward('|')); - BufferTestManip(context.Format).IgnoreEverySpaces(); + buf::FMTParamsManip(context.fmtstream).param_go_to('|', ','); + loop = SF_TRY(buf::TestManip(context.fmtstream).is_equal_to_forward('|')); + buf::TestManip(context.fmtstream).ignore_every_spaces(); } } else - { return ReloadDefaultStyle(); } + { return reload_default_style(); } } else - { return ReloadDefaultStyle(); } + { return reload_default_style(); } return {}; } template - [[nodiscard]] std::expected detail::TextPropertiesManager::ParseStyleNamed(BufferInfoView& format) + [[nodiscard]] std::expected detail::TextPropertiesManager::parse_style_named(buf::StreamView& format) { - detail::BufferUtilsManip utils(format); + buf::UtilsManip utils(format); static constexpr std::pair, detail::TextProperties::TextStyle::Intensity> styleIntensity[] = { {"bold", detail::TextProperties::TextStyle::Intensity::Bold}, @@ -188,34 +188,34 @@ namespace stream::fmt::detail {"subscript", detail::TextProperties::TextStyle::Script::Subscript}, {"n-script", detail::TextProperties::TextStyle::Script::AllDisable}}; - std::uint8_t code = (std::uint8_t)SF_TRY(BufferUtilsManip(format).get_word_from_dict_pairs(styleIntensity)); - if (code != 255) return ApplyStyle(detail::TextProperties::TextStyle::Intensity{code}); - code = (std::uint8_t)SF_TRY(BufferUtilsManip(format).get_word_from_dict_pairs(styleItalic)); - if (code != 255) return ApplyStyle(detail::TextProperties::TextStyle::Italic{code}); - code = (std::uint8_t)SF_TRY(BufferUtilsManip(format).get_word_from_dict_pairs(styleBlink)); - if (code != 255) return ApplyStyle(detail::TextProperties::TextStyle::Blink{code}); - code = (std::uint8_t)SF_TRY(BufferUtilsManip(format).get_word_from_dict_pairs(styleInverted)); - if (code != 255) return ApplyStyle(detail::TextProperties::TextStyle::Inverted{code}); - code = (std::uint8_t)SF_TRY(BufferUtilsManip(format).get_word_from_dict_pairs(styleIdeogram)); - if (code != 255) return ApplyStyle(detail::TextProperties::TextStyle::Ideogram{code}); - code = (std::uint8_t)SF_TRY(BufferUtilsManip(format).get_word_from_dict_pairs(styleScript)); - if (code != 255) return ApplyStyle(detail::TextProperties::TextStyle::Script{code}); - - code = (std::uint8_t)SF_TRY(BufferUtilsManip(format).get_word_from_dict_pairs(styleUnderline)); + std::uint8_t code = (std::uint8_t)SF_TRY(buf::UtilsManip(format).get_word_from_dict_pairs(styleIntensity)); + if (code != 255) return apply_style(detail::TextProperties::TextStyle::Intensity{code}); + code = (std::uint8_t)SF_TRY(buf::UtilsManip(format).get_word_from_dict_pairs(styleItalic)); + if (code != 255) return apply_style(detail::TextProperties::TextStyle::Italic{code}); + code = (std::uint8_t)SF_TRY(buf::UtilsManip(format).get_word_from_dict_pairs(styleBlink)); + if (code != 255) return apply_style(detail::TextProperties::TextStyle::Blink{code}); + code = (std::uint8_t)SF_TRY(buf::UtilsManip(format).get_word_from_dict_pairs(styleInverted)); + if (code != 255) return apply_style(detail::TextProperties::TextStyle::Inverted{code}); + code = (std::uint8_t)SF_TRY(buf::UtilsManip(format).get_word_from_dict_pairs(styleIdeogram)); + if (code != 255) return apply_style(detail::TextProperties::TextStyle::Ideogram{code}); + code = (std::uint8_t)SF_TRY(buf::UtilsManip(format).get_word_from_dict_pairs(styleScript)); + if (code != 255) return apply_style(detail::TextProperties::TextStyle::Script{code}); + + code = (std::uint8_t)SF_TRY(buf::UtilsManip(format).get_word_from_dict_pairs(styleUnderline)); if (code != 255) { if (code == (std::uint8_t)detail::TextProperties::TextStyle::Underline::SelectUnderlinedColor) { - detail::TextProperties::TextStyle::UnderlineColor::ColorCube underlineColor = SF_TRY(SelectUnderlinedColorStyle(format)); - return ApplyStyle(underlineColor); + detail::TextProperties::TextStyle::UnderlineColor::ColorCube underlineColor = SF_TRY(select_underlined_color_style(format)); + return apply_style(underlineColor); } - return ApplyStyle(detail::TextProperties::TextStyle::Underline{code}); + return apply_style(detail::TextProperties::TextStyle::Underline{code}); } return {}; } template - [[nodiscard]] std::expected TextPropertiesManager::SelectUnderlinedColorStyle(BufferInfoView& format) + [[nodiscard]] std::expected TextPropertiesManager::select_underlined_color_style(buf::StreamView& format) { // TODO // FIXME @@ -223,20 +223,20 @@ namespace stream::fmt::detail } template - [[nodiscard]] std::expected detail::TextPropertiesManager::ParseFront(Context::BasicContext& context) + [[nodiscard]] std::expected detail::TextPropertiesManager::parse_front(context::BasicContext& context) { static constexpr std::string_view frontCode[] = {"default", "front0", "front1", "front2", "front3", "front4", "front5", "front6", "front7", "front8", "front9"}; - if (BufferTestAccess(context.Format).IsEqualTo(':')) + if (buf::TestAccess(context.fmtstream).is_equal_to(':')) { - SF_TRY(BufferManip(context.Format).Forward()); - BufferTestManip(context.Format).IgnoreEverySpaces(); + SF_TRY(buf::Manip(context.fmtstream).forward()); + buf::TestManip(context.fmtstream).ignore_every_spaces(); - detail::TextProperties::TextFront::FrontID frontID = (std::uint8_t)SF_TRY(BufferUtilsManip(context.Format).get_word_from_list(frontCode)); - return ApplyFront(frontID); + detail::TextProperties::TextFront::FrontID frontID = (std::uint8_t)SF_TRY(buf::UtilsManip(context.fmtstream).get_word_from_list(frontCode)); + return apply_front(frontID); } else - return ReloadDefaultFront(); + return reload_default_front(); return {}; } } diff --git a/src/stream/fmt/context/formatter_executor/basic_formatter_executor.h b/src/stream/fmt/context/formatter_executor/basic_formatter_executor.h index d9c557dc..deff9401 100644 --- a/src/stream/fmt/context/formatter_executor/basic_formatter_executor.h +++ b/src/stream/fmt/context/formatter_executor/basic_formatter_executor.h @@ -2,8 +2,8 @@ #include "stream/fmt/context/basic_context/basic_context.h" -#include "stream/fmt/buffer/fmt_buffer_out_manip.h" -#include "stream/fmt/buffer/buffer_write_manip.h" +#include "stream/fmt/buf/fmt_manip_io.h" +#include "stream/fmt/buf/write_manip.h" #include "formatter_type.h" #include "index_args.h" @@ -21,7 +21,7 @@ namespace stream::fmt::context }; template - class BasicFormatterExecutor : public ContextExecutor + class BasicFormatterExecutor : public context_executor { public: using TChar = CharType; @@ -29,39 +29,39 @@ namespace stream::fmt::context using M_Type = BasicFormatterExecutor; public: - BasicFormatterExecutor(detail::FMTBufferOutInfo& bufferOut, detail::ITextPropertiesExecutor& textPropertiesExecutor); + BasicFormatterExecutor(buf::FMTStreamIO& ostream, detail::ITextPropertiesExecutor& text_properties_executor); ~BasicFormatterExecutor() override = default; - [[nodiscard]] std::expected Terminate(); + [[nodiscard]] std::expected terminate(); public: - detail::FMTBufferOutInfo& BufferOut; + buf::FMTStreamIO& ostream; EndOfStringCharMode EndOfStringChar = EndOfStringCharMode::Optional; - using ContextExecutor::Data; - using ContextExecutor::TextManager; + using context_executor::data; + using context_executor::TextManager; protected: - [[nodiscard]] std::expected ExecRawString(std::basic_string_view sv) override + [[nodiscard]] std::expected exec_raw_string(std::basic_string_view sv) override { - return detail::BufferWriteManip(BufferOut).FastWriteString(sv); + return buf::WriteManip(ostream).fast_write_string(sv); } - [[nodiscard]] std::expected ExecSettings() override; + [[nodiscard]] std::expected exec_settings() override; public: template - [[nodiscard]] std::expected Run_(detail::BufferInfoView format, Args&&... args); + [[nodiscard]] std::expected run_(buf::StreamView format, Args&&... args); template - [[nodiscard]] std::expected Run(Format&& format, Args&&... args); + [[nodiscard]] std::expected run(Format&& format, Args&&... args); public: template - [[nodiscard]] inline std::expected WriteType(Type&& type, Rest&&... rest) + [[nodiscard]] inline std::expected write_type(Type&& type, Rest&&... rest) { - auto&& formatErr = FormatterType>::Type, M_Type>::format(std::forward(type), *this); + auto&& formatErr = FormatterType>::type, M_Type>::format(std::forward(type), *this); SF_TRY(formatErr); if constexpr (sizeof...(rest) > 0) - { SF_TRY(WriteType(std::forward(rest)...)); } + { SF_TRY(write_type(std::forward(rest)...)); } return {}; } }; @@ -70,20 +70,20 @@ namespace stream::fmt::context namespace stream::fmt::context { template - BasicFormatterExecutor::BasicFormatterExecutor(detail::FMTBufferOutInfo& bufferOut, detail::ITextPropertiesExecutor& textPropertiesExecutor) - : ContextExecutor(textPropertiesExecutor) - , BufferOut(bufferOut) + BasicFormatterExecutor::BasicFormatterExecutor(buf::FMTStreamIO& ostream_, detail::ITextPropertiesExecutor& text_properties_executor_) + : context_executor(text_properties_executor_) + , ostream(ostream_) { - textPropertiesExecutor.link_to_executor(this); + text_properties_executor_.link_to_executor(this); } template - [[nodiscard]] std::expected BasicFormatterExecutor::Terminate() + [[nodiscard]] std::expected BasicFormatterExecutor::terminate() { - detail::BufferOutManip(BufferOut).ComputeGeneratedSize(); + buf::ManipIO(ostream).compute_generated_size(); // End char not included in buffer manager context to deduce size correctly - auto res = detail::BufferOutManip(BufferOut).Pushback('\0'); + auto res = buf::ManipIO(ostream).pushback('\0'); if (EndOfStringChar == EndOfStringCharMode::Forced) { SF_TRY(res); } @@ -91,34 +91,34 @@ namespace stream::fmt::context } template - [[nodiscard]] std::expected BasicFormatterExecutor::ExecSettings() + [[nodiscard]] std::expected BasicFormatterExecutor::exec_settings() { - // Indent - auto indent = Data.Specifiers.Get("indent"); + // indent + auto indent = data.specifiers.get("indent"); if (indent != nullptr) - BufferOut.Indent = indent->AsNumber; + ostream.indent = indent->as_number; return {}; } template template - [[nodiscard]] std::expected BasicFormatterExecutor::Run_(detail::BufferInfoView format, Args&&... args) + [[nodiscard]] std::expected BasicFormatterExecutor::run_(buf::StreamView format, Args&&... args) { - auto argsInterface = detail::FormatterArgsInterface, Args...>(*this, std::forward(args)...); + auto args_interface = detail::FormatterArgsInterface, Args...>(*this, std::forward(args)...); - detail::TextProperties::Properties saveTextProperties = TextManager.Save(); - Context::BasicContext context(*this, format, argsInterface); - SF_TRY(context.Run()); - return TextManager.Reload(saveTextProperties); + detail::TextProperties::Properties saveTextProperties = TextManager.save(); + context::BasicContext context(*this, format, args_interface); + SF_TRY(context.run()); + return TextManager.reload(saveTextProperties); } template template - [[nodiscard]] std::expected BasicFormatterExecutor::Run(Format&& formatInput, Args&&... args) + [[nodiscard]] std::expected BasicFormatterExecutor::run(Format&& format_input, Args&&... args) { - return Run_(detail::BufferInfoView{formatInput}, std::forward(args)...); + return run_(buf::StreamView{format_input}, std::forward(args)...); } } -#include "FormatBasics-impl.h" -#include "FormatTextProperties-impl.h" +#include "format_basics_impl.h" +#include "format_text_properties_impl.h" diff --git a/src/stream/fmt/context/formatter_executor/format_basics_impl.h b/src/stream/fmt/context/formatter_executor/format_basics_impl.h index 14717047..fb85ff9a 100644 --- a/src/stream/fmt/context/formatter_executor/format_basics_impl.h +++ b/src/stream/fmt/context/formatter_executor/format_basics_impl.h @@ -2,7 +2,7 @@ #include "basic_formatter_executor.h" -#include "stream/fmt/buffer/FMTBufferWriteManip.h" +#include "stream/fmt/buf/fmt_write_manip.h" namespace stream::fmt { @@ -16,9 +16,9 @@ namespace stream::fmt [[nodiscard]] static std::expected format(const typename FormatterExecutor::detail::template FormatSpecifier& specifier, FormatterExecutor& executor) { if (specifier.ValueIsText) - { SF_TRY(executor.Run("{ '{}', '{}' }", specifier.Name, specifier.AsText)); } + { SF_TRY(executor.run("{ '{}', '{}' }", specifier.name, specifier.as_text)); } else - { SF_TRY(executor.Run("{ '{}', '{}' }", specifier.Name, specifier.AsNumber)); } + { SF_TRY(executor.run("{ '{}', '{}' }", specifier.name, specifier.as_number)); } return {}; } }; @@ -32,18 +32,18 @@ namespace stream::fmt template [[nodiscard]] std::expected FormatObjectArray(const T* const buffer, std::size_t totalsize, FormatterExecutor& executor) { - std::size_t beginIdx = (std::size_t)executor.Data.Specifiers.GetAsNumber("begin", 0); - totalsize = executor.Data.Specifiers.GetAsNumber("totalsize", totalsize); - totalsize = executor.Data.Specifiers.GetAsNumber("end", totalsize); + std::size_t beginIdx = (std::size_t)executor.data.specifiers.get_as_number("begin", 0); + totalsize = executor.data.specifiers.get_as_number("totalsize", totalsize); + totalsize = executor.data.specifiers.get_as_number("end", totalsize); - std::size_t size = executor.Data.Specifiers.GetAsNumber("size", totalsize - beginIdx); + std::size_t size = executor.data.specifiers.get_as_number("size", totalsize - beginIdx); if (size == std::numeric_limits::max()) { return std::unexpected(FMTResult::GivenArgs_UnableToDeduceSize); } - SF_TRY(detail::BufferWriteManip(executor.buffer_out).FastWriteString(executor.Data.Specifiers.GetAsText("begin", STDEnumerableUtility::DefaultBegin))); + SF_TRY(buf::WriteManip(executor.ostream).fast_write_string(executor.data.specifiers.get_as_text("begin", STDEnumerableUtility::DefaultBegin))); - std::basic_string_view join = executor.Data.Specifiers.GetAsText("join", STDEnumerableUtility::DefaultJoin); + std::basic_string_view join = executor.data.specifiers.get_as_text("join", STDEnumerableUtility::DefaultJoin); bool first = true; const T* itbegin = buffer + beginIdx; @@ -54,41 +54,41 @@ namespace stream::fmt if (first) { first = false; } else - { SF_TRY(detail::FMTBufferWriteManip(executor.buffer_out).WriteIndentString(join)); } - SF_TRY(executor.WriteType(*itbegin++)); + { SF_TRY(buf::FMTWriteManip(executor.ostream).write_indent_string(join)); } + SF_TRY(executor.write_type(*itbegin++)); } - return detail::BufferWriteManip(executor.buffer_out).FastWriteString(executor.Data.Specifiers.GetAsText("end", STDEnumerableUtility::DefaultEnd)); + return buf::WriteManip(executor.ostream).fast_write_string(executor.data.specifiers.get_as_text("end", STDEnumerableUtility::DefaultEnd)); } template - [[nodiscard]] std::expected FormatString(const T* buffer, std::size_t size, FormatterExecutor& executor) + [[nodiscard]] std::expected format_string(const T* buffer, std::size_t size, FormatterExecutor& executor) { - std::size_t beginIdx = (std::size_t)executor.Data.Specifiers.GetAsNumber("begin", 0); - size = executor.Data.Specifiers.GetAsNumber("size", size); + std::size_t beginIdx = (std::size_t)executor.data.specifiers.get_as_number("begin", 0); + size = executor.data.specifiers.get_as_number("size", size); if (size == std::numeric_limits::max()) { size = std::basic_string_view(buffer).size(); } - if (executor.Data.Specifiers.Has("array")) + if (executor.data.specifiers.has("array")) return FormatObjectArray(buffer, size, executor); if (beginIdx > size) return {}; const T* begin = buffer + beginIdx; // TODO: current indent ignore shift - if (executor.Data.Specifiers.Has("indent")) - return detail::FMTBufferWriteManip(executor.buffer_out).WriteIndentCharPtr(begin, size); + if (executor.data.specifiers.has("indent")) + return buf::FMTWriteManip(executor.ostream).write_indent_char_ptr(begin, size); - if (executor.Data.PrefixSuffix) - { SF_TRY(detail::BufferOutManip(executor.buffer_out).Pushback('\"')); } + if (executor.data.prefix_suffix) + { SF_TRY(buf::ManipIO(executor.ostream).pushback('\"')); } - if (executor.Data.HasSpec == false) - { SF_TRY(detail::BufferWriteManip(executor.buffer_out).FastWriteCharArray(begin, size)); } + if (executor.data.has_spec == false) + { SF_TRY(buf::WriteManip(executor.ostream).fast_write_char_array(begin, size)); } else - { SF_TRY(detail::FMTBufferWriteManip(executor.buffer_out).WriteCharPtr(begin, size, executor.Data.Shift)); } + { SF_TRY(buf::FMTWriteManip(executor.ostream).write_char_ptr(begin, size, executor.data.shift)); } - if (executor.Data.PrefixSuffix) - { SF_TRY(detail::BufferOutManip(executor.buffer_out).Pushback('\"')); } + if (executor.data.prefix_suffix) + { SF_TRY(buf::ManipIO(executor.ostream).pushback('\"')); } return {}; } @@ -104,19 +104,19 @@ namespace stream::fmt { [[nodiscard]] static std::expected format(const bool t, FormatterExecutor& executor) { - if (executor.Data.PrefixSuffix) + if (executor.data.prefix_suffix) { if (t == true) - return detail::BufferWriteManip(executor.buffer_out).FastWriteStringLitteral("True"); + return buf::WriteManip(executor.ostream).fast_write_string_literal("True"); else - return detail::BufferWriteManip(executor.buffer_out).FastWriteStringLitteral("False"); + return buf::WriteManip(executor.ostream).fast_write_string_literal("False"); } else { if (t == true) - return detail::BufferOutManip(executor.buffer_out).Pushback('1'); + return buf::ManipIO(executor.ostream).pushback('1'); else - return detail::BufferOutManip(executor.buffer_out).Pushback('0'); + return buf::ManipIO(executor.ostream).pushback('0'); } return {}; @@ -124,11 +124,11 @@ namespace stream::fmt }; template - requires (std::is_integral_v && !std::is_floating_point_v && !detail::IsCharType::Value) + requires (std::is_integral_v && !std::is_floating_point_v && !detail::IsCharType::value) struct FormatterType { [[nodiscard]] static inline std::expected format(const T t, FormatterExecutor& executor) - { return detail::FMTBufferWriteManip(executor.buffer_out).WriteIntegerFormatData(t, executor.Data); } + { return buf::FMTWriteManip(executor.ostream).write_integer_format_data(t, executor.data); } }; template @@ -136,15 +136,15 @@ namespace stream::fmt struct FormatterType { [[nodiscard]] static inline std::expected format(const T t, FormatterExecutor& executor) - { return detail::FMTBufferWriteManip(executor.buffer_out).WriteFloatFormatData(t, executor.Data); } + { return buf::FMTWriteManip(executor.ostream).write_float_formatdata(t, executor.data); } }; template - requires detail::IsCharType::Value + requires detail::IsCharType::value struct FormatterType { [[nodiscard]] static inline std::expected format(const T t, FormatterExecutor& executor) - { return detail::BufferOutManip(executor.buffer_out).Pushback(t); } + { return buf::ManipIO(executor.ostream).pushback(t); } }; //-------------------------------------------------------// @@ -157,8 +157,8 @@ namespace stream::fmt [[nodiscard]] static inline std::expected format(const void* const t, FormatterExecutor& executor) { if (t == nullptr) - return detail::BufferOutManip(executor.buffer_out).FastWriteString(executor.Data.GetAsText("null", "nullptr")); - return detail::BufferWriteManip(executor.buffer_out).FastWriteInteger(std::size_t(t)); + return buf::ManipIO(executor.ostream).fast_write_string(executor.data.get_as_text("null", "nullptr")); + return buf::WriteManip(executor.ostream).fast_write_integer(std::size_t(t)); } }; @@ -168,10 +168,10 @@ namespace stream::fmt [[nodiscard]] static inline std::expected format(const T* const t, FormatterExecutor& executor) { if (t == nullptr) - { return detail::BufferWriteManip(executor.buffer_out).FastWriteString(executor.Data.Specifiers.GetAsText("null", "nullptr")); } + { return buf::WriteManip(executor.ostream).fast_write_string(executor.data.specifiers.get_as_text("null", "nullptr")); } - if constexpr (detail::IsCharType::Value) - { return detail::Forwarders::FormatString(t, std::numeric_limits::max(), executor); } + if constexpr (detail::IsCharType::value) + { return detail::Forwarders::format_string(t, std::numeric_limits::max(), executor); } else { detail::Forwarders::FormatObjectArray(t, std::numeric_limits::max(), executor); } @@ -184,11 +184,11 @@ namespace stream::fmt { [[nodiscard]] static inline std::expected format(T const (&t)[SIZE], FormatterExecutor& executor) { - if constexpr (detail::IsCharType::Value) + if constexpr (detail::IsCharType::value) { std::size_t size = SIZE; while (t[size - 1] == '\0') --size; - return detail::Forwarders::FormatString(t, size, executor); + return detail::Forwarders::format_string(t, size, executor); } else { diff --git a/src/stream/fmt/context/formatter_executor/format_text_properties_impl.h b/src/stream/fmt/context/formatter_executor/format_text_properties_impl.h index e4bd20ca..5befd838 100644 --- a/src/stream/fmt/context/formatter_executor/format_text_properties_impl.h +++ b/src/stream/fmt/context/formatter_executor/format_text_properties_impl.h @@ -22,16 +22,16 @@ namespace stream::fmt { [[nodiscard]] static std::expected format(const detail::TextProperties::TextColor::reset_color, FormatterExecutor& executor) { - return executor.TextManager.ApplyColorReset(); + return executor.TextManager.apply_color_reset(); } }; template - struct FormatterType + struct FormatterType { - [[nodiscard]] static std::expected format(const detail::TextProperties::TextStyle::ResetStyle, FormatterExecutor& executor) + [[nodiscard]] static std::expected format(const detail::TextProperties::TextStyle::reset_style, FormatterExecutor& executor) { - return executor.TextManager.ApplyStyleReset(); + return executor.TextManager.apply_style_reset(); } }; @@ -40,7 +40,7 @@ namespace stream::fmt { [[nodiscard]] static std::expected format(const detail::TextProperties::TextFront::reset_front, FormatterExecutor& executor) { - return executor.TextManager.ApplyFrontReset(); + return executor.TextManager.apply_front_reset(); } }; @@ -49,32 +49,32 @@ namespace stream::fmt //---------------------------------------// template - requires detail::TextPropertiesColorIsApply + requires detail::TextPropertiesColorIsapply struct FormatterType { [[nodiscard]] static std::expected format(const T& t, FormatterExecutor& executor) { - return executor.TextManager.AskApplyColor(t); + return executor.TextManager.ask_apply_color(t); } }; template - requires detail::TextPropertiesStyleIsApply + requires detail::TextPropertiesStyleIsapply struct FormatterType { [[nodiscard]] static std::expected format(const T& t, FormatterExecutor& executor) { - return executor.TextManager.AskApplyStyle(t); + return executor.TextManager.ask_apply_style(t); } }; template - requires detail::TextPropertiesFrontIsApply + requires detail::TextPropertiesFrontIsapply struct FormatterType { [[nodiscard]] static std::expected format(const T& t, FormatterExecutor& executor) { - return executor.TextManager.AskApplyFront(t); + return executor.TextManager.ask_apply_front(t); } }; } diff --git a/src/stream/fmt/context/formatter_executor/formatter_args.h b/src/stream/fmt/context/formatter_executor/formatter_args.h index e783c62f..551b64a6 100644 --- a/src/stream/fmt/context/formatter_executor/formatter_args.h +++ b/src/stream/fmt/context/formatter_executor/formatter_args.h @@ -18,20 +18,20 @@ namespace stream::fmt::detail struct FormatterArgs<> { public: - static inline constexpr std::size_t Size() { return 0; } + static inline constexpr std::size_t size() { return 0; } public: template - [[nodiscard]] inline std::expected RunTypeAtIndex(FormatterExecutor&, std::int32_t) + [[nodiscard]] inline std::expected run_type_at(FormatterExecutor&, std::int32_t) { return std::unexpected(FMTResult::ArgsInterface_IndexOutOfBounds); } template - [[nodiscard]] inline std::expected GetIndexOfCurrentNamedArg(BufferInfoView&, std::int32_t) + [[nodiscard]] inline std::expected get_index_of_current_named_arg(buf::StreamView&, std::int32_t) { return std::unexpected(FMTResult::ArgsInterface_CantMatchNamedArgs); } - [[nodiscard]] inline std::expected GetPointerIDAt(std::int32_t) + [[nodiscard]] inline std::expected get_pointerid_at(std::int32_t) { return std::unexpected(FMTResult::ArgsInterface_IndexOutOfBounds); } @@ -58,38 +58,38 @@ namespace stream::fmt::detail const TypeWithoutRef& m_Value; public: - static inline constexpr std::size_t Size() { return sizeof...(Rest) + 1; } + static inline constexpr std::size_t size() { return sizeof...(Rest) + 1; } public: template - [[nodiscard]] inline std::expected RunTypeAtIndex(Executor& executor, std::int32_t idx) + [[nodiscard]] inline std::expected run_type_at(Executor& executor, std::int32_t idx) { if (idx == 0) { - return executor.WriteType(m_Value); + return executor.write_type(m_Value); } - return FormatterArgs::RunTypeAtIndex(executor, idx - 1); + return FormatterArgs::run_type_at(executor, idx - 1); } public: template - [[nodiscard]] inline std::expected GetIndexOfCurrentNamedArg(BufferInfoView& format, std::int32_t beginSearchIndex) + [[nodiscard]] inline std::expected get_index_of_current_named_arg(buf::StreamView& format, std::int32_t beginSearchIndex) { - if constexpr (detail::IsANamedArgs>::value) + if constexpr (detail::IsANamedArgs>::value) { - bool currentIsANamedArg = SF_TRY(detail::FMTBufferParamsManip(format).NextIsNamedArgs(m_Value.GetName())); + bool currentIsANamedArg = SF_TRY(buf::FMTParamsManip(format).next_is_named_args(m_Value.get_name())); if (currentIsANamedArg) return beginSearchIndex; } - return FormatterArgs::GetIndexOfCurrentNamedArg(format, beginSearchIndex + 1); + return FormatterArgs::get_index_of_current_named_arg(format, beginSearchIndex + 1); } public: - [[nodiscard]] inline std::expected GetPointerIDAt(std::int32_t idx) + [[nodiscard]] inline std::expected get_pointerid_at(std::int32_t idx) { if (idx == 0) - return PointerID{.TypeInfo = typeid(const TypeWithoutRef), .Ptr = const_cast(static_cast(&m_Value))}; - return FormatterArgs::GetPointerIDAt(idx - 1); + return PointerID{.type_info = typeid(const TypeWithoutRef), .ptr = const_cast(static_cast(&m_Value))}; + return FormatterArgs::get_pointerid_at(idx - 1); } public: @@ -99,7 +99,7 @@ namespace stream::fmt::detail if (idx == 0) { if constexpr (FMTCanContextConvert) - { return FMTContextConvert::Convert(m_Value); } + { return FMTContextConvert::convert(m_Value); } else { return std::unexpected(FMTResult::ArgsInterface_InvalidConversion); } } @@ -120,39 +120,39 @@ namespace stream::fmt::detail public: FormatterArgsInterface(FormatterExecutor& executor, Args&&... args) : BasicArgsInterface() - , Executor(executor) - , ArgsInterface(std::forward(args)...) + , executor(executor) + , args_interface(std::forward(args)...) {} ~FormatterArgsInterface() override = default; public: - size_t Size() override { return ArgsInterface.Size(); } + size_t size() override { return args_interface.size(); } - [[nodiscard]] std::expected RunTypeAtIndex(std::int32_t idx) override + [[nodiscard]] std::expected run_type_at(std::int32_t idx) override { - return ArgsInterface.RunTypeAtIndex(Executor, idx); + return args_interface.run_type_at(executor, idx); } - [[nodiscard]] std::expected GetIndexOfCurrentNamedArg(BufferInfoView& format) override + [[nodiscard]] std::expected get_index_of_current_named_arg(buf::StreamView& format) override { - return ArgsInterface.GetIndexOfCurrentNamedArg(format, std::int32_t{0}); + return args_interface.get_index_of_current_named_arg(format, std::int32_t{0}); } - [[nodiscard]] std::expected GetPointerIDAt(std::int32_t idx) override + [[nodiscard]] std::expected get_pointerid_at(std::int32_t idx) override { - return ArgsInterface.GetPointerIDAt(idx); + return args_interface.get_pointerid_at(idx); } public: - [[nodiscard]] std::expected, FMTResult> GetStringAt(std::int32_t idx) override + [[nodiscard]] std::expected, FMTResult> get_string_at(std::int32_t idx) override { - return ArgsInterface.template GetConvertedTypeAt>(idx); + return args_interface.template GetConvertedTypeAt>(idx); } - [[nodiscard]] std::expected GetIntAt(std::int32_t idx) override + [[nodiscard]] std::expected get_int_at(std::int32_t idx) override { - return ArgsInterface.template GetConvertedTypeAt(idx); + return args_interface.template GetConvertedTypeAt(idx); } protected: - FormatterExecutor& Executor; - ContextArgsType ArgsInterface; + FormatterExecutor& executor; + ContextArgsType args_interface; }; } diff --git a/src/stream/fmt/context/formatter_executor/formatter_text_properties_executor/formatter_text_properties_executor.h b/src/stream/fmt/context/formatter_executor/formatter_text_properties_executor/formatter_text_properties_executor.h index 68fc1e3b..d19e6fae 100644 --- a/src/stream/fmt/context/formatter_executor/formatter_text_properties_executor/formatter_text_properties_executor.h +++ b/src/stream/fmt/context/formatter_executor/formatter_text_properties_executor/formatter_text_properties_executor.h @@ -1,7 +1,7 @@ #pragma once #include "stream/fmt/context/basic_context/text_properties_executor.h" -#include "stream/fmt/buffer/fmt_buffer_out_manip.h" +#include "stream/fmt/buf/fmt_manip_io.h" #include "stream/fmt/context/formatter_executor/basic_formatter_executor.h" namespace stream::fmt::detail @@ -14,11 +14,11 @@ namespace stream::fmt::detail void link_to_executor(void* executor) override { - Buffer = &reinterpret_cast*>(executor)->BufferOut; + buffer = &reinterpret_cast*>(executor)->ostream; } protected: - detail::FMTBufferOutInfo* Buffer{nullptr}; + buf::FMTStreamIO* buffer{nullptr}; }; } @@ -48,10 +48,10 @@ namespace stream::fmt::detail public: [[nodiscard]] std::expected reset_front() override {} - [[nodiscard]] std::expected ExecuteFront(const detail::TextProperties::TextFront::FrontID&) override {} + [[nodiscard]] std::expected execute_front(const detail::TextProperties::TextFront::FrontID&) override {} public: - [[nodiscard]] std::expected ResetStyle() override {} + [[nodiscard]] std::expected reset_style() override {} [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Intensity&) override {} [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Italic&) override {} [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Underline&) override {} diff --git a/src/stream/fmt/context/formatter_executor/formatter_text_properties_executor/formatter_text_properties_executor_ansi.h b/src/stream/fmt/context/formatter_executor/formatter_text_properties_executor/formatter_text_properties_executor_ansi.h index 3d9de111..ce2aaeef 100644 --- a/src/stream/fmt/context/formatter_executor/formatter_text_properties_executor/formatter_text_properties_executor_ansi.h +++ b/src/stream/fmt/context/formatter_executor/formatter_text_properties_executor/formatter_text_properties_executor_ansi.h @@ -1,145 +1,145 @@ #pragma once -#include "FormatterTextPropertiesExecutor.h" -#include "stream/fmt/detail/IndentHandlers.h" +#include "formatter_text_properties_executor.h" +#include "stream/fmt/detail/indent_handlers.h" namespace stream::fmt::detail { template - class FormatterANSITextPropertiesExecutor final : public IFormatterTextPropertiesExecutor + class FormatterTextPropertiesExecutorANSI final : public IFormatterTextPropertiesExecutor { public: - FormatterANSITextPropertiesExecutor() = default; - ~FormatterANSITextPropertiesExecutor() override = default; + FormatterTextPropertiesExecutorANSI() = default; + ~FormatterTextPropertiesExecutorANSI() override = default; - using IFormatterTextPropertiesExecutor::Buffer; + using IFormatterTextPropertiesExecutor::buffer; public: [[nodiscard]] std::expected all_properties_reset() override { - NoStrideFunction noStride(*Buffer); - return BufferWriteManip(*Buffer).FastWriteStringLitteral("\033[0m"); + NoStrideFunction no_stride(*buffer); + return buf::WriteManip(*buffer).fast_write_string_literal("\033[0m"); } public: [[nodiscard]] std::expected reset_color() override { - NoStrideFunction noStride(*Buffer); - return BufferWriteManip(*Buffer).FastWriteStringLitteral("\033[39;49m"); + NoStrideFunction no_stride(*buffer); + return buf::WriteManip(*buffer).fast_write_string_literal("\033[39;49m"); } [[nodiscard]] std::expected execute_color(const TextProperties::TextColor::BasicColorFG& t) { - NoStrideFunction noStride(*Buffer); - return BufferWriteManip(*Buffer).BasicWriteType("\033[", static_cast(t), "m"); + NoStrideFunction no_stride(*buffer); + return buf::WriteManip(*buffer).basic_write_type("\033[", static_cast(t), "m"); } [[nodiscard]] std::expected execute_color(const TextProperties::TextColor::BasicColorBG& t) { - NoStrideFunction noStride(*Buffer); - return BufferWriteManip(*Buffer).BasicWriteType("\033[", static_cast(t), "m"); + NoStrideFunction no_stride(*buffer); + return buf::WriteManip(*buffer).basic_write_type("\033[", static_cast(t), "m"); } [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::BasicColor& t) override { - NoStrideFunction noStride(*Buffer); - return BufferWriteManip(*Buffer).BasicWriteType("\033[", static_cast(t.Fg), ";", static_cast(t.Bg), "m"); + NoStrideFunction no_stride(*buffer); + return buf::WriteManip(*buffer).basic_write_type("\033[", static_cast(t.fg), ";", static_cast(t.bg), "m"); } [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::Color24bFG& t) override { - NoStrideFunction noStride(*Buffer); - return BufferWriteManip(*Buffer).BasicWriteType("\033[38;2;", t.R, ";", t.G, ";", t.B, "m"); + NoStrideFunction no_stride(*buffer); + return buf::WriteManip(*buffer).basic_write_type("\033[38;2;", t.r, ";", t.g, ";", t.b, "m"); } [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::Color24bBG& t) override { - NoStrideFunction noStride(*Buffer); - return BufferWriteManip(*Buffer).BasicWriteType("\033[48;2;", t.R, ";", t.G, ";", t.B, "m"); + NoStrideFunction no_stride(*buffer); + return buf::WriteManip(*buffer).basic_write_type("\033[48;2;", t.r, ";", t.g, ";", t.b, "m"); } [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::Color24b& t) override { - NoStrideFunction noStride(*Buffer); - return BufferWriteManip(*Buffer).BasicWriteType("\033[38;2;", t.Fg.R, ";", t.Fg.G, ";", t.Fg.B, "; 48; 2;", t.Bg.R, ";", t.Bg.G, ";", t.Bg.B, "m"); + NoStrideFunction no_stride(*buffer); + return buf::WriteManip(*buffer).basic_write_type("\033[38;2;", t.fg.r, ";", t.fg.g, ";", t.fg.b, "; 48; 2;", t.bg.r, ";", t.bg.g, ";", t.bg.b, "m"); } [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::ColorCubeFG& t) override { - NoStrideFunction noStride(*Buffer); - return BufferWriteManip(*Buffer).BasicWriteType("\033[38;5;", t.GetColorRef(), "m"); + NoStrideFunction no_stride(*buffer); + return buf::WriteManip(*buffer).basic_write_type("\033[38;5;", t.get_color_ref(), "m"); } [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::ColorCubeBG& t) override { - NoStrideFunction noStride(*Buffer); - return BufferWriteManip(*Buffer).BasicWriteType("\033[48;5;", t.GetColorRef(), "m"); + NoStrideFunction no_stride(*buffer); + return buf::WriteManip(*buffer).basic_write_type("\033[48;5;", t.get_color_ref(), "m"); } [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::ColorCube& t) override { - NoStrideFunction noStride(*Buffer); - return BufferWriteManip(*Buffer).BasicWriteType("\033[48;5;", t.Fg.GetColorRef(), ";48;5;", t.Bg.GetColorRef(), "m"); + NoStrideFunction no_stride(*buffer); + return buf::WriteManip(*buffer).basic_write_type("\033[48;5;", t.fg.get_color_ref(), ";48;5;", t.bg.get_color_ref(), "m"); } public: [[nodiscard]] std::expected reset_front() override { - NoStrideFunction noStride(*Buffer); - return BufferWriteManip(*Buffer).BasicWriteType("\033[", detail::TextProperties::TextFront::FrontID::DefaultFrontID, "m"); + NoStrideFunction no_stride(*buffer); + return buf::WriteManip(*buffer).basic_write_type("\033[", detail::TextProperties::TextFront::FrontID::DefaultFrontID, "m"); } - [[nodiscard]] std::expected ExecuteFront(const detail::TextProperties::TextFront::FrontID& t) override + [[nodiscard]] std::expected execute_front(const detail::TextProperties::TextFront::FrontID& t) override { - NoStrideFunction noStride(*Buffer); - return BufferWriteManip(*Buffer).BasicWriteType("\033[", t.ID, "m"); + NoStrideFunction no_stride(*buffer); + return buf::WriteManip(*buffer).basic_write_type("\033[", t.ID, "m"); } public: - [[nodiscard]] std::expected ResetStyle() override + [[nodiscard]] std::expected reset_style() override { // TODO - NoStrideFunction noStride(*Buffer); - return BufferWriteManip(*Buffer).FastWriteStringLitteral("\033[0m"); + NoStrideFunction no_stride(*buffer); + return buf::WriteManip(*buffer).fast_write_string_literal("\033[0m"); } [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Intensity& t) override { - NoStrideFunction noStride(*Buffer); - return BufferWriteManip(*Buffer).BasicWriteType("\033[", static_cast(t), "m"); + NoStrideFunction no_stride(*buffer); + return buf::WriteManip(*buffer).basic_write_type("\033[", static_cast(t), "m"); } [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Italic& t) override { - NoStrideFunction noStride(*Buffer); - return BufferWriteManip(*Buffer).BasicWriteType("\033[", static_cast(t), "m"); + NoStrideFunction no_stride(*buffer); + return buf::WriteManip(*buffer).basic_write_type("\033[", static_cast(t), "m"); } [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Underline& t) override { - NoStrideFunction noStride(*Buffer); - return BufferWriteManip(*Buffer).BasicWriteType("\033[", static_cast(t), "m"); + NoStrideFunction no_stride(*buffer); + return buf::WriteManip(*buffer).basic_write_type("\033[", static_cast(t), "m"); } [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::UnderlineColor::Color&) override { - NoStrideFunction noStride(*Buffer); - return BufferWriteManip(*Buffer).BasicWriteType("\033[59m"); + NoStrideFunction no_stride(*buffer); + return buf::WriteManip(*buffer).basic_write_type("\033[59m"); } [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::UnderlineColor::ColorCube& t) override { - NoStrideFunction noStride(*Buffer); - return BufferWriteManip(*Buffer).BasicWriteType("\033[58;5;", t.GetColorRef(), "m"); + NoStrideFunction no_stride(*buffer); + return buf::WriteManip(*buffer).basic_write_type("\033[58;5;", t.get_color_ref(), "m"); } [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::UnderlineColor::Color24b& t) override { - NoStrideFunction noStride(*Buffer); - return BufferWriteManip(*Buffer).BasicWriteType("\033[58;2;", t.R, ";", t.G, ";", t.B, "m"); + NoStrideFunction no_stride(*buffer); + return buf::WriteManip(*buffer).basic_write_type("\033[58;2;", t.r, ";", t.g, ";", t.b, "m"); } [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Blink& t) override { - NoStrideFunction noStride(*Buffer); - return BufferWriteManip(*Buffer).BasicWriteType("\033[", static_cast(t), "m"); + NoStrideFunction no_stride(*buffer); + return buf::WriteManip(*buffer).basic_write_type("\033[", static_cast(t), "m"); } [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Inverted& t) override { - NoStrideFunction noStride(*Buffer); - return BufferWriteManip(*Buffer).BasicWriteType("\033[", static_cast(t), "m"); + NoStrideFunction no_stride(*buffer); + return buf::WriteManip(*buffer).basic_write_type("\033[", static_cast(t), "m"); } [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Ideogram& t) override { - NoStrideFunction noStride(*Buffer); - return BufferWriteManip(*Buffer).BasicWriteType("\033[", static_cast(t), "m"); + NoStrideFunction no_stride(*buffer); + return buf::WriteManip(*buffer).basic_write_type("\033[", static_cast(t), "m"); } [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Script& t) override { - NoStrideFunction noStride(*Buffer); - return BufferWriteManip(*Buffer).BasicWriteType("\033[", static_cast(t), "m"); + NoStrideFunction no_stride(*buffer); + return buf::WriteManip(*buffer).basic_write_type("\033[", static_cast(t), "m"); } }; } diff --git a/src/stream/fmt/context/formatter_executor/formatter_type.h b/src/stream/fmt/context/formatter_executor/formatter_type.h index d6caf1ab..7c5dabed 100644 --- a/src/stream/fmt/context/formatter_executor/formatter_type.h +++ b/src/stream/fmt/context/formatter_executor/formatter_type.h @@ -11,7 +11,7 @@ namespace stream::fmt [[nodiscard]] static std::expected format(const T&, FormatterExecutor& executor) { #ifdef UNKOWN_TYPE_MESSAGE - executor.Run("({C:red}FMT unknow type: {})", typeid(T).name()); + executor.run("({C:red}FMT unknow type: {})", typeid(T).name()); #endif #ifdef UNKOWN_TYPE_FAIL static_assert(false); @@ -24,16 +24,16 @@ namespace stream::fmt }; } -#define STREAMFORMAT_AUTO_FORMATTER(Type, fmt, ...) \ +#define STREAMFORMAT_AUTO_FORMATTER(Type, formatstr, ...) \ template \ struct stream::fmt::FormatterType \ { \ - [[nodiscard]] static std::expected format(const Type& value, FormatterExecutor& executor) { return executor.Run(fmt, __VA_ARGS__); } \ + [[nodiscard]] static std::expected format(const Type&, FormatterExecutor& executor) { return executor.run(formatstr, __VA_ARGS__); } \ }; -#define STREAMFORMAT_AUTO_FORMATTER_T(Type, fmt, ...) \ +#define STREAMFORMAT_AUTO_FORMATTER_T(Type, formatstr, ...) \ template \ struct stream::fmt::FormatterType \ { \ - [[nodiscard]] static std::expected format(const Type&, FormatterExecutor& executor) { return executor.Run(fmt, __VA_ARGS__); } \ + [[nodiscard]] static std::expected format(const Type&, FormatterExecutor& executor) { return executor.run(formatstr, __VA_ARGS__); } \ }; diff --git a/src/stream/fmt/context/formatter_executor/index_args.h b/src/stream/fmt/context/formatter_executor/index_args.h index d7589985..2f35354c 100644 --- a/src/stream/fmt/context/formatter_executor/index_args.h +++ b/src/stream/fmt/context/formatter_executor/index_args.h @@ -10,18 +10,18 @@ namespace stream::fmt public: FCIndexArgs(const std::uint8_t idx, const T& t) : m_Value(t) - , m_Idx(idx) + , idx_(idx) {} public: - inline bool IsRightIdx(std::uint8_t idx) const { return idx == m_Idx; } + inline bool IsRightIdx(std::uint8_t idx) const { return idx == idx_; } public: - inline const T& GetValue() const { return m_Value; } + inline const T& get_value() const { return m_Value; } protected: const T& m_Value; - const std::uint8_t m_Idx; + const std::uint8_t idx_; }; template @@ -30,7 +30,7 @@ namespace stream::fmt template [[nodiscard]] static inline std::expected format(const FCIndexArgs& t, FormatterExecutor& executor) { - return executor.WriteType(t.GetValue()); + return executor.write_type(t.get_value()); } }; } diff --git a/src/stream/fmt/context/formatter_executor/named_args.h b/src/stream/fmt/context/formatter_executor/named_args.h index 9fb23b2d..bc9fed35 100644 --- a/src/stream/fmt/context/formatter_executor/named_args.h +++ b/src/stream/fmt/context/formatter_executor/named_args.h @@ -11,22 +11,22 @@ namespace stream::fmt public: template StringViewNamedArgs(const CharName (&name)[SIZE], const T& t) - : m_Name(name) + : name_(name) , value(t) {} StringViewNamedArgs(std::basic_string_view name, const T& t) - : m_Name(name) + : name_(name) , value(t) {} public: - T& GetValue() { return value; } - const T& GetValue() const { return value; } - std::basic_string_view GetName() const { return m_Name; } + T& get_value() { return value; } + const T& get_value() const { return value; } + std::basic_string_view get_name() const { return name_; } protected: - std::basic_string_view m_Name; + std::basic_string_view name_; const T& value; }; @@ -35,7 +35,7 @@ namespace stream::fmt { [[nodiscard]] static inline std::expected format(const StringViewNamedArgs& t, FormatterExecutor& executor) { - return executor.WriteType(t.GetValue()); + return executor.write_type(t.get_value()); } }; @@ -45,22 +45,22 @@ namespace stream::fmt { public: StringNamedArgs(const std::string& str, const T& t) - : m_Name(str) + : name_(str) , value(t) {} StringNamedArgs(std::string&& str, const T& t) - : m_Name(std::move(str)) + : name_(std::move(str)) , value(t) {} public: - T& GetValue() { return value; } - const T& GetValue() const { return value; } - std::basic_string_view GetName() const { return m_Name; } + T& get_value() { return value; } + const T& get_value() const { return value; } + std::basic_string_view get_name() const { return name_; } protected: - std::basic_string m_Name; + std::basic_string name_; const T& value; }; @@ -69,11 +69,11 @@ namespace stream::fmt { [[nodiscard]] static inline std::expected format(const StringNamedArgs& t, FormatterExecutor& executor) { - return executor.WriteType(t.GetValue()); + return executor.write_type(t.get_value()); } }; - namespace Detail + namespace detail { template struct IsANamedArgs diff --git a/src/stream/fmt/context/formatter_executor/std_enumerable.h b/src/stream/fmt/context/formatter_executor/std_enumerable.h index c0da04e2..7f4f6df7 100644 --- a/src/stream/fmt/context/formatter_executor/std_enumerable.h +++ b/src/stream/fmt/context/formatter_executor/std_enumerable.h @@ -1,7 +1,7 @@ #pragma once #include "formatter_type.h" -#include "stream/fmt/context/utils/ContextFunctions.h" +#include "stream/fmt/context/utils/context_functions.h" #include "stream/fmt/detail/prelude.h" #include @@ -32,14 +32,14 @@ namespace stream::fmt , m_Size(size < 0 ? (std::int32_t)value.size() - beginIdx : size) {} - inline const T& GetValue() const { return m_Value; } + inline const T& get_value() const { return m_Value; } - inline std::basic_string_view GetStrJoin() const { return m_StrJoin; } - inline std::basic_string_view GetStrBegin() const { return m_StrBegin; } - inline std::basic_string_view GetStrEnd() const { return m_StrEnd; } + inline std::basic_string_view get_str_join() const { return m_StrJoin; } + inline std::basic_string_view get_str_begin() const { return m_StrBegin; } + inline std::basic_string_view get_str_end() const { return m_StrEnd; } - inline std::int32_t GetBeginIdx() const { return m_BeginIdx; } - inline std::int32_t GetSize() const { return m_Size; } + inline std::int32_t get_begin_idx() const { return m_BeginIdx; } + inline std::int32_t get_size() const { return m_Size; } private: const T& m_Value; @@ -57,26 +57,26 @@ namespace stream::fmt { [[nodiscard]] static std::expected format(const STDEnumerable& enumerable, FormatterExecutor& executor) { - SF_TRY(executor.buffer_out.WriteIndentStringView(enumerable.GetStrBegin())); - SF_TRY(executor.buffer_out.AddIndent(enumerable.GetStrBegin().size())); + SF_TRY(executor.ostream.write_indent_string_view(enumerable.get_str_begin())); + SF_TRY(executor.ostream.add_indent(enumerable.get_str_begin().size())); { // TODO: Why ? ... - detail::FunctionApplyNextOverride applyNextOverride(executor); + detail::FunctionapplyNextOverride apply_next_override(executor); bool first = true; - std::for_each_n(enumerable.GetValue().cbegin() + enumerable.GetBeginIdx(), enumerable.GetSize(), [&](const auto& element) { + std::for_each_n(enumerable.get_value().cbegin() + enumerable.get_begin_idx(), enumerable.get_size(), [&](const auto& element) { if (first) { first = false; } else - { SF_TRY(executor.buffer_out.WriteIndentStringView(enumerable.GetStrJoin())); } + { SF_TRY(executor.ostream.write_indent_string_view(enumerable.get_str_join())); } - SF_TRY(executor.WriteType(element)); + SF_TRY(executor.write_type(element)); }); } - executor.buffer_out.RemoveIndent(enumerable.GetStrBegin().size()); - SF_TRY(executor.buffer_out.WriteIndentStringView(enumerable.GetStrEnd())); + executor.ostream.remove_indent(enumerable.get_str_begin().size()); + SF_TRY(executor.ostream.write_indent_string_view(enumerable.get_str_end())); } }; @@ -90,13 +90,13 @@ namespace stream::fmt { [[nodiscard]] static inline std::expected format(const T& container, FormatterExecutor& executor) { - STDEnumerable enumerable(container, executor.Data.GetAsText("join", STDEnumerableUtility::DefaultJoin), - executor.Data.GetAsText("begin", STDEnumerableUtility::DefaultBegin), - executor.Data.GetAsText("end", STDEnumerableUtility::DefaultEnd), - executor.Data.GetAsNumber("begin", 0), - executor.Data.GetAsNumber("size", -1)); + STDEnumerable enumerable(container, executor.data.get_as_text("join", STDEnumerableUtility::DefaultJoin), + executor.data.get_as_text("begin", STDEnumerableUtility::DefaultBegin), + executor.data.get_as_text("end", STDEnumerableUtility::DefaultEnd), + executor.data.get_as_number("begin", 0), + executor.data.get_as_number("size", -1)); - return executor.WriteType(enumerable); + return executor.write_type(enumerable); } }; diff --git a/src/stream/fmt/context/formatter_executor/utility_functions.h b/src/stream/fmt/context/formatter_executor/utility_functions.h index ae28886b..c1deff94 100644 --- a/src/stream/fmt/context/formatter_executor/utility_functions.h +++ b/src/stream/fmt/context/formatter_executor/utility_functions.h @@ -2,219 +2,219 @@ #include "basic_formatter_executor.h" -#include "stream/fmt/buffer/buffer_out_manager/dynamic_buffer_out_manager.h" -#include "stream/fmt/buffer/buffer_out_manager/given_buffer_out_manager.h" -#include "stream/fmt/buffer/buffer_out_manager/static_buffer_out_manager.h" +#include "stream/fmt/buf/streamio_manager/dynamic_streamio_manager.h" +#include "stream/fmt/buf/streamio_manager/given_streamio_manager.h" +#include "stream/fmt/buf/streamio_manager/static_streamio_manager.h" -#include "FormatterTextPropertiesExecutor/FormatterANSITextPropertiesExecutor.h" +#include "formatter_text_properties_executor/formatter_text_properties_executor_ansi.h" #include namespace stream::fmt { /////---------- Impl with as Format ----------////// - namespace Detail + namespace detail { template - requires(IsCharType::Value) - [[nodiscard]] std::expected FormatInManager( - detail::BasicBufferOutManager& bufferOutManager, + requires(IsCharType::value) + [[nodiscard]] std::expected format_in_manager( + buf::BasicStreamIOManager& ostream_manager, bool newline, - BufferInfoView format, + buf::StreamView format, Args&&... args ) { using TCharResolved = std::remove_const_t; - detail::FormatterANSITextPropertiesExecutor textPropertiesExecutor; - detail::FMTBufferOutInfo bufferOut = SF_TRY(detail::FMTBufferOutInfo::Create(bufferOutManager)); - Context::BasicFormatterExecutor executor(bufferOut, textPropertiesExecutor); - SF_TRY(executor.Run(format, std::forward(args)...)); - if (newline) SF_TRY(BufferOutManip(bufferOut).Pushback('\n')); - return executor.Terminate(); + detail::FormatterTextPropertiesExecutorANSI text_properties_executor; + buf::FMTStreamIO ostream = SF_TRY(buf::FMTStreamIO::create(ostream_manager)); + context::BasicFormatterExecutor executor(ostream, text_properties_executor); + SF_TRY(executor.run(format, std::forward(args)...)); + if (newline) SF_TRY(buf::ManipIO(ostream).pushback('\n')); + return executor.terminate(); } template - requires(IsCharType::Value) - [[nodiscard]] std::expected FormatInManager(detail::BasicBufferOutManager& bufferOutManager, bool newline, T&& t) + requires(IsCharType::value) + [[nodiscard]] std::expected format_in_manager(buf::BasicStreamIOManager& ostream_manager, bool newline, T&& t) { using TCharResolved = std::remove_const_t; - detail::FormatterANSITextPropertiesExecutor textPropertiesExecutor; - detail::FMTBufferOutInfo bufferOut = SF_TRY(detail::FMTBufferOutInfo::Create(bufferOutManager)); - Context::BasicFormatterExecutor executor(bufferOut, textPropertiesExecutor); - SF_TRY(executor.WriteType(std::forward(t))); - if (newline) SF_TRY(BufferOutManip(bufferOut).Pushback('\n')); - return executor.Terminate(); + detail::FormatterTextPropertiesExecutorANSI text_properties_executor; + buf::FMTStreamIO ostream = SF_TRY(buf::FMTStreamIO::create(ostream_manager)); + context::BasicFormatterExecutor executor(ostream, text_properties_executor); + SF_TRY(executor.write_type(std::forward(t))); + if (newline) SF_TRY(buf::ManipIO(ostream).pushback('\n')); + return executor.terminate(); } } template - requires(detail::IsCharType::Value && detail::ConvertibleToBufferInfoView) - [[nodiscard]] std::expected FormatInChar(TChar (&buffer)[BUFFER_SIZE], Format&& formatInput, Args&&... args) + requires(detail::IsCharType::value && buf::convertible_to_buffer_info_view) + [[nodiscard]] std::expected format_in_char(TChar (&buffer)[BUFFER_SIZE], Format&& format_input, Args&&... args) { - detail::GivenBufferOutManager bufferOutManager(buffer); - return detail::FormatInManager(bufferOutManager, false, detail::BufferInfoView{formatInput}, std::forward(args)...); + buf::GivenStreamIOManager ostream_manager(buffer); + return detail::format_in_manager(ostream_manager, false, buf::StreamView{format_input}, std::forward(args)...); } template - requires(detail::IsCharType::Value && detail::ConvertibleToBufferInfoView) - [[nodiscard]] std::expected FormatInChar(TChar* const buffer, const std::size_t bufferSize, Format&& formatInput, Args&&... args) + requires(detail::IsCharType::value && buf::convertible_to_buffer_info_view) + [[nodiscard]] std::expected format_in_char(TChar* const buffer, const std::size_t buffer_size, Format&& format_input, Args&&... args) { - detail::GivenBufferOutManager bufferOutManager(buffer, bufferSize); - return detail::FormatInManager(bufferOutManager, false, detail::BufferInfoView{formatInput}, std::forward(args)...); + buf::GivenStreamIOManager ostream_manager(buffer, buffer_size); + return detail::format_in_manager(ostream_manager, false, buf::StreamView{format_input}, std::forward(args)...); } template - requires(detail::IsCharType::Value && detail::ConvertibleToBufferInfoView) - [[nodiscard]] std::expected CFilePrint(FILE* stream, Format&& formatInput, Args&&... args) + requires(detail::IsCharType::value && buf::convertible_to_buffer_info_view) + [[nodiscard]] std::expected cfile_print(FILE* stream, Format&& format_input, Args&&... args) { - detail::DynamicBufferOutManager bufferOutManager(256); - SF_TRY(detail::FormatInManager(bufferOutManager, false, detail::BufferInfoView{formatInput}, std::forward(args)...)); + buf::DynamicStreamIOManager ostream_manager(256); + SF_TRY(detail::format_in_manager(ostream_manager, false, buf::StreamView{format_input}, std::forward(args)...)); - std::fwrite(bufferOutManager.GetBuffer(), bufferOutManager.GetLastGeneratedDataSize(), 1, stream); + std::fwrite(ostream_manager.get_buffer(), ostream_manager.get_last_generated_data_size(), 1, stream); std::fflush(stream); return {}; } template - requires(detail::IsCharType::Value && detail::ConvertibleToBufferInfoView) - [[nodiscard]] std::expected CFilePrintLn(FILE* stream, Format&& formatInput, Args&&... args) + requires(detail::IsCharType::value && buf::convertible_to_buffer_info_view) + [[nodiscard]] std::expected cfile_println(FILE* stream, Format&& format_input, Args&&... args) { - detail::DynamicBufferOutManager bufferOutManager(256); - SF_TRY(detail::FormatInManager(bufferOutManager, true, detail::BufferInfoView{formatInput}, std::forward(args)...)); + buf::DynamicStreamIOManager ostream_manager(256); + SF_TRY(detail::format_in_manager(ostream_manager, true, buf::StreamView{format_input}, std::forward(args)...)); - std::fwrite(bufferOutManager.GetBuffer(), bufferOutManager.GetLastGeneratedDataSize(), 1, stream); + std::fwrite(ostream_manager.get_buffer(), ostream_manager.get_last_generated_data_size(), 1, stream); std::fflush(stream); return {}; } template - requires(detail::IsCharType::Value && detail::ConvertibleToBufferInfoView) - [[nodiscard]] std::expected FilePrint(std::basic_ostream& stream, Format&& formatInput, Args&&... args) + requires(detail::IsCharType::value && buf::convertible_to_buffer_info_view) + [[nodiscard]] std::expected file_print(std::basic_ostream& stream, Format&& format_input, Args&&... args) { - detail::DynamicBufferOutManager bufferOutManager(256); - SF_TRY(detail::FormatInManager(bufferOutManager, false, detail::BufferInfoView{formatInput}, std::forward(args)...)); + buf::DynamicStreamIOManager ostream_manager(256); + SF_TRY(detail::format_in_manager(ostream_manager, false, buf::StreamView{format_input}, std::forward(args)...)); - stream.write(bufferOutManager.GetBuffer(), bufferOutManager.GetLastGeneratedDataSize()); + stream.write(ostream_manager.get_buffer(), ostream_manager.get_last_generated_data_size()); stream.flush(); return {}; } template - requires(detail::IsCharType::Value && detail::ConvertibleToBufferInfoView) - [[nodiscard]] std::expected FilePrintLn(std::basic_ostream& stream, Format&& formatInput, Args&&... args) + requires(detail::IsCharType::value && buf::convertible_to_buffer_info_view) + [[nodiscard]] std::expected file_println(std::basic_ostream& stream, Format&& format_input, Args&&... args) { - detail::DynamicBufferOutManager bufferOutManager(256); - SF_TRY(detail::FormatInManager(bufferOutManager, true, detail::BufferInfoView{formatInput}, std::forward(args)...)); + buf::DynamicStreamIOManager ostream_manager(256); + SF_TRY(detail::format_in_manager(ostream_manager, true, buf::StreamView{format_input}, std::forward(args)...)); - stream.write(bufferOutManager.GetBuffer(), bufferOutManager.GetLastGeneratedDataSize()); + stream.write(ostream_manager.get_buffer(), ostream_manager.get_last_generated_data_size()); stream.flush(); return {}; } template - requires(detail::IsCharType::Value && detail::ConvertibleToBufferInfoView) - [[nodiscard]] std::expected FormatInString(std::basic_string& str, Format&& formatInput, Args&&... args) + requires(detail::IsCharType::value && buf::convertible_to_buffer_info_view) + [[nodiscard]] std::expected format_in_string(std::basic_string& str, Format&& format_input, Args&&... args) { - detail::DynamicBufferOutManager bufferOutManager(256); - SF_TRY(detail::FormatInManager(bufferOutManager, false, detail::BufferInfoView{formatInput}, std::forward(args)...)); - str = bufferOutManager.GetLastGeneratedString(); + buf::DynamicStreamIOManager ostream_manager(256); + SF_TRY(detail::format_in_manager(ostream_manager, false, buf::StreamView{format_input}, std::forward(args)...)); + str = ostream_manager.get_last_generated_string_view(); return {}; } template - requires(detail::IsCharType::Value && detail::ConvertibleToBufferInfoView) - [[nodiscard]] inline std::expected, FMTResult> FormatString(Format&& formatInput, Args&&... args) + requires(detail::IsCharType::value && buf::convertible_to_buffer_info_view) + [[nodiscard]] inline std::expected, FMTResult> format_string(Format&& format_input, Args&&... args) { - detail::DynamicBufferOutManager bufferOutManager(256); - SF_TRY(detail::FormatInManager(bufferOutManager, false, detail::BufferInfoView{formatInput}, std::forward(args)...)); - return bufferOutManager.GetLastGeneratedString(); + buf::DynamicStreamIOManager ostream_manager(256); + SF_TRY(detail::format_in_manager(ostream_manager, false, buf::StreamView{format_input}, std::forward(args)...)); + return std::basic_string{ostream_manager.get_last_generated_string_view()}; } /////---------- NO-FORMAT Impl except for string which are formatted to avoid {} ----------////// template - requires(detail::IsCharType::Value) - [[nodiscard]] std::expected FormatInChar(TChar (&buffer)[BUFFER_SIZE], T&& t) + requires(detail::IsCharType::value) + [[nodiscard]] std::expected format_in_char(TChar (&buffer)[BUFFER_SIZE], T&& t) { - detail::GivenBufferOutManager bufferOutManager(buffer, BUFFER_SIZE); - return detail::FormatInManager(bufferOutManager, false, std::forward(t)); + buf::GivenStreamIOManager ostream_manager(buffer, BUFFER_SIZE); + return detail::format_in_manager(ostream_manager, false, std::forward(t)); } template - requires(detail::IsCharType::Value) - [[nodiscard]] std::expected FormatInChar(TChar* const buffer, const std::size_t bufferSize, T&& t) + requires(detail::IsCharType::value) + [[nodiscard]] std::expected format_in_char(TChar* const buffer, const std::size_t buffer_size, T&& t) { - detail::GivenBufferOutManager bufferOutManager(buffer, bufferSize); - return detail::FormatInManager(bufferOutManager, false, std::forward(t)); + buf::GivenStreamIOManager ostream_manager(buffer, buffer_size); + return detail::format_in_manager(ostream_manager, false, std::forward(t)); } template - requires(detail::IsCharType::Value) - [[nodiscard]] std::expected CFilePrint(FILE* stream, T&& t) + requires(detail::IsCharType::value) + [[nodiscard]] std::expected cfile_print(FILE* stream, T&& t) { - detail::DynamicBufferOutManager bufferOutManager(32); - SF_TRY(detail::FormatInManager(bufferOutManager, false, std::forward(t))); + buf::DynamicStreamIOManager ostream_manager(32); + SF_TRY(detail::format_in_manager(ostream_manager, false, std::forward(t))); - std::fwrite(bufferOutManager.GetBuffer(), static_cast(bufferOutManager.GetLastGeneratedDataSize()), 1, stream); + std::fwrite(ostream_manager.get_buffer(), static_cast(ostream_manager.get_last_generated_data_size()), 1, stream); std::fflush(stream); return {}; } template - requires(detail::IsCharType::Value) - [[nodiscard]] std::expected CFilePrintLn(FILE* stream, T&& t) + requires(detail::IsCharType::value) + [[nodiscard]] std::expected cfile_println(FILE* stream, T&& t) { - detail::DynamicBufferOutManager bufferOutManager(32); - SF_TRY(detail::FormatInManager(bufferOutManager, true, std::forward(t))); + buf::DynamicStreamIOManager ostream_manager(32); + SF_TRY(detail::format_in_manager(ostream_manager, true, std::forward(t))); - std::fwrite(bufferOutManager.GetBuffer(), static_cast(bufferOutManager.GetLastGeneratedDataSize()), 1, stream); + std::fwrite(ostream_manager.get_buffer(), static_cast(ostream_manager.get_last_generated_data_size()), 1, stream); std::fflush(stream); return {}; } template - requires(detail::IsCharType::Value) - [[nodiscard]] std::expected FilePrint(std::basic_ostream& stream, T&& t) + requires(detail::IsCharType::value) + [[nodiscard]] std::expected file_print(std::basic_ostream& stream, T&& t) { - detail::DynamicBufferOutManager bufferOutManager(32); - SF_TRY(detail::FormatInManager(bufferOutManager, false, std::forward(t))); + buf::DynamicStreamIOManager ostream_manager(32); + SF_TRY(detail::format_in_manager(ostream_manager, false, std::forward(t))); - stream.write(bufferOutManager.GetBuffer(), static_cast(bufferOutManager.GetLastGeneratedDataSize())); + stream.write(ostream_manager.get_buffer(), static_cast(ostream_manager.get_last_generated_data_size())); stream.flush(); return {}; } template - requires(detail::IsCharType::Value) - [[nodiscard]] std::expected FilePrintLn(std::basic_ostream& stream, T&& t) + requires(detail::IsCharType::value) + [[nodiscard]] std::expected file_println(std::basic_ostream& stream, T&& t) { - detail::DynamicBufferOutManager bufferOutManager(32); - SF_TRY(detail::FormatInManager(bufferOutManager, true, std::forward(t))); + buf::DynamicStreamIOManager ostream_manager(32); + SF_TRY(detail::format_in_manager(ostream_manager, true, std::forward(t))); - stream.write(bufferOutManager.GetBuffer(), static_cast(bufferOutManager.GetLastGeneratedDataSize())); + stream.write(ostream_manager.get_buffer(), static_cast(ostream_manager.get_last_generated_data_size())); stream.flush(); return {}; } template - requires(detail::IsCharType::Value) - [[nodiscard]] std::expected FormatInString(std::basic_string& str, T&& t) + requires(detail::IsCharType::value) + [[nodiscard]] std::expected format_in_string(std::basic_string& str, T&& t) { - detail::DynamicBufferOutManager bufferOutManager(32); - SF_TRY(detail::FormatInManager(bufferOutManager, false, std::forward(t))); - str = bufferOutManager.GetLastGeneratedString(); + buf::DynamicStreamIOManager ostream_manager(32); + SF_TRY(detail::format_in_manager(ostream_manager, false, std::forward(t))); + str = ostream_manager.get_last_generated_string_view(); return {}; } template - requires(detail::IsCharType::Value) - [[nodiscard]] inline std::expected, FMTResult> FormatString(T&& t) + requires(detail::IsCharType::value) + [[nodiscard]] inline std::expected, FMTResult> format_string(T&& t) { - detail::DynamicBufferOutManager bufferOutManager(32); - SF_TRY(detail::FormatInManager(bufferOutManager, false, std::forward(t))); - return bufferOutManager.GetLastGeneratedString(); + buf::DynamicStreamIOManager ostream_manager(32); + SF_TRY(detail::format_in_manager(ostream_manager, false, std::forward(t))); + return std::string{ostream_manager.get_last_generated_string_view()}; } } @@ -228,47 +228,47 @@ namespace stream::fmt switch(result) { case FMTResult::FunctionNotImpl: - return detail::BufferWriteManip(executor.buffer_out).FastWriteStringLitteral("FunctionNotImpl"); + return buf::WriteManip(executor.ostream).fast_write_string_literal("FunctionNotImpl"); case FMTResult::Buffer_NonValid: - return detail::BufferWriteManip(executor.buffer_out).FastWriteStringLitteral("Buffer_NonValid"); + return buf::WriteManip(executor.ostream).fast_write_string_literal("Buffer_NonValid"); case FMTResult::Buffer_OutOfBoundAccess: - return detail::BufferWriteManip(executor.buffer_out).FastWriteStringLitteral("Buffer_OutOfBoundAccess"); + return buf::WriteManip(executor.ostream).fast_write_string_literal("Buffer_OutOfBoundAccess"); case FMTResult::Buffer_UnableToReserveMemory: - return detail::BufferWriteManip(executor.buffer_out).FastWriteStringLitteral("Buffer_UnableToReserveMemory"); + return buf::WriteManip(executor.ostream).fast_write_string_literal("Buffer_UnableToReserveMemory"); case FMTResult::Parse_NonValidDigit: - return detail::BufferWriteManip(executor.buffer_out).FastWriteStringLitteral("Parse_NonValidDigit"); + return buf::WriteManip(executor.ostream).fast_write_string_literal("Parse_NonValidDigit"); case FMTResult::Parse_TokenNotExpected: - return detail::BufferWriteManip(executor.buffer_out).FastWriteStringLitteral("Parse_TokenNotExpected"); + return buf::WriteManip(executor.ostream).fast_write_string_literal("Parse_TokenNotExpected"); case FMTResult::ArgsInterface_Unavaible: - return detail::BufferWriteManip(executor.buffer_out).FastWriteStringLitteral("ArgsInterface_Unavaible"); + return buf::WriteManip(executor.ostream).fast_write_string_literal("ArgsInterface_Unavaible"); case FMTResult::ArgsInterface_InvalidTypeID: - return detail::BufferWriteManip(executor.buffer_out).FastWriteStringLitteral("ArgsInterface_InvalidTypeID"); + return buf::WriteManip(executor.ostream).fast_write_string_literal("ArgsInterface_InvalidTypeID"); case FMTResult::ArgsInterface_InvalidConversion: - return detail::BufferWriteManip(executor.buffer_out).FastWriteStringLitteral("ArgsInterface_InvalidConversion"); + return buf::WriteManip(executor.ostream).fast_write_string_literal("ArgsInterface_InvalidConversion"); case FMTResult::ArgsInterface_CantMatchNamedArgs: - return detail::BufferWriteManip(executor.buffer_out).FastWriteStringLitteral("ArgsInterface_CantMatchNamedArgs"); + return buf::WriteManip(executor.ostream).fast_write_string_literal("ArgsInterface_CantMatchNamedArgs"); case FMTResult::ArgsInterface_IndexOutOfBounds: - return detail::BufferWriteManip(executor.buffer_out).FastWriteStringLitteral("ArgsInterface_IndexOutOfBounds"); - case FMTResult::Specifers_Full: - return detail::BufferWriteManip(executor.buffer_out).FastWriteStringLitteral("Specifers_Full"); - case FMTResult::Specifers_Invalid: - return detail::BufferWriteManip(executor.buffer_out).FastWriteStringLitteral("Specifers_Invalid"); - case FMTResult::Specifers_DoesNotExist: - return detail::BufferWriteManip(executor.buffer_out).FastWriteStringLitteral("Specifers_DoesNotExist"); + return buf::WriteManip(executor.ostream).fast_write_string_literal("ArgsInterface_IndexOutOfBounds"); + case FMTResult::Specifiers_Full: + return buf::WriteManip(executor.ostream).fast_write_string_literal("Specifiers_Full"); + case FMTResult::Specifiers_Invalid: + return buf::WriteManip(executor.ostream).fast_write_string_literal("Specifiers_Invalid"); + case FMTResult::Specifiers_DoesNotExist: + return buf::WriteManip(executor.ostream).fast_write_string_literal("Specifiers_DoesNotExist"); case FMTResult::Context_ParsingFormat: - return detail::BufferWriteManip(executor.buffer_out).FastWriteStringLitteral("Context_ParsingFormat"); + return buf::WriteManip(executor.ostream).fast_write_string_literal("Context_ParsingFormat"); case FMTResult::Context_ArgumentIndexResolution: - return detail::BufferWriteManip(executor.buffer_out).FastWriteStringLitteral("Context_ArgumentIndexResolution"); + return buf::WriteManip(executor.ostream).fast_write_string_literal("Context_ArgumentIndexResolution"); case FMTResult::Context_ArgumentIndexExpected: - return detail::BufferWriteManip(executor.buffer_out).FastWriteStringLitteral("Context_ArgumentIndexExpected"); - case FMTResult::Context_CannotApplyType: - return detail::BufferWriteManip(executor.buffer_out).FastWriteStringLitteral("Context_CannotApplyType"); + return buf::WriteManip(executor.ostream).fast_write_string_literal("Context_ArgumentIndexExpected"); + case FMTResult::Context_CannotapplyType: + return buf::WriteManip(executor.ostream).fast_write_string_literal("Context_CannotapplyType"); case FMTResult::GivenArgs_UnableToDeduceSize: - return detail::BufferWriteManip(executor.buffer_out).FastWriteStringLitteral("GivenArgs_UnableToDeduceSize"); + return buf::WriteManip(executor.ostream).fast_write_string_literal("GivenArgs_UnableToDeduceSize"); case FMTResult::Manager_StaticMemory: - return detail::BufferWriteManip(executor.buffer_out).FastWriteStringLitteral("Manager_StaticMemory"); + return buf::WriteManip(executor.ostream).fast_write_string_literal("Manager_StaticMemory"); case FMTResult::Manager_AllocationFailed: - return detail::BufferWriteManip(executor.buffer_out).FastWriteStringLitteral("Manager_AllocationFailed"); + return buf::WriteManip(executor.ostream).fast_write_string_literal("Manager_AllocationFailed"); } } }; diff --git a/src/stream/fmt/context/parser_executor/basic_parser_executor.h b/src/stream/fmt/context/parser_executor/basic_parser_executor.h index 071bb3ba..0c7118dd 100644 --- a/src/stream/fmt/context/parser_executor/basic_parser_executor.h +++ b/src/stream/fmt/context/parser_executor/basic_parser_executor.h @@ -1,21 +1,21 @@ #pragma once -#include "stream/fmt/buffer/buffer_info.h" -#include "stream/fmt/buffer/buffer_manip.h" -#include "stream/fmt/buffer/buffer_test_manip.h" +#include "stream/fmt/buf/stream.h" +#include "stream/fmt/buf/manip.h" +#include "stream/fmt/buf/test_manip.h" #include "stream/fmt/context/basic_context/basic_context.h" -#include "ParserType.h" +#include "parser_type.h" -#include "ParserArgs.h" +#include "parser_args.h" -#include "ParserTextPropertiesExecutor/ParserTextPropertiesExecutor.h" +#include "parser_text_properties_executor/parser_text_properties_executor.h" namespace stream::fmt::context { template - class BasicParserExecutor : public ContextExecutor + class BasicParserExecutor : public context_executor { public: using TChar = CharType; @@ -23,39 +23,39 @@ namespace stream::fmt::context using M_Type = BasicParserExecutor; public: - BasicParserExecutor(detail::BufferInfoView& bufferIn, detail::ITextPropertiesExecutor& textPropertiesExecutor); + BasicParserExecutor(buf::StreamView& istream, detail::ITextPropertiesExecutor& text_properties_executor); ~BasicParserExecutor() override = default; - [[nodiscard]] std::expected Terminate(); + [[nodiscard]] std::expected terminate(); public: - detail::BufferInfoView& BufferIn; + buf::StreamView& istream; - using ContextExecutor::Data; - using ContextExecutor::TextManager; + using context_executor::data; + using context_executor::TextManager; protected: - [[nodiscard]] std::expected ExecRawString(std::basic_string_view sv) override + [[nodiscard]] std::expected exec_raw_string(std::basic_string_view sv) override { - SF_TRY(detail::BufferTestManip(BufferIn).is_same_forward(sv.data(), sv.size())); + SF_TRY(buf::TestManip(istream).is_same_forward(sv.data(), sv.size())); return {}; } - [[nodiscard]] std::expected ExecSettings() override { return {}; }; + [[nodiscard]] std::expected exec_settings() override { return {}; }; public: template - [[nodiscard]] std::expected Run_(detail::BufferInfoView format, Args&&... args); + [[nodiscard]] std::expected run_(buf::StreamView format, Args&&... args); template - [[nodiscard]] std::expected Run(Format&& format, Args&&... args); + [[nodiscard]] std::expected run(Format&& format, Args&&... args); public: template - [[nodiscard]] inline std::expected ReadType(Type& type, Rest&... rest) + [[nodiscard]] inline std::expected read_type(Type& type, Rest&... rest) { - auto&& parseErr = ParserType>::Type, M_Type>::parse(type, *this); + auto&& parseErr = ParserType>::type, M_Type>::parse(type, *this); SF_TRY(parseErr); if constexpr (sizeof...(rest) > 0) - SF_TRY(ReadType(std::forward(rest)...)); + SF_TRY(read_type(std::forward(rest)...)); return {}; } }; @@ -64,38 +64,38 @@ namespace stream::fmt::context namespace stream::fmt::context { template - BasicParserExecutor::BasicParserExecutor(detail::BufferInfoView& bufferIn, detail::ITextPropertiesExecutor& textPropertiesExecutor) - : ContextExecutor(textPropertiesExecutor) - , BufferIn{bufferIn} + BasicParserExecutor::BasicParserExecutor(buf::StreamView& istream_, detail::ITextPropertiesExecutor& text_properties_executor_) + : context_executor(text_properties_executor_) + , istream{istream_} { - textPropertiesExecutor.link_to_executor(this); + text_properties_executor_.link_to_executor(this); } template - [[nodiscard]] std::expected BasicParserExecutor::Terminate() + [[nodiscard]] std::expected BasicParserExecutor::terminate() { return {}; } template template - [[nodiscard]] std::expected BasicParserExecutor::Run_(detail::BufferInfoView format, Args&&... args) + [[nodiscard]] std::expected BasicParserExecutor::run_(buf::StreamView format, Args&&... args) { - auto argsInterface = detail::ParserArgsInterface, Args...>(*this, std::forward(args)...); + auto args_interface = detail::ParserArgsInterface, Args...>(*this, std::forward(args)...); - detail::TextProperties::Properties saveTextProperties = TextManager.Save(); - Context::BasicContext context(*this, format, argsInterface); - SF_TRY(context.Run()); - return TextManager.Reload(saveTextProperties); + detail::TextProperties::Properties saveTextProperties = TextManager.save(); + context::BasicContext context(*this, format, args_interface); + SF_TRY(context.run()); + return TextManager.reload(saveTextProperties); } template template - [[nodiscard]] std::expected BasicParserExecutor::Run(Format&& formatInput, Args&&... args) + [[nodiscard]] std::expected BasicParserExecutor::run(Format&& format_input, Args&&... args) { - return Run_(detail::BufferInfoView{formatInput}, std::forward(args)...); + return run_(buf::StreamView{format_input}, std::forward(args)...); } } -#include "ParseBasics-impl.h" -#include "ParseTextProperties-impl.h" +#include "parse_basics_impl.h" +#include "parse_text_properties_impl.h" diff --git a/src/stream/fmt/context/parser_executor/parse_basics_impl.h b/src/stream/fmt/context/parser_executor/parse_basics_impl.h index 57a0b571..896426af 100644 --- a/src/stream/fmt/context/parser_executor/parse_basics_impl.h +++ b/src/stream/fmt/context/parser_executor/parse_basics_impl.h @@ -1,7 +1,7 @@ #pragma once -#include "BasicParserExecutor.h" -#include "stream/fmt/buffer/FMTBufferReadManip.h" +#include "basic_parser_executor.h" +#include "stream/fmt/buf/fmt_read_manip.h" namespace stream::fmt { @@ -18,37 +18,37 @@ namespace stream::fmt { [[nodiscard]] static std::expected parse(bool& t, ParserExecutor& executor) { - if (!executor.Data.PrefixSuffix) + if (!executor.data.prefix_suffix) { - if (detail::BufferTestAccess(executor.BufferIn).IsEqualTo('t', 'T')) + if (buf::TestAccess(executor.istream).is_equal_to('t', 'T')) { - SF_TRY(detail::BufferManip(executor.BufferIn).Forward()); - if (detail::BufferTestAccess(executor.BufferIn).IsSame("rue")) + SF_TRY(buf::Manip(executor.istream).forward()); + if (buf::TestAccess(executor.istream).is_same("rue")) { - SF_TRY(detail::BufferManip(executor.BufferIn).Forward()); + SF_TRY(buf::Manip(executor.istream).forward()); t = true; } } - else if (detail::BufferTestAccess(executor.BufferIn).IsEqualTo('f', 'F')) + else if (buf::TestAccess(executor.istream).is_equal_to('f', 'F')) { - SF_TRY(detail::BufferManip(executor.BufferIn).Forward()); - if (detail::BufferTestAccess(executor.BufferIn).IsSame("alse")) + SF_TRY(buf::Manip(executor.istream).forward()); + if (buf::TestAccess(executor.istream).is_same("alse")) { - SF_TRY(detail::BufferManip(executor.BufferIn).Forward()); + SF_TRY(buf::Manip(executor.istream).forward()); t = false; } } } else { - if (detail::BufferTestAccess(executor.BufferIn).IsEqualTo('1')) + if (buf::TestAccess(executor.istream).is_equal_to('1')) { - SF_TRY(detail::BufferManip(executor.BufferIn).Forward()); + SF_TRY(buf::Manip(executor.istream).forward()); t = true; } - else if (detail::BufferTestAccess(executor.BufferIn).IsEqualTo('0')) + else if (buf::TestAccess(executor.istream).is_equal_to('0')) { - SF_TRY(detail::BufferManip(executor.BufferIn).Forward()); + SF_TRY(buf::Manip(executor.istream).forward()); t = false; } } @@ -57,11 +57,11 @@ namespace stream::fmt }; template - requires (std::is_integral_v && !std::is_floating_point_v && !detail::IsCharType::Value) + requires (std::is_integral_v && !std::is_floating_point_v && !detail::IsCharType::value) struct ParserType { [[nodiscard]] static inline std::expected parse(T& t, ParserExecutor& executor) - { return detail::FMTBufferReadManip(executor.BufferIn).ReadIntegerFormatData(t, executor.Data); } + { return buf::FMTReadManip(executor.istream).read_integer_format_data(t, executor.data); } }; template @@ -69,7 +69,7 @@ namespace stream::fmt struct ParserType { [[nodiscard]] static inline std::expected parse(T& t, ParserExecutor& executor) - { return detail::FMTBufferReadManip(executor.BufferIn).ReadFloatFormatData(t, executor.Data); } + { return buf::FMTReadManip(executor.istream).read_float_format_data(t, executor.data); } }; //-------------------------------------------------------// diff --git a/src/stream/fmt/context/parser_executor/parse_text_properties_impl.h b/src/stream/fmt/context/parser_executor/parse_text_properties_impl.h index 0d773946..8e2168c9 100644 --- a/src/stream/fmt/context/parser_executor/parse_text_properties_impl.h +++ b/src/stream/fmt/context/parser_executor/parse_text_properties_impl.h @@ -1,6 +1,6 @@ #pragma once -#include "BasicParserExecutor.h" +#include "basic_parser_executor.h" namespace stream::fmt { @@ -22,16 +22,16 @@ namespace stream::fmt { [[nodiscard]] static inline std::expected parse(detail::TextProperties::TextColor::reset_color, ParserExecutor& executor) { - return executor.TextManager.ApplyColorReset(); + return executor.TextManager.apply_color_reset(); } }; template - struct ParserType + struct ParserType { - [[nodiscard]] static inline std::expected parse(detail::TextProperties::TextStyle::ResetStyle, ParserExecutor& executor) + [[nodiscard]] static inline std::expected parse(detail::TextProperties::TextStyle::reset_style, ParserExecutor& executor) { - return executor.TextManager.ApplyStyleReset(); + return executor.TextManager.apply_style_reset(); } }; @@ -40,7 +40,7 @@ namespace stream::fmt { [[nodiscard]] static inline std::expected parse(detail::TextProperties::TextFront::reset_front, ParserExecutor& executor) { - return executor.TextManager.ApplyFrontReset(); + return executor.TextManager.apply_front_reset(); } }; @@ -49,32 +49,32 @@ namespace stream::fmt //---------------------------------------// template - requires detail::TextPropertiesColorIsApply + requires detail::TextPropertiesColorIsapply struct ParserType { [[nodiscard]] static inline std::expected parse(T& t, ParserExecutor& executor) { - return executor.TextManager.AskApplyColor(t); + return executor.TextManager.ask_apply_color(t); } }; template - requires detail::TextPropertiesStyleIsApply + requires detail::TextPropertiesStyleIsapply struct ParserType { [[nodiscard]] static inline std::expected parse(T& t, ParserExecutor& executor) { - return executor.TextManager.AskApplyStyle(t); + return executor.TextManager.ask_apply_style(t); } }; template - requires detail::TextPropertiesFrontIsApply + requires detail::TextPropertiesFrontIsapply struct ParserType { [[nodiscard]] static inline std::expected parse(T& t, ParserExecutor& executor) { - return executor.TextManager.AskApplyFront(t); + return executor.TextManager.ask_apply_front(t); } }; } diff --git a/src/stream/fmt/context/parser_executor/parser_args.h b/src/stream/fmt/context/parser_executor/parser_args.h index 5de27197..d9fa377a 100644 --- a/src/stream/fmt/context/parser_executor/parser_args.h +++ b/src/stream/fmt/context/parser_executor/parser_args.h @@ -18,20 +18,20 @@ namespace stream::fmt::detail ParserArgs() = default; public: - static inline constexpr std::size_t Size() { return 0; } + static inline constexpr std::size_t size() { return 0; } public: template - [[nodiscard]] inline std::expected RunTypeAtIndex(FormatterExecutor&, std::int32_t) + [[nodiscard]] inline std::expected run_type_at(FormatterExecutor&, std::int32_t) { return std::unexpected(FMTResult::ArgsInterface_IndexOutOfBounds); } template - [[nodiscard]] inline std::expected GetIndexOfCurrentNamedArg(BufferInfoView& format, std::int32_t) + [[nodiscard]] inline std::expected get_index_of_current_named_arg(buf::StreamView& format, std::int32_t) { return std::unexpected(FMTResult::ArgsInterface_CantMatchNamedArgs); } - [[nodiscard]] inline std::expected GetPointerIDAt(std::int32_t) + [[nodiscard]] inline std::expected get_pointerid_at(std::int32_t) { return std::unexpected(FMTResult::ArgsInterface_IndexOutOfBounds); } @@ -58,37 +58,37 @@ namespace stream::fmt::detail TypeWithoutRef& m_Value; public: - static inline constexpr std::size_t Size() { return sizeof...(Rest) + 1; } + static inline constexpr std::size_t size() { return sizeof...(Rest) + 1; } public: template - [[nodiscard]] inline std::expected RunTypeAtIndex(Executor& executor, std::int32_t idx) + [[nodiscard]] inline std::expected run_type_at(Executor& executor, std::int32_t idx) { if (idx == 0) { - return executor.ReadType(m_Value); + return executor.read_type(m_Value); } - return ParserArgs::RunTypeAtIndex(executor, idx - 1); + return ParserArgs::run_type_at(executor, idx - 1); } public: template - [[nodiscard]] inline std::expected GetIndexOfCurrentNamedArg(BufferInfoView& format, std::int32_t beginSearchIndex) + [[nodiscard]] inline std::expected get_index_of_current_named_arg(buf::StreamView& format, std::int32_t beginSearchIndex) { - if constexpr (detail::IsANamedArgs>::value) + if constexpr (detail::IsANamedArgs>::value) { - bool currentIsANamedArg = SF_TRY(detail::FMTBufferParamsManip(format).NextIsNamedArgs(m_Value.GetName())); + bool currentIsANamedArg = SF_TRY(buf::FMTParamsManip(format).next_is_named_args(m_Value.get_name())); if (currentIsANamedArg) return beginSearchIndex; } - return ParserArgs::GetIndexOfCurrentNamedArg(format, beginSearchIndex + 1); + return ParserArgs::get_index_of_current_named_arg(format, beginSearchIndex + 1); } public: - [[nodiscard]] inline std::expected GetPointerIDAt(std::int32_t idx) + [[nodiscard]] inline std::expected get_pointerid_at(std::int32_t idx) { - if (idx == 0) return PointerID{.TypeInfo = typeid(TypeWithoutRef), .Ptr = static_cast(&m_Value)}; - return ParserArgs::GetPointerIDAt(idx - 1); + if (idx == 0) return PointerID{.type_info = typeid(TypeWithoutRef), .ptr = static_cast(&m_Value)}; + return ParserArgs::get_pointerid_at(idx - 1); } public: @@ -98,7 +98,7 @@ namespace stream::fmt::detail if (idx == 0) { if constexpr (FMTCanContextConvert) - { return FMTContextConvert::Convert(m_Value); } + { return FMTContextConvert::convert(m_Value); } else { return std::unexpected(FMTResult::ArgsInterface_InvalidConversion); } } @@ -119,40 +119,40 @@ namespace stream::fmt::detail public: ParserArgsInterface(ParserExecutor& executor, Args&&... args) : BasicArgsInterface() - , Executor(executor) - , ArgsInterface(std::forward(args)...) + , executor(executor) + , args_interface(std::forward(args)...) {} ~ParserArgsInterface() override = default; public: - std::size_t Size() override { return ArgsInterface.Size(); } + std::size_t size() override { return args_interface.size(); } public: - [[nodiscard]] std::expected RunTypeAtIndex(std::int32_t idx) override + [[nodiscard]] std::expected run_type_at(std::int32_t idx) override { - return ArgsInterface.RunTypeAtIndex(Executor, idx); + return args_interface.run_type_at(executor, idx); } - [[nodiscard]] std::expected GetIndexOfCurrentNamedArg(BufferInfoView& format) override + [[nodiscard]] std::expected get_index_of_current_named_arg(buf::StreamView& format) override { - return ArgsInterface.GetIndexOfCurrentNamedArg(format, std::int32_t{0}); + return args_interface.get_index_of_current_named_arg(format, std::int32_t{0}); } - [[nodiscard]] inline std::expected GetPointerIDAt(std::int32_t idx) override + [[nodiscard]] inline std::expected get_pointerid_at(std::int32_t idx) override { - return ArgsInterface.GetPointerIDAt(idx); + return args_interface.get_pointerid_at(idx); } public: - [[nodiscard]] std::expected, FMTResult> GetStringAt(std::int32_t idx) override + [[nodiscard]] std::expected, FMTResult> get_string_at(std::int32_t idx) override { - return ArgsInterface.template GetConvertedTypeAt>(idx); + return args_interface.template GetConvertedTypeAt>(idx); } - [[nodiscard]] std::expected GetIntAt(std::int32_t idx) override + [[nodiscard]] std::expected get_int_at(std::int32_t idx) override { - return ArgsInterface.template GetConvertedTypeAt(idx); + return args_interface.template GetConvertedTypeAt(idx); } protected: - ParserExecutor& Executor; - ContextArgsType ArgsInterface; + ParserExecutor& executor; + ContextArgsType args_interface; }; } diff --git a/src/stream/fmt/context/parser_executor/parser_text_properties_executor/parser_text_properties_executor.h b/src/stream/fmt/context/parser_executor/parser_text_properties_executor/parser_text_properties_executor.h index 5ed25490..65e798b3 100644 --- a/src/stream/fmt/context/parser_executor/parser_text_properties_executor/parser_text_properties_executor.h +++ b/src/stream/fmt/context/parser_executor/parser_text_properties_executor/parser_text_properties_executor.h @@ -2,7 +2,7 @@ #include "stream/fmt/context/basic_context/text_properties_executor.h" #include "stream/fmt/detail/prelude.h" -#include "stream/fmt/context/ParserExecutor/BasicParserExecutor.h" +#include "stream/fmt/context/parser_executor/basic_parser_executor.h" namespace stream::fmt::detail { @@ -15,11 +15,11 @@ namespace stream::fmt::detail void link_to_executor(void* executor) override { - Buffer = &reinterpret_cast*>(executor)->BufferIn; + buffer = &reinterpret_cast*>(executor)->istream; } protected: - BufferInfoView* Buffer{nullptr}; + buf::StreamView* buffer{nullptr}; }; } @@ -32,7 +32,7 @@ namespace stream::fmt::detail ParserNOTextPropertiesExecutor() = default; ~ParserNOTextPropertiesExecutor() override = default; - using IParserTextPropertiesExecutor::Buffer; + using IParserTextPropertiesExecutor::buffer; public: [[nodiscard]] std::expected all_properties_reset() override { return {}; } @@ -51,10 +51,10 @@ namespace stream::fmt::detail public: [[nodiscard]] std::expected reset_front() override { return {}; } - [[nodiscard]] std::expected ExecuteFront(const detail::TextProperties::TextFront::FrontID&) override { return {}; } + [[nodiscard]] std::expected execute_front(const detail::TextProperties::TextFront::FrontID&) override { return {}; } public: - [[nodiscard]] std::expected ResetStyle() override { return {}; } + [[nodiscard]] std::expected reset_style() override { return {}; } [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Intensity&) override { return {}; } [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Italic&) override { return {}; } [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Underline&) override { return {}; } diff --git a/src/stream/fmt/context/parser_executor/parser_text_properties_executor/parser_text_properties_executor_ansi.h b/src/stream/fmt/context/parser_executor/parser_text_properties_executor/parser_text_properties_executor_ansi.h index 6c408ee8..f5141b39 100644 --- a/src/stream/fmt/context/parser_executor/parser_text_properties_executor/parser_text_properties_executor_ansi.h +++ b/src/stream/fmt/context/parser_executor/parser_text_properties_executor/parser_text_properties_executor_ansi.h @@ -1,6 +1,6 @@ #pragma once -#include "ParserTextPropertiesExecutor.h" +#include "parser_text_properties_executor.h" namespace stream::fmt::detail { @@ -11,134 +11,134 @@ namespace stream::fmt::detail ParserANSITextPropertiesExecutor() = default; ~ParserANSITextPropertiesExecutor() override = default; - using IParserTextPropertiesExecutor::Buffer; + using IParserTextPropertiesExecutor::buffer; public: [[nodiscard]] std::expected all_properties_reset() override { return std::unexpected(FMTResult::FunctionNotImpl); - /*BufferReadManip(buffer).BasicReadType('\033', '[', 0, 'm');*/ + /*ReadManip(buffer).BasicReadType('\033', '[', 0, 'm');*/ } public: [[nodiscard]] std::expected reset_color() override { return std::unexpected(FMTResult::FunctionNotImpl); - /*BufferReadManip(buffer).BasicReadType('\033', '[', 39, ';', 49, 'm');*/ + /*ReadManip(buffer).BasicReadType('\033', '[', 39, ';', 49, 'm');*/ } [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::BasicColorFG&) override { return std::unexpected(FMTResult::FunctionNotImpl); - /*BufferReadManip(buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ + /*ReadManip(buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ } [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::BasicColorBG&) override { return std::unexpected(FMTResult::FunctionNotImpl); - /*BufferReadManip(buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ + /*ReadManip(buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ } [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::BasicColor&) override { return std::unexpected(FMTResult::FunctionNotImpl); - /*BufferReadManip(buffer).BasicReadType('\033', '[', static_cast(t.Fg) , ';', static_cast(t.Bg), 'm');*/ + /*ReadManip(buffer).BasicReadType('\033', '[', static_cast(t.fg) , ';', static_cast(t.bg), 'm');*/ } [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::Color24bFG&) override { return std::unexpected(FMTResult::FunctionNotImpl); - /*BufferReadManip(buffer).BasicReadType("\033[38;2;", t.R, ';', t.G, ';', t.B, 'm');*/ + /*ReadManip(buffer).BasicReadType("\033[38;2;", t.r, ';', t.g, ';', t.b, 'm');*/ } [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::Color24bBG&) override { return std::unexpected(FMTResult::FunctionNotImpl); - /*BufferReadManip(buffer).BasicReadType("\033[48;2;", t.R, ';', t.G, ';', t.B, 'm');*/ + /*ReadManip(buffer).BasicReadType("\033[48;2;", t.r, ';', t.g, ';', t.b, 'm');*/ } [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::Color24b&) override { return std::unexpected(FMTResult::FunctionNotImpl); - /*BufferReadManip(buffer).BasicReadType("\033[38;2;", t.Fg.R, ';', t.Fg.G, ';', t.Fg.B, "; 48; 2;", t.Bg.R, ';', t.Bg.G, ';', t.Bg.B, 'm');*/ + /*ReadManip(buffer).BasicReadType("\033[38;2;", t.fg.r, ';', t.fg.g, ';', t.fg.b, "; 48; 2;", t.bg.r, ';', t.bg.g, ';', t.bg.b, 'm');*/ } [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::ColorCubeFG&) override { return std::unexpected(FMTResult::FunctionNotImpl); - /*BufferReadManip(buffer).BasicReadType("\033[38;5;", t.GetColorRef(), 'm');*/ + /*ReadManip(buffer).BasicReadType("\033[38;5;", t.get_color_ref(), 'm');*/ } [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::ColorCubeBG&) override { return std::unexpected(FMTResult::FunctionNotImpl); - /*BufferReadManip(buffer).BasicReadType("\033[48;5;", t.GetColorRef(), 'm');*/ + /*ReadManip(buffer).BasicReadType("\033[48;5;", t.get_color_ref(), 'm');*/ } [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::ColorCube&) override { return std::unexpected(FMTResult::FunctionNotImpl); - /*BufferReadManip(buffer).BasicReadType("\033[48;5;", t.Fg.GetColorRef(), ";48;5;", t.Bg.GetColorRef(), 'm');*/ + /*ReadManip(buffer).BasicReadType("\033[48;5;", t.fg.get_color_ref(), ";48;5;", t.bg.get_color_ref(), 'm');*/ } public: [[nodiscard]] std::expected reset_front() override { return std::unexpected(FMTResult::FunctionNotImpl); - /*BufferReadManip(buffer).BasicReadType('\033', '[', detail::TextProperties::TextFront::FrontID::DefaultFrontID, 'm');*/ + /*ReadManip(buffer).BasicReadType('\033', '[', detail::TextProperties::TextFront::FrontID::DefaultFrontID, 'm');*/ } - [[nodiscard]] std::expected ExecuteFront(const detail::TextProperties::TextFront::FrontID&) override + [[nodiscard]] std::expected execute_front(const detail::TextProperties::TextFront::FrontID&) override { return std::unexpected(FMTResult::FunctionNotImpl); - /*BufferReadManip(buffer).BasicReadType('\033', '[', t.ID, 'm');*/ + /*ReadManip(buffer).BasicReadType('\033', '[', t.ID, 'm');*/ } public: - [[nodiscard]] std::expected ResetStyle() override + [[nodiscard]] std::expected reset_style() override { return std::unexpected(FMTResult::FunctionNotImpl); - /*BufferReadManip(buffer).BasicReadType('\033', '[', 0, 'm');*/ + /*ReadManip(buffer).BasicReadType('\033', '[', 0, 'm');*/ } [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Intensity&) override { return std::unexpected(FMTResult::FunctionNotImpl); - /*BufferReadManip(buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ + /*ReadManip(buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ } [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Italic&) override { return std::unexpected(FMTResult::FunctionNotImpl); - /*BufferReadManip(buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ + /*ReadManip(buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ } [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Underline&) override { return std::unexpected(FMTResult::FunctionNotImpl); - /*BufferReadManip(buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ + /*ReadManip(buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ } [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::UnderlineColor::Color&) override { return std::unexpected(FMTResult::FunctionNotImpl); - /*BufferReadManip(buffer).BasicReadType("\033[59m");*/ + /*ReadManip(buffer).BasicReadType("\033[59m");*/ } [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::UnderlineColor::ColorCube&) override { return std::unexpected(FMTResult::FunctionNotImpl); - /*BufferReadManip(buffer).BasicReadType("\033[58;5;", t.GetColorRef(), 'm');*/ + /*ReadManip(buffer).BasicReadType("\033[58;5;", t.get_color_ref(), 'm');*/ } [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::UnderlineColor::Color24b&) override { return std::unexpected(FMTResult::FunctionNotImpl); - /*BufferReadManip(buffer).BasicReadType("\033[58;2;", t.R, ';', t.G, ';', t.B, 'm');*/ + /*ReadManip(buffer).BasicReadType("\033[58;2;", t.r, ';', t.g, ';', t.b, 'm');*/ } [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Blink&) override { return std::unexpected(FMTResult::FunctionNotImpl); - /*BufferReadManip(buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ + /*ReadManip(buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ } [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Inverted&) override { return std::unexpected(FMTResult::FunctionNotImpl); - /*BufferReadManip(buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ + /*ReadManip(buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ } [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Ideogram&) override { return std::unexpected(FMTResult::FunctionNotImpl); - /*BufferReadManip(buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ + /*ReadManip(buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ } [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Script&) override { return std::unexpected(FMTResult::FunctionNotImpl); - /*BufferReadManip(buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ + /*ReadManip(buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ } }; } diff --git a/src/stream/fmt/context/parser_executor/parser_type.h b/src/stream/fmt/context/parser_executor/parser_type.h index 1350763c..68e54d9b 100644 --- a/src/stream/fmt/context/parser_executor/parser_type.h +++ b/src/stream/fmt/context/parser_executor/parser_type.h @@ -5,7 +5,7 @@ #define STREAMFORMAT_PARSER_DECLARED namespace stream::fmt { - template > + template > struct ParserType { static inline bool parse(T&, ParserExecutor&) @@ -27,9 +27,9 @@ namespace stream::fmt } -#define STREAMFORMAT_AUTO_PARSER(Type, fmt, ...) \ +#define STREAMFORMAT_AUTO_PARSER(type, fmt, ...) \ template \ struct stream::fmt::ParserType \ { \ - static bool parse(Type& value, ParserExecutor& executor) { return executor.Run(fmt, __VA_ARGS__); } \ + static bool parse(Type& value, ParserExecutor& executor) { return executor.run(fmt, __VA_ARGS__); } \ }; diff --git a/src/stream/fmt/context/parser_executor/utility_functions.h b/src/stream/fmt/context/parser_executor/utility_functions.h index b1686316..64ad48dc 100644 --- a/src/stream/fmt/context/parser_executor/utility_functions.h +++ b/src/stream/fmt/context/parser_executor/utility_functions.h @@ -1,24 +1,24 @@ #pragma once -#include "BasicParserExecutor.h" +#include "basic_parser_executor.h" -#include "stream/fmt/buffer/buffer_out_manager/given_buffer_out_manager.h" -#include "stream/fmt/buffer/buffer_out_manager/static_buffer_out_manager.h" +#include "stream/fmt/buf/streamio_manager/given_streamio_manager.h" +#include "stream/fmt/buf/streamio_manager/static_streamio_manager.h" -#include "ParserTextPropertiesExecutor/ParserANSITextPropertiesExecutor.h" +#include "parser_text_properties_executor/parser_text_properties_executor_ansi.h" namespace stream::fmt { template - [[nodiscard]] std::expected parse(Buffer&& bufferInput, Format&& formatInput, Args&&... args) + [[nodiscard]] std::expected parse(Buffer&& buffer_input, Format&& format_input, Args&&... args) { - detail::BufferInfoView buffer{bufferInput}; - detail::BufferInfoView format{formatInput}; + buf::StreamView buffer{buffer_input}; + buf::StreamView format{format_input}; using TChar = typename decltype(format)::TChar; - detail::ParserNOTextPropertiesExecutor> textPropertiesExecutor; - Context::BasicParserExecutor> executor(buffer, textPropertiesExecutor); - SF_TRY(executor.Run(format, std::forward(args)...)); - return executor.Terminate(); + detail::ParserNOTextPropertiesExecutor> text_properties_executor; + context::BasicParserExecutor> executor(buffer, text_properties_executor); + SF_TRY(executor.run(format, std::forward(args)...)); + return executor.terminate(); } } diff --git a/src/stream/fmt/context/utils/context_functions.h b/src/stream/fmt/context/utils/context_functions.h index d5404e7d..d4c67196 100644 --- a/src/stream/fmt/context/utils/context_functions.h +++ b/src/stream/fmt/context/utils/context_functions.h @@ -5,18 +5,18 @@ namespace stream::fmt::detail { template - struct FunctionApplyNextOverride + struct FunctionapplyNextOverride { - inline explicit FunctionApplyNextOverride(FormatterExecutor& executor) - : Executor(executor) - , FormatData(executor.Data) + inline explicit FunctionapplyNextOverride(FormatterExecutor& executor) + : executor(executor) + , formatdata(executor.data) { - Executor.FormatDataApplyNextOverride(); + executor.formatdata_apply_next_override(); } - inline ~FunctionApplyNextOverride() { Executor.Data = FormatData; } + inline ~FunctionapplyNextOverride() { executor.data = formatdata; } - FormatterExecutor& Executor; - detail::FormatData FormatData; + FormatterExecutor& executor; + detail::FormatData formatdata; }; } diff --git a/src/stream/fmt/detail/convert_traits.h b/src/stream/fmt/detail/convert_traits.h index 85efc0d6..d26957d5 100644 --- a/src/stream/fmt/detail/convert_traits.h +++ b/src/stream/fmt/detail/convert_traits.h @@ -7,55 +7,55 @@ namespace stream::fmt::detail template struct FormatTypeForwardAs { - using Type = T; + using type = T; }; template struct FMTContextConvert { - static constexpr bool IsConvertible = false; + static constexpr bool is_convertible = false; }; template requires(std::is_convertible_v&& std::is_convertible_v) struct FMTContextConvert { - static constexpr bool IsConvertible = true; - static constexpr To Convert(const From& from) { return static_cast(from); } + static constexpr bool is_convertible = true; + static constexpr To convert(const From& from) { return static_cast(from); } }; template requires(std::is_convertible_v&& std::is_convertible_v) struct FMTContextConvert { - static constexpr bool IsConvertible = true; - static constexpr std::int32_t Convert(const From& from) { return std::int32_t(static_cast(from)); } + static constexpr bool is_convertible = true; + static constexpr std::int32_t convert(const From& from) { return std::int32_t(static_cast(from)); } }; template concept FMTCanContextConvert = requires(const From& from) { - requires FMTContextConvert::IsConvertible; + requires FMTContextConvert::is_convertible; { - FMTContextConvert::Convert(from) + FMTContextConvert::convert(from) } -> std::same_as; }; template struct FMTContextSame { - static constexpr bool SameAs = false; + static constexpr bool same_as = false; }; template - requires(std::is_same_v, detail::GetBaseType>) struct FMTContextSame + requires(std::is_same_v, detail::get_base_type>) struct FMTContextSame { - static constexpr bool SameAs = true; + static constexpr bool same_as = true; }; template - concept FMTIsContextSame = requires(To* to, const From& from) + concept fmt_is_context_same = requires(To* to, const From& from) { - requires FMTContextSame::SameAs; + requires FMTContextSame::same_as; *to = from; }; } diff --git a/src/stream/fmt/detail/fmt_result.h b/src/stream/fmt/detail/fmt_result.h index 80c4e916..3d85e54d 100644 --- a/src/stream/fmt/detail/fmt_result.h +++ b/src/stream/fmt/detail/fmt_result.h @@ -20,14 +20,14 @@ namespace stream::fmt ArgsInterface_CantMatchNamedArgs, ArgsInterface_IndexOutOfBounds, - Specifers_Full, - Specifers_Invalid, - Specifers_DoesNotExist, + Specifiers_Full, + Specifiers_Invalid, + Specifiers_DoesNotExist, Context_ParsingFormat, Context_ArgumentIndexResolution, Context_ArgumentIndexExpected, - Context_CannotApplyType, + Context_CannotapplyType, GivenArgs_UnableToDeduceSize, diff --git a/src/stream/fmt/detail/indent_handlers.h b/src/stream/fmt/detail/indent_handlers.h index cb1e5171..9c5d4bce 100644 --- a/src/stream/fmt/detail/indent_handlers.h +++ b/src/stream/fmt/detail/indent_handlers.h @@ -1,21 +1,21 @@ #pragma once #include "stream/fmt/detail/prelude.h" -#include "stream/fmt/buffer/fmt_buffer_out_manip.h" +#include "stream/fmt/buf/fmt_manip_io.h" namespace stream::fmt::detail { template struct NoStrideFunction { - inline explicit NoStrideFunction(FMTBufferOutInfo& buffer) - : Buffer(buffer) - , SizeBuffer(BufferAccess(buffer).GetBufferCurrentSize()) + inline explicit NoStrideFunction(buf::FMTStreamIO& buffer_) + : buffer(buffer_) + , size_buffer(buf::Access(buffer_).get_buffer_current_size()) {} - ~NoStrideFunction() { FMTBufferOutManip(buffer).AddNoStride(BufferAccess(buffer).GetBufferCurrentSize() - SizeBuffer); } + ~NoStrideFunction() { buf::FMTManipIO(buffer).add_no_stride(buf::Access(buffer).get_buffer_current_size() - size_buffer); } - FMTBufferOutInfo& Buffer; - std::size_t SizeBuffer; + buf::FMTStreamIO& buffer; + std::size_t size_buffer; }; } diff --git a/src/stream/fmt/detail/prelude.h b/src/stream/fmt/detail/prelude.h index cae33a7a..1d24aa01 100644 --- a/src/stream/fmt/detail/prelude.h +++ b/src/stream/fmt/detail/prelude.h @@ -12,7 +12,7 @@ // // Macro PackSave ; PackSave (foreshadowing for constexpr) // -// TOKENIZER bufferIn +// TOKENIZER istream // // GLOBBER // diff --git a/src/stream/fmt/detail/specifiers.h b/src/stream/fmt/detail/specifiers.h index 216e6bb0..572b4f5c 100644 --- a/src/stream/fmt/detail/specifiers.h +++ b/src/stream/fmt/detail/specifiers.h @@ -37,32 +37,32 @@ namespace stream::fmt::detail { public: constexpr ShiftPrint() - : Before(' ') - , After(' ') + : before(' ') + , after(' ') {} constexpr ShiftPrint(char c) - : Before(c) - , After(c) + : before(c) + , after(c) {} constexpr ShiftPrint(char before, char after) - : Before(before) - , After(after) + : before(before) + , after(after) {} public: - char Before; - char After; + char before; + char after; public: - constexpr bool BeforeIsADigit() const { return Before >= '0' && Before <= '9'; } + constexpr bool before_is_a_digit() const { return before >= '0' && before <= '9'; } }; public: - ShiftType Type = ShiftType::Default; // < - > - ^ - ShiftPrint Print = ShiftPrint{}; // 0 - ' ' - * ..... - std::int32_t Size = -1; // ? - ^? + ShiftType type = ShiftType::Default; // < - > - ^ + ShiftPrint print = ShiftPrint{}; // 0 - ' ' - * ..... + std::int32_t size = -1; // ? - ^? }; } @@ -72,133 +72,133 @@ namespace stream::fmt::detail struct FormatSpecifier { FormatSpecifier() - : Name(nullptr, 0) - , AsText(nullptr, 0) - , AsNumber(0) - , HasText(false) - , HasNumber(false) + : name(nullptr, 0) + , as_text(nullptr, 0) + , as_number(0) + , has_text(false) + , has_number(false) {} FormatSpecifier(std::basic_string_view name) - : Name(name) - , AsText(nullptr, 0) - , AsNumber(0) - , HasText(false) - , HasNumber(false) + : name(name) + , as_text(nullptr, 0) + , as_number(0) + , has_text(false) + , has_number(false) {} FormatSpecifier(std::basic_string_view name, std::basic_string_view value) - : Name(name) - , AsText(value) - , AsNumber(0) - , HasText(true) - , HasNumber(false) + : name(name) + , as_text(value) + , as_number(0) + , has_text(true) + , has_number(false) {} FormatSpecifier(std::basic_string_view name, const std::int32_t value) - : Name(name) - , AsText(nullptr, 0) - , AsNumber(value) - , HasText(false) - , HasNumber(true) + : name(name) + , as_text(nullptr, 0) + , as_number(value) + , has_text(false) + , has_number(true) {} - FormatSpecifier(std::basic_string_view name, const std::int32_t valueAsNumber, std::basic_string_view valueAsText) - : Name(name) - , AsText(valueAsText) - , AsNumber(valueAsNumber) - , HasText(true) - , HasNumber(true) + FormatSpecifier(std::basic_string_view name, const std::int32_t value_as_number, std::basic_string_view value_as_text) + : name(name) + , as_text(value_as_text) + , as_number(value_as_number) + , has_text(true) + , has_number(true) {} - std::basic_string_view Name = ""; - std::basic_string_view AsText = ""; - std::int32_t AsNumber = 0; - bool HasText = false; - bool HasNumber = false; + std::basic_string_view name = ""; + std::basic_string_view as_text = ""; + std::int32_t as_number = 0; + bool has_text = false; + bool has_number = false; }; template struct FormatSpecifierList { public: - std::uint8_t SpecifierCount = 0; - std::array, SIZE> Specifier{}; + std::uint8_t specifier_count = 0; + std::array, SIZE> specifiers{}; struct Constraint { - bool HasText = false; - bool HasNumber = false; + bool has_text = false; + bool has_number = false; }; public: static inline constexpr std::uint8_t NotFound() { return (std::numeric_limits::max)(); } - FormatSpecifier* Get(std::basic_string_view name, const Constraint& constraint = Constraint{}) + FormatSpecifier* get(std::basic_string_view name, const Constraint& constraint = Constraint{}) { - STREAMFORMAT_ASSERT(SpecifierCount <= SIZE); - for (std::uint8_t i = 0; i < SpecifierCount; ++i) - if (Specifier[i].Name == name) + STREAMFORMAT_ASSERT(specifier_count <= SIZE); + for (std::uint8_t i = 0; i < specifier_count; ++i) + if (specifiers[i].name == name) { - bool textContraintsatisfied = !constraint.HasText || Specifier[i].HasText; - bool numberContraintsatisfied = !constraint.HasNumber || Specifier[i].HasNumber; - if (textContraintsatisfied && numberContraintsatisfied) - return &Specifier[i]; + bool text_contraint_satisfied = !constraint.has_text || specifiers[i].has_text; + bool number_contraint_satisfied = !constraint.has_number || specifiers[i].has_number; + if (text_contraint_satisfied && number_contraint_satisfied) + return &specifiers[i]; } return nullptr; } - const FormatSpecifier* Get(std::basic_string_view name, const Constraint& constraint = Constraint{}) const + const FormatSpecifier* get(std::basic_string_view name, const Constraint& constraint = Constraint{}) const { - STREAMFORMAT_ASSERT(SpecifierCount <= SIZE); - for (std::uint8_t i = 0; i < SpecifierCount; ++i) - if (Specifier[i].Name == name) + STREAMFORMAT_ASSERT(specifier_count <= SIZE); + for (std::uint8_t i = 0; i < specifier_count; ++i) + if (specifiers[i].name == name) { - bool textContraintsatisfied = !constraint.HasText || Specifier[i].HasText; - bool numberContraintsatisfied = !constraint.HasNumber || Specifier[i].HasNumber; - if (textContraintsatisfied && numberContraintsatisfied) - return &Specifier[i]; + bool text_contraint_satisfied = !constraint.has_text || specifiers[i].has_text; + bool number_contraint_satisfied = !constraint.has_number || specifiers[i].has_number; + if (text_contraint_satisfied && number_contraint_satisfied) + return &specifiers[i]; } return nullptr; } - bool Has(std::basic_string_view name) const { return Get(name) != nullptr; } + bool has(std::basic_string_view name) const { return get(name) != nullptr; } - std::int32_t GetAsNumber(std::basic_string_view name, std::int32_t defaultValue) const + std::int32_t get_as_number(std::basic_string_view name, std::int32_t default_value) const { - const FormatSpecifier* get = Get(name, Constraint{.HasNumber = true}); - if (get == nullptr || !get->HasNumber) - return defaultValue; - return get->AsNumber; + const FormatSpecifier* getptr = get(name, Constraint{.has_number = true}); + if (getptr == nullptr || !getptr->has_number) + return default_value; + return getptr->as_number; } - std::basic_string_view GetAsText(std::basic_string_view name, std::basic_string_view defaultValue) const + std::basic_string_view get_as_text(std::basic_string_view name, std::basic_string_view default_value) const { - const FormatSpecifier* get = Get(name, Constraint{.HasText = true}); - if (get == nullptr || !get->HasText) - return defaultValue; - return get->AsText; + const FormatSpecifier* getptr = get(name, Constraint{.has_text = true}); + if (getptr == nullptr || !getptr->has_text) + return default_value; + return getptr->as_text; } public: - [[nodiscard]] std::expected Pushback(const FormatSpecifier& specifier) + [[nodiscard]] std::expected pushback(const FormatSpecifier& specifier) { - if (SpecifierCount >= SIZE) - return std::unexpected(FMTResult::Specifers_Full); - Specifier[SpecifierCount++] = specifier; + if (specifier_count >= SIZE) + return std::unexpected(FMTResult::Specifiers_Full); + specifiers[specifier_count++] = specifier; return {}; } - [[nodiscard]] std::expected Concat(const FormatSpecifier& specifier) + [[nodiscard]] std::expected concat(const FormatSpecifier& specifier) { - FormatSpecifier* local = Get(specifier.Name); + FormatSpecifier* local = get(specifier.name); if (local == nullptr) - return Pushback(specifier); + return pushback(specifier); - if (specifier.HasText) - { local->HasText = true; local->AsText = specifier.AsText; } - if (specifier.HasNumber) - { local->HasNumber = true; local->AsNumber = specifier.AsNumber; } + if (specifier.has_text) + { local->has_text = true; local->as_text = specifier.as_text; } + if (specifier.has_number) + { local->has_number = true; local->as_number = specifier.as_number; } return {}; } }; @@ -207,41 +207,41 @@ namespace stream::fmt::detail struct FormatData { public: - bool HasSpec = false; - bool KeepNewStyle = false; // W + bool has_spec = false; + bool keep_new_style = false; // W - bool PrefixSuffix = false; // # - IntegerPrintBase IntegerPrint = IntegerPrintBase::Dec; // B - X - O - D - std::int32_t FloatPrecision = -1; // . - ShiftInfo Shift; + bool prefix_suffix = false; // # + IntegerPrintBase integer_print = IntegerPrintBase::Dec; // b - X - O - D + std::int32_t float_precision = -1; // . + ShiftInfo shift; - FormatSpecifierList Specifiers; + FormatSpecifierList specifiers; - std::basic_string_view NextOverride = std::basic_string_view(nullptr, 0); + std::basic_string_view next_override = std::basic_string_view(nullptr, 0); public: - void Apply(const FormatData& given) { *this = given; } + void apply(const FormatData& given) { *this = given; } - void Apply(const IntegerPrintBase& given) { IntegerPrint = given; } - void Apply(const ShiftInfo& given) { Shift = given; } - void Apply(const FormatSpecifier& given) { Specifiers.Concat(given); } + void apply(const IntegerPrintBase& given) { integer_print = given; } + void apply(const ShiftInfo& given) { shift = given; } + void apply(const FormatSpecifier& given) { specifiers.concat(given); } template - bool TestApply(const T* given) + bool testapply(const T* given) requires requires(const T& value, FormatData& data) { - data.Apply(value); + data.apply(value); } { if (given == nullptr) return false; - Apply(*given); + apply(*given); return true; } }; template - concept FormatDataCanApply = requires(const T& value, FormatData& data) + concept format_data_can_apply = requires(const T& value, FormatData& data) { - data.Apply(value); + data.apply(value); }; } diff --git a/src/stream/fmt/detail/types_traits.h b/src/stream/fmt/detail/types_traits.h index ffcba64e..f28808df 100644 --- a/src/stream/fmt/detail/types_traits.h +++ b/src/stream/fmt/detail/types_traits.h @@ -7,13 +7,13 @@ namespace stream::fmt::detail { template - using GetBaseType = std::remove_cv_t>; + using get_base_type = std::remove_cv_t>; template struct IsCharType { - using BaseType = GetBaseType; - static constexpr bool Value = std::is_same_v || std::is_same_v || std::is_same_v || + using BaseType = get_base_type; + static constexpr bool value = std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v; }; } diff --git a/src/stream/fmt/serializers/compilation_data.h b/src/stream/fmt/serializers/compilation_data.h index d3a6bd83..502980f3 100644 --- a/src/stream/fmt/serializers/compilation_data.h +++ b/src/stream/fmt/serializers/compilation_data.h @@ -7,36 +7,36 @@ namespace stream::fmt::detail { struct FileLocation { - FileLocation(std::string_view fileName, int fileLine = 0) - : FileName(fileName) - , FileLine(fileLine) + FileLocation(std::string_view file_name_, int file_line_ = 0) + : file_name(file_name_) + , file_line(file_line_) {} - std::string_view FileName; // __FILE__ - int FileLine; // __LINE__ + std::string_view file_name; // __FILE__ + int file_line; // __LINE__ }; struct FunctionProperties { - FunctionProperties(std::string_view fileName, int fileLine = 0, std::string_view functionName = "", std::string_view functionSignature = "", - std::string_view functionAssemblyName = "") - : Location(fileName, fileLine) - , FunctionName(functionName) - , FunctionSignature(functionSignature) - , FunctionAssemblyName(functionAssemblyName) + FunctionProperties(std::string_view file_name_, int file_line_ = 0, std::string_view functionName = "", std::string_view function_signature_ = "", + std::string_view function_assembly_name_ = "") + : location(file_name_, file_line_) + , function_name(functionName) + , function_signature(function_signature_) + , function_assembly_name(function_assembly_name_) {} - FunctionProperties(FileLocation location, std::string_view functionName = "", std::string_view functionSignature = "", std::string_view functionAssemblyName = "") - : Location(location) - , FunctionName(functionName) - , FunctionSignature(functionSignature) - , FunctionAssemblyName(functionAssemblyName) + FunctionProperties(FileLocation location, std::string_view functionName = "", std::string_view function_signature_ = "", std::string_view function_assembly_name_ = "") + : location(location) + , function_name(functionName) + , function_signature(function_signature_) + , function_assembly_name(function_assembly_name_) {} - FileLocation Location; - std::string_view FunctionName; // __FUNCTION__ - std::string_view FunctionSignature; // __FUNCSIG__ -- __PRETTY_FUNCTION__ - std::string_view FunctionAssemblyName; // __FUNCDNAME__ + FileLocation location; + std::string_view function_name; // __FUNCTION__ + std::string_view function_signature; // __FUNCSIG__ -- __PRETTY_FUNCTION__ + std::string_view function_assembly_name; // __FUNCDNAME__ }; } @@ -50,9 +50,9 @@ namespace stream::fmt { [[nodiscard]] static inline std::expected format(const detail::FileLocation& t, FormatterExecutor& executor) { - SF_TRY(executor.WriteType(t.FileName)); - SF_TRY(executor.buffer_out.Pushback(':')); - return executor.WriteType(t.FileLine); + SF_TRY(executor.write_type(t.file_name)); + SF_TRY(executor.ostream.pushback(':')); + return executor.write_type(t.file_line); } }; @@ -61,9 +61,9 @@ namespace stream::fmt { [[nodiscard]] static inline std::expected format(const detail::FunctionProperties& t, FormatterExecutor& executor) { - SF_TRY(executor.WriteType(t.Location)); - SF_TRY(executor.buffer_out.WriteCharArray(" @ ")); - return executor.WriteType(t.FunctionName); + SF_TRY(executor.write_type(t.location)); + SF_TRY(executor.ostream.write_char_array(" @ ")); + return executor.write_type(t.function_name); } }; } diff --git a/src/stream/fmt/serializers/format_chrono.h b/src/stream/fmt/serializers/format_chrono.h index da39e39e..85187d48 100644 --- a/src/stream/fmt/serializers/format_chrono.h +++ b/src/stream/fmt/serializers/format_chrono.h @@ -1,9 +1,9 @@ #pragma once -#include "stream/fmt/buffer/buffer_test_manip.h" -#include "stream/fmt/buffer/buffer_write_manip.h" -#include "stream/fmt/buffer/buffer_read_manip.h" -#include "stream/fmt/buffer/FMTBufferWriteManip.h" +#include "stream/fmt/buf/test_manip.h" +#include "stream/fmt/buf/write_manip.h" +#include "stream/fmt/buf/read_manip.h" +#include "stream/fmt/buf/fmt_write_manip.h" #include "stream/fmt/context/formatter_executor/basic_formatter_executor.h" @@ -19,100 +19,100 @@ namespace stream::fmt::detail }; template - [[nodiscard]] std::expected WriteSubTime_(const std::chrono::time_point& value, BufferInfoView& pattern, FMTBufferOutInfo& buffer, TimePrintMode mode) + [[nodiscard]] std::expected write_sub_time_(const std::chrono::time_point& value, buf::StreamView& pattern, buf::FMTStreamIO& buffer, TimePrintMode mode) { ShiftInfo shift; - shift.Type = detail::ShiftInfo::ShiftType::Right; - shift.Print = detail::ShiftInfo::ShiftPrint('0', ' '); - shift.Size = 0; - (void)BufferReadManip(pattern).FastReadInteger(shift.Size); + shift.type = detail::ShiftInfo::ShiftType::Right; + shift.print = detail::ShiftInfo::ShiftPrint('0', ' '); + shift.size = 0; + (void)buf::ReadManip(pattern).fast_read_integer(shift.size); - if (mode == TimePrintMode::Mod && shift.Size < 0) - shift.Size = 3; + if (mode == TimePrintMode::Mod && shift.size < 0) + shift.size = 3; - if (BufferTestAccess(pattern).IsSame("ns", 2)) + if (buf::TestAccess(pattern).is_same("ns", 2)) { - SF_TRY(BufferManip(pattern).Forward()); + SF_TRY(buf::Manip(pattern).forward()); std::uint32_t ns = static_cast(std::chrono::time_point_cast(value).time_since_epoch().count()); if (mode == TimePrintMode::Mod) ns = ns % 1000; - SF_TRY(FMTBufferWriteManip(buffer).WriteInteger(static_cast(ns) % 1000, shift)); + SF_TRY(buf::FMTWriteManip(buffer).write_integer(static_cast(ns) % 1000, shift)); } - else if (BufferTestAccess(pattern).IsSame("us", 2)) + else if (buf::TestAccess(pattern).is_same("us", 2)) { - SF_TRY(BufferManip(pattern).Forward()); + SF_TRY(buf::Manip(pattern).forward()); std::uint32_t us = static_cast(std::chrono::time_point_cast(value).time_since_epoch().count()); if (mode == TimePrintMode::Mod) us = us % 1000; else if (mode == TimePrintMode::Sub) us = us / 1000; - SF_TRY(FMTBufferWriteManip(buffer).WriteInteger(static_cast(us) % 1000, shift)); + SF_TRY(buf::FMTWriteManip(buffer).write_integer(static_cast(us) % 1000, shift)); } - else if (BufferTestAccess(pattern).IsSame("ms", 2)) + else if (buf::TestAccess(pattern).is_same("ms", 2)) { - SF_TRY(BufferManip(pattern).Forward()); + SF_TRY(buf::Manip(pattern).forward()); std::uint32_t ms = static_cast(std::chrono::time_point_cast(value).time_since_epoch().count()); if (mode == TimePrintMode::Mod) ms = ms % 1000; else if (mode == TimePrintMode::Sub) ms = ms / 1000000; - SF_TRY(FMTBufferWriteManip(buffer).WriteInteger(static_cast(ms) % 1000, shift)); + SF_TRY(buf::FMTWriteManip(buffer).write_integer(static_cast(ms) % 1000, shift)); } - else if (BufferTestAccess(pattern).IsEqualTo('s')) + else if (buf::TestAccess(pattern).is_equal_to('s')) { - SF_TRY(BufferManip(pattern).Forward()); + SF_TRY(buf::Manip(pattern).forward()); std::uint32_t sec = static_cast(std::chrono::time_point_cast(value).time_since_epoch().count()); if (mode == TimePrintMode::Mod) sec = sec % 60; else if (mode == TimePrintMode::Sub) sec = sec / 1000000000; - SF_TRY(FMTBufferWriteManip(buffer).WriteInteger(static_cast(sec) % 1000, shift)); + SF_TRY(buf::FMTWriteManip(buffer).write_integer(static_cast(sec) % 1000, shift)); } - else if (BufferTestAccess(pattern).IsEqualTo('m')) + else if (buf::TestAccess(pattern).is_equal_to('m')) { - SF_TRY(BufferManip(pattern).Forward()); + SF_TRY(buf::Manip(pattern).forward()); std::uint32_t min = static_cast(std::chrono::time_point_cast(value).time_since_epoch().count()); if (mode == TimePrintMode::Mod) min = min % 60; - SF_TRY(FMTBufferWriteManip(buffer).WriteInteger(static_cast(min) % 1000, shift)); + SF_TRY(buf::FMTWriteManip(buffer).write_integer(static_cast(min) % 1000, shift)); } - else if (BufferTestAccess(pattern).IsEqualTo('h')) + else if (buf::TestAccess(pattern).is_equal_to('h')) { - SF_TRY(BufferManip(pattern).Forward()); + SF_TRY(buf::Manip(pattern).forward()); std::uint32_t min = static_cast(std::chrono::time_point_cast(value).time_since_epoch().count()); if (mode == TimePrintMode::Mod) min = min % 24; - SF_TRY(FMTBufferWriteManip(buffer).WriteInteger(static_cast(min) % 1000, shift)); + SF_TRY(buf::FMTWriteManip(buffer).write_integer(static_cast(min) % 1000, shift)); } return {}; } template - [[nodiscard]] std::expected WriteTime(const std::chrono::time_point& value, BufferInfoView pattern, FMTBufferOutInfo& buffer) + [[nodiscard]] std::expected WriteTime(const std::chrono::time_point& value, buf::StreamView pattern, buf::FMTStreamIO& buffer) { - auto view = SF_TRY(BufferTestManip(pattern).ViewExec( - [&] -> std::expected { FMTBufferParamsManip(pattern).ParamGoTo('%', '#', '/'); return {}; } + auto view = SF_TRY(buf::TestManip(pattern).ViewExec( + [&] -> std::expected { buf::FMTParamsManip(pattern).param_go_to('%', '#', '/'); return {}; } )); - SF_TRY(BufferWriteManip(buffer).FastWriteString(view)); + SF_TRY(buf::WriteManip(buffer).fast_write_string(view)); - while (!BufferAccess(pattern).IsEndOfString()) + while (!buf::Access(pattern).is_end_of_string()) { TimePrintMode mode; - if (BufferTestAccess(pattern).IsEqualTo('%')) + if (buf::TestAccess(pattern).is_equal_to('%')) mode = TimePrintMode::Mod; - else if (BufferTestAccess(pattern).IsEqualTo('#')) + else if (buf::TestAccess(pattern).is_equal_to('#')) mode = TimePrintMode::FullTime; - else if (BufferTestAccess(pattern).IsEqualTo('/')) + else if (buf::TestAccess(pattern).is_equal_to('/')) mode = TimePrintMode::Sub; - SF_TRY(BufferManip(pattern).Forward()); - SF_TRY(WriteSubTime_(value, pattern, buffer, mode)); + SF_TRY(buf::Manip(pattern).forward()); + SF_TRY(write_sub_time_(value, pattern, buffer, mode)); - auto view = SF_TRY(BufferTestManip(pattern).ViewExec( - [&] -> std::expected { FMTBufferParamsManip(pattern).ParamGoTo('%', '#', '/'); return {}; } + auto view = SF_TRY(buf::TestManip(pattern).ViewExec( + [&] -> std::expected { buf::FMTParamsManip(pattern).param_go_to('%', '#', '/'); return {}; } )); - SF_TRY(BufferWriteManip(buffer).FastWriteString(view)); + SF_TRY(buf::WriteManip(buffer).fast_write_string(view)); } return {}; @@ -126,7 +126,7 @@ namespace stream::fmt { [[nodiscard]] static inline std::expected format(const std::chrono::time_point& t, FormatterExecutor& executor) { - return detail::WriteTime(t, detail::BufferInfoView(executor.Data.Specifiers.GetAsText("pattern", "%h:%m:%s.%ms")), executor.buffer_out); + return detail::WriteTime(t, buf::StreamView(executor.data.specifiers.get_as_text("pattern", "%h:%m:%s.%ms")), executor.ostream); } }; @@ -135,28 +135,28 @@ namespace stream::fmt { [[nodiscard]] static inline std::expected format(const std::chrono::duration& t, FormatterExecutor& executor) { - if (executor.Data.Specifiers.Has("pattern")) + if (executor.data.specifiers.has("pattern")) { return detail::WriteTime( std::chrono::time_point>(t), - detail::BufferInfoView(executor.Data.Specifiers.GetAsText("pattern", "%h:%m:%s.%ms")), - executor.buffer_out + buf::StreamView(executor.data.specifiers.get_as_text("pattern", "%h:%m:%s.%ms")), + executor.ostream ); } - SF_TRY(detail::BufferWriteManip(executor.buffer_out).FastWriteInteger(t.count())); + SF_TRY(buf::WriteManip(executor.ostream).fast_write_integer(t.count())); if constexpr (std::is_same_v, std::chrono::seconds>) - { SF_TRY(detail::BufferOutManip(executor.buffer_out).Pushback('s')); } + { SF_TRY(buf::ManipIO(executor.ostream).pushback('s')); } else if constexpr (std::is_same_v, std::chrono::minutes>) - { SF_TRY(detail::BufferOutManip(executor.buffer_out).Pushback('m')); } + { SF_TRY(buf::ManipIO(executor.ostream).pushback('m')); } else if constexpr (std::is_same_v, std::chrono::hours>) - { SF_TRY(detail::BufferOutManip(executor.buffer_out).Pushback('h')); } + { SF_TRY(buf::ManipIO(executor.ostream).pushback('h')); } else if constexpr (std::is_same_v, std::chrono::milliseconds>) - { SF_TRY(detail::BufferOutManip(executor.buffer_out).Pushback('m', 's')); } + { SF_TRY(buf::ManipIO(executor.ostream).pushback('m', 's')); } else if constexpr (std::is_same_v, std::chrono::microseconds>) - { SF_TRY(detail::BufferOutManip(executor.buffer_out).Pushback('u', 's')); } + { SF_TRY(buf::ManipIO(executor.ostream).pushback('u', 's')); } else if constexpr (std::is_same_v, std::chrono::nanoseconds>) - { SF_TRY(detail::BufferOutManip(executor.buffer_out).Pushback('n', 's')); } + { SF_TRY(buf::ManipIO(executor.ostream).pushback('n', 's')); } return {}; } diff --git a/src/stream/fmt/serializers/format_stdlib.h b/src/stream/fmt/serializers/format_stdlib.h index 4ba622f0..bbe3ba37 100644 --- a/src/stream/fmt/serializers/format_stdlib.h +++ b/src/stream/fmt/serializers/format_stdlib.h @@ -17,21 +17,21 @@ namespace stream::fmt struct FormatterType, FormatterExecutor> { [[nodiscard]] static inline std::expected format(const std::basic_string& t, FormatterExecutor& executor) - { return detail::BufferWriteManip(executor.buffer_out).FastWriteString(t); } + { return buf::WriteManip(executor.ostream).fast_write_string(t); } }; template struct FormatterType, FormatterExecutor> { [[nodiscard]] static inline std::expected format(std::basic_string_view t, FormatterExecutor& executor) - { return detail::BufferWriteManip(executor.buffer_out).FastWriteString(t); } + { return buf::WriteManip(executor.ostream).fast_write_string(t); } }; template struct FormatterType, FormatterExecutor> { [[nodiscard]] static inline std::expected format(const std::basic_stringstream& t, FormatterExecutor& executor) - { return detail::BufferWriteManip(executor.buffer_out).FastWriteCharArray(t.str(), t.size()); } + { return buf::WriteManip(executor.ostream).fast_write_char_array(t.str(), t.size()); } }; //------------------------------------------// @@ -44,7 +44,7 @@ namespace stream::fmt { [[nodiscard]] static inline std::expected format(const std::unique_ptr& t, FormatterExecutor& executor) { - if (executor.Data.TrueValue) + if (executor.data.TrueValue) return FormatterType::format(t.get(), executor); else return FormatterType::format(*t, executor); @@ -59,7 +59,7 @@ namespace stream::fmt { [[nodiscard]] static inline std::expected format(const std::shared_ptr& t, FormatterExecutor& executor) { - if (executor.Data.TrueValue) + if (executor.data.TrueValue) return FormatterType::format(t.get(), executor); else return FormatterType::format(*t, executor); diff --git a/src/stream/fmt/serializers/parse_chrono.h b/src/stream/fmt/serializers/parse_chrono.h index 964e2d3f..de36cfab 100644 --- a/src/stream/fmt/serializers/parse_chrono.h +++ b/src/stream/fmt/serializers/parse_chrono.h @@ -1,7 +1,7 @@ #pragma once #include -#include "stream/fmt/context/ParserExecutor/BasicParserExecutor.h" +#include "stream/fmt/context/parser_executor/basic_parser_executor.h" namespace stream::fmt::detail { diff --git a/src/stream/fmt/serializers/parse_stdlib.h b/src/stream/fmt/serializers/parse_stdlib.h index 55907913..f32691af 100644 --- a/src/stream/fmt/serializers/parse_stdlib.h +++ b/src/stream/fmt/serializers/parse_stdlib.h @@ -1,6 +1,6 @@ #pragma once -#include "stream/fmt/context/ParserExecutor/BasicParserExecutor.h" +#include "stream/fmt/context/parser_executor/basic_parser_executor.h" #include #include diff --git a/src/stream/fmt/serializers/std_container/FMT_tuple.h b/src/stream/fmt/serializers/std_container/FMT_tuple.h index 7c706a25..68c70eda 100644 --- a/src/stream/fmt/serializers/std_container/FMT_tuple.h +++ b/src/stream/fmt/serializers/std_container/FMT_tuple.h @@ -7,10 +7,10 @@ namespace stream::fmt::TupleDetail { template - using NthTypeOf = typename std::tuple_element>::type; + using NthTypeOf = typename std::tuple_element>::Type; template - constexpr NthTypeOf& Get(Args&&... args) + constexpr NthTypeOf& get(Args&&... args) { std::tuple tuple(args...); return std::get(tuple); @@ -25,15 +25,15 @@ namespace stream::fmt::TupleDetail template [[nodiscard]] static inline std::expected TupleFormatRec(FormatterExecutor& executor, const T& t) { - return executor.WriteType(t); + return executor.write_type(t); } template [[nodiscard]] static inline std::expected TupleFormatRec(FormatterExecutor& executor, const T& t, Args&&... args) { - SF_TRY(executor.WriteType(t)); - SF_TRY(executor.buffer_out.Pushback(',')); - SF_TRY(executor.buffer_out.Pushback(' ')); + SF_TRY(executor.write_type(t)); + SF_TRY(executor.ostream.pushback(',')); + SF_TRY(executor.ostream.pushback(' ')); return TupleFormatRec(context, args...); } } @@ -45,7 +45,7 @@ namespace stream::fmt { [[nodiscard]] static inline std::expected format(const std::tuple& t, FormatterExecutor& executor) { - SF_TRY(executor.buffer_out.Pushback('<')); + SF_TRY(executor.ostream.pushback('<')); std::expected err = {}; std::apply([&context, &err](auto&&... args) { @@ -53,7 +53,7 @@ namespace stream::fmt if (not res) { err = res.error(); } }, t); - SF_TRY(executor.buffer_out.Pushback('>')); + SF_TRY(executor.ostream.pushback('>')); } }; @@ -62,11 +62,11 @@ namespace stream::fmt { [[nodiscard]] static inline std::expected format(const std::pair& t, FormatterExecutor& executor) { - SF_TRY(executor.buffer_out.Pushback('<')); - SF_TRY(executor.WriteType(t.first)); - SF_TRY(executor.buffer_out.Pushback(':')); - SF_TRY(executor.WriteType(t.second)); - SF_TRY(executor.buffer_out.Pushback('>')); + SF_TRY(executor.ostream.pushback('<')); + SF_TRY(executor.write_type(t.first)); + SF_TRY(executor.ostream.pushback(':')); + SF_TRY(executor.write_type(t.second)); + SF_TRY(executor.ostream.pushback('>')); return {}; } diff --git a/src/stream/fmt/text_properties/text_properties_color.h b/src/stream/fmt/text_properties/text_properties_color.h index e8163f7c..b4186c72 100644 --- a/src/stream/fmt/text_properties/text_properties_color.h +++ b/src/stream/fmt/text_properties/text_properties_color.h @@ -90,11 +90,11 @@ namespace stream::fmt::detail { constexpr BasicColor(TextProperties::TextColor::BasicColorFG fg = TextProperties::TextColor::BasicColorFG::Default, TextProperties::TextColor::BasicColorBG bg = TextProperties::TextColor::BasicColorBG::Default) - : Fg(fg) - , Bg(bg) + : fg(fg) + , bg(bg) {} - TextProperties::TextColor::BasicColorFG Fg; - TextProperties::TextColor::BasicColorBG Bg; + TextProperties::TextColor::BasicColorFG fg; + TextProperties::TextColor::BasicColorBG bg; }; struct TextProperties::TextColor::BaseColorCube @@ -132,7 +132,7 @@ namespace stream::fmt::detail static inline constexpr std::uint8_t Default = 0; public: - enum class Type : std::uint8_t + enum class type : std::uint8_t { Normal, Bright, @@ -141,33 +141,33 @@ namespace stream::fmt::detail }; public: - std::uint8_t Color; + std::uint8_t color; public: - std::uint8_t GetColor() const { return Color; } - std::uint8_t GetColorRef() { return Color; } - std::uint8_t GetColorRef() const { return Color; } + std::uint8_t get_color() const { return color; } + std::uint8_t get_color_ref() { return color; } + std::uint8_t get_color_ref() const { return color; } public: constexpr BaseColorCube(const std::uint8_t color) - : Color(color) + : color(color) {} constexpr BaseColorCube() - : Color(0) + : color(0) {} - Type GetType() + type GetType() { - if (Color >= MinNormalColor && Color <= MaxNormalColor) - return Type::Normal; - else if (Color >= MinBrightColor && Color <= MaxBrightColor) - return Type::Bright; - else if (Color >= Min666CubeColor && Color <= Max666CubeColor) - return Type::Cube666; - else if (Color >= MinGrayscale && Color <= MaxGrayscale) - return Type::Grayscale; - return Type::Normal; + if (color >= MinNormalColor && color <= MaxNormalColor) + return type::Normal; + else if (color >= MinBrightColor && color <= MaxBrightColor) + return type::Bright; + else if (color >= Min666CubeColor && color <= Max666CubeColor) + return type::Cube666; + else if (color >= MinGrayscale && color <= MaxGrayscale) + return type::Grayscale; + return type::Normal; } static BaseColorCube MakeNormalColor(std::uint8_t value) @@ -300,37 +300,37 @@ namespace stream::fmt::detail struct TextProperties::TextColor::ColorCube { constexpr ColorCube() - : Fg() - , Bg() + : fg() + , bg() {} constexpr ColorCube(const TextProperties::TextColor::ColorCubeFG& fg) - : Fg(fg) - , Bg() + : fg(fg) + , bg() {} constexpr ColorCube(const TextProperties::TextColor::ColorCubeFG& fg, const TextProperties::TextColor::ColorCubeBG& bg) - : Fg(fg) - , Bg(bg) + : fg(fg) + , bg(bg) {} - TextProperties::TextColor::ColorCubeFG Fg; - TextProperties::TextColor::ColorCubeBG Bg; + TextProperties::TextColor::ColorCubeFG fg; + TextProperties::TextColor::ColorCubeBG bg; }; struct TextProperties::TextColor::BaseColor24b { constexpr BaseColor24b(std::uint8_t r, std::uint8_t g, std::uint8_t b) - : R(r) - , G(g) - , B(b) + : r(r) + , g(g) + , b(b) {} - std::uint8_t R, G, B; + std::uint8_t r, g, b; }; inline bool operator==(const TextProperties::TextColor::BaseColor24b& lhs, const TextProperties::TextColor::BaseColor24b& rhs) { - return lhs.R == rhs.R && lhs.G == rhs.G && lhs.B == rhs.B; + return lhs.r == rhs.r && lhs.g == rhs.g && lhs.b == rhs.b; } // No need of virtual destructor since Color24bFG is purely a renaming of BaseColor24b @@ -351,19 +351,19 @@ namespace stream::fmt::detail struct TextProperties::TextColor::Color24b { - constexpr Color24b(const TextProperties::TextColor::Color24bFG&& fg = TextProperties::TextColor::Color24bFG(), - const TextProperties::TextColor::Color24bBG&& bg = TextProperties::TextColor::Color24bBG()) - : Fg(fg) - , Bg(bg) + constexpr Color24b(const TextProperties::TextColor::Color24bFG&& fg_ = TextProperties::TextColor::Color24bFG(), + const TextProperties::TextColor::Color24bBG&& bg_ = TextProperties::TextColor::Color24bBG()) + : fg(fg_) + , bg(bg_) {} - TextProperties::TextColor::Color24bFG Fg; - TextProperties::TextColor::Color24bBG Bg; + TextProperties::TextColor::Color24bFG fg; + TextProperties::TextColor::Color24bBG bg; }; inline bool operator==(const TextProperties::TextColor::Color24b& lhs, const TextProperties::TextColor::Color24b& rhs) { - return lhs.Fg == rhs.Fg && lhs.Bg == rhs.Bg; + return lhs.fg == rhs.fg && lhs.bg == rhs.bg; } enum class TextProperties::TextColor::ColorType : std::uint8_t @@ -376,63 +376,63 @@ namespace stream::fmt::detail union TextProperties::TextColor::ColorFGData { constexpr ColorFGData() - : BasicColor{TextProperties::TextColor::BasicColorFG::Default} + : basic_color{TextProperties::TextColor::BasicColorFG::Default} {} - TextProperties::TextColor::BasicColorFG BasicColor; - TextProperties::TextColor::ColorCubeFG ColorCube; - TextProperties::TextColor::Color24bFG Color24b; + TextProperties::TextColor::BasicColorFG basic_color; + TextProperties::TextColor::ColorCubeFG color_cube; + TextProperties::TextColor::Color24bFG color24b; }; union TextProperties::TextColor::ColorBGData { constexpr ColorBGData() - : BasicColor{TextProperties::TextColor::BasicColorBG::Default} + : basic_color{TextProperties::TextColor::BasicColorBG::Default} {} - TextProperties::TextColor::BasicColorBG BasicColor; - TextProperties::TextColor::ColorCubeBG ColorCube; - TextProperties::TextColor::Color24bBG Color24b; + TextProperties::TextColor::BasicColorBG basic_color; + TextProperties::TextColor::ColorCubeBG color_cube; + TextProperties::TextColor::Color24bBG color24b; }; struct TextProperties::TextColor::ColorFG { - TextProperties::TextColor::ColorFGData Data; - TextProperties::TextColor::ColorType Type{TextProperties::TextColor::ColorType::BasicColor}; + TextProperties::TextColor::ColorFGData data; + TextProperties::TextColor::ColorType type{TextProperties::TextColor::ColorType::BasicColor}; }; struct TextProperties::TextColor::ColorBG { - TextProperties::TextColor::ColorBGData Data; - TextProperties::TextColor::ColorType Type{TextProperties::TextColor::ColorType::BasicColor}; + TextProperties::TextColor::ColorBGData data; + TextProperties::TextColor::ColorType type{TextProperties::TextColor::ColorType::BasicColor}; }; inline bool operator==(const TextProperties::TextColor::ColorFG& lhs, const TextProperties::TextColor::ColorFG& rhs) { - if (lhs.Type != rhs.Type) return false; - switch (lhs.Type) + if (lhs.type != rhs.type) return false; + switch (lhs.type) { case TextProperties::TextColor::ColorType::BasicColor: - return lhs.Data.BasicColor == rhs.Data.BasicColor; + return lhs.data.basic_color == rhs.data.basic_color; case TextProperties::TextColor::ColorType::ColorCube: - return lhs.Data.ColorCube == rhs.Data.ColorCube; + return lhs.data.color_cube == rhs.data.color_cube; case TextProperties::TextColor::ColorType::Color24b: - return lhs.Data.Color24b == rhs.Data.Color24b; + return lhs.data.color24b == rhs.data.color24b; } return false; } inline bool operator==(const TextProperties::TextColor::ColorBG& lhs, const TextProperties::TextColor::ColorBG& rhs) { - if (lhs.Type != rhs.Type) return false; - switch (lhs.Type) + if (lhs.type != rhs.type) return false; + switch (lhs.type) { case TextProperties::TextColor::ColorType::BasicColor: - return lhs.Data.BasicColor == rhs.Data.BasicColor; + return lhs.data.basic_color == rhs.data.basic_color; case TextProperties::TextColor::ColorType::ColorCube: - return lhs.Data.ColorCube == rhs.Data.ColorCube; + return lhs.data.color_cube == rhs.data.color_cube; case TextProperties::TextColor::ColorType::Color24b: - return lhs.Data.Color24b == rhs.Data.Color24b; + return lhs.data.color24b == rhs.data.color24b; } return false; } @@ -444,102 +444,102 @@ namespace stream::fmt::detail { public: constexpr Color() - : Fg() - , Bg() + : fg() + , bg() {} public: - TextProperties::TextColor::ColorFG Fg; - TextProperties::TextColor::ColorBG Bg; + TextProperties::TextColor::ColorFG fg; + TextProperties::TextColor::ColorBG bg; public: - void ModifyReset() + void modify_reset() { - Fg = TextProperties::TextColor::ColorFG{}; - Bg = TextProperties::TextColor::ColorBG{}; + fg = TextProperties::TextColor::ColorFG{}; + bg = TextProperties::TextColor::ColorBG{}; } - void Apply(const TextProperties::TextColor::Color& given) { *this = given; } + void apply(const TextProperties::TextColor::Color& given) { *this = given; } - void Apply(const TextProperties::TextColor::reset_color&) { ModifyReset(); } - void Apply(const TextProperties::TextColor::BasicColorFG& given) + void apply(const TextProperties::TextColor::reset_color&) { modify_reset(); } + void apply(const TextProperties::TextColor::BasicColorFG& given) { - Fg.Type = TextProperties::TextColor::ColorType::BasicColor; - Fg.Data.BasicColor = given; + fg.type = TextProperties::TextColor::ColorType::BasicColor; + fg.data.basic_color = given; } - void Apply(const TextProperties::TextColor::BasicColorBG& given) + void apply(const TextProperties::TextColor::BasicColorBG& given) { - Bg.Type = TextProperties::TextColor::ColorType::BasicColor; - Bg.Data.BasicColor = given; + bg.type = TextProperties::TextColor::ColorType::BasicColor; + bg.data.basic_color = given; } - void Apply(const TextProperties::TextColor::BasicColor& given) + void apply(const TextProperties::TextColor::BasicColor& given) { - Apply(given.Fg); - Apply(given.Bg); + apply(given.fg); + apply(given.bg); } - void Apply(const TextProperties::TextColor::ColorCubeFG& given) + void apply(const TextProperties::TextColor::ColorCubeFG& given) { - Fg.Type = TextProperties::TextColor::ColorType::ColorCube; - Fg.Data.ColorCube = given; + fg.type = TextProperties::TextColor::ColorType::ColorCube; + fg.data.color_cube = given; } - void Apply(const TextProperties::TextColor::ColorCubeBG& given) + void apply(const TextProperties::TextColor::ColorCubeBG& given) { - Bg.Type = TextProperties::TextColor::ColorType::ColorCube; - Bg.Data.ColorCube = given; + bg.type = TextProperties::TextColor::ColorType::ColorCube; + bg.data.color_cube = given; } - void Apply(const TextProperties::TextColor::ColorCube& given) + void apply(const TextProperties::TextColor::ColorCube& given) { - Apply(given.Fg); - Apply(given.Bg); + apply(given.fg); + apply(given.bg); } - void Apply(const TextProperties::TextColor::Color24bFG& given) + void apply(const TextProperties::TextColor::Color24bFG& given) { - Fg.Type = TextProperties::TextColor::ColorType::Color24b; - Fg.Data.Color24b = given; + fg.type = TextProperties::TextColor::ColorType::Color24b; + fg.data.color24b = given; } - void Apply(const TextProperties::TextColor::Color24bBG& given) + void apply(const TextProperties::TextColor::Color24bBG& given) { - Bg.Type = TextProperties::TextColor::ColorType::Color24b; - Bg.Data.Color24b = given; + bg.type = TextProperties::TextColor::ColorType::Color24b; + bg.data.color24b = given; } - void Apply(const TextProperties::TextColor::Color24b& given) + void apply(const TextProperties::TextColor::Color24b& given) { - Apply(given.Fg); - Apply(given.Bg); + apply(given.fg); + apply(given.bg); } public: - bool NeedModif(const TextProperties::TextColor::reset_color&) { return true; } - - bool NeedModif(const TextProperties::TextColor::Color& given) { return *this != given; } - - bool NeedModif(const TextProperties::TextColor::BasicColorFG& given) { return Fg.Type != TextProperties::TextColor::ColorType::BasicColor || Fg.Data.BasicColor != given; } - bool NeedModif(const TextProperties::TextColor::BasicColorBG& given) { return Bg.Type != TextProperties::TextColor::ColorType::BasicColor || Bg.Data.BasicColor != given; } - bool NeedModif(const TextProperties::TextColor::BasicColor& given) { return NeedModif(given.Fg) || NeedModif(given.Bg); } - bool NeedModif(const TextProperties::TextColor::ColorCubeFG& given) { return Fg.Type != TextProperties::TextColor::ColorType::ColorCube || Fg.Data.ColorCube != given; } - bool NeedModif(const TextProperties::TextColor::ColorCubeBG& given) { return Bg.Type != TextProperties::TextColor::ColorType::ColorCube || Bg.Data.ColorCube != given; } - bool NeedModif(const TextProperties::TextColor::ColorCube& given) { return NeedModif(given.Fg) || NeedModif(given.Bg); } - bool NeedModif(const TextProperties::TextColor::Color24bFG& given) { return Fg.Type != TextProperties::TextColor::ColorType::Color24b || Fg.Data.Color24b != given; } - bool NeedModif(const TextProperties::TextColor::Color24bBG& given) { return Bg.Type != TextProperties::TextColor::ColorType::Color24b || Bg.Data.Color24b != given; } - bool NeedModif(const TextProperties::TextColor::Color24b& given) { return NeedModif(given.Fg) || NeedModif(given.Bg); } + bool need_modif(const TextProperties::TextColor::reset_color&) { return true; } + + bool need_modif(const TextProperties::TextColor::Color& given) { return *this != given; } + + bool need_modif(const TextProperties::TextColor::BasicColorFG& given) { return fg.type != TextProperties::TextColor::ColorType::BasicColor || fg.data.basic_color != given; } + bool need_modif(const TextProperties::TextColor::BasicColorBG& given) { return bg.type != TextProperties::TextColor::ColorType::BasicColor || bg.data.basic_color != given; } + bool need_modif(const TextProperties::TextColor::BasicColor& given) { return need_modif(given.fg) || need_modif(given.bg); } + bool need_modif(const TextProperties::TextColor::ColorCubeFG& given) { return fg.type != TextProperties::TextColor::ColorType::ColorCube || fg.data.color_cube != given; } + bool need_modif(const TextProperties::TextColor::ColorCubeBG& given) { return bg.type != TextProperties::TextColor::ColorType::ColorCube || bg.data.color_cube != given; } + bool need_modif(const TextProperties::TextColor::ColorCube& given) { return need_modif(given.fg) || need_modif(given.bg); } + bool need_modif(const TextProperties::TextColor::Color24bFG& given) { return fg.type != TextProperties::TextColor::ColorType::Color24b || fg.data.color24b != given; } + bool need_modif(const TextProperties::TextColor::Color24bBG& given) { return bg.type != TextProperties::TextColor::ColorType::Color24b || bg.data.color24b != given; } + bool need_modif(const TextProperties::TextColor::Color24b& given) { return need_modif(given.fg) || need_modif(given.bg); } }; inline bool operator==(const TextProperties::TextColor::Color& lhs, const TextProperties::TextColor::Color& rhs) { - return lhs.Fg == rhs.Fg && lhs.Bg == rhs.Bg; + return lhs.fg == rhs.fg && lhs.bg == rhs.bg; } template - concept TextPropertiesColorCanApply = requires(const T& value, TextProperties::TextColor::Color& data) + concept text_properties_color_can_apply = requires(const T& value, TextProperties::TextColor::Color& data) { - data.Apply(value); + data.apply(value); }; template - struct TextPropertiesColorIsApplyType + struct TextPropertiesColorIsapplyType { - using BaseType = GetBaseType; - static constexpr bool Value = std::is_same_v || std::is_same_v || + using BaseType = get_base_type; + static constexpr bool value = std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || @@ -548,5 +548,5 @@ namespace stream::fmt::detail }; template - concept TextPropertiesColorIsApply = TextPropertiesColorIsApplyType::Value; + concept TextPropertiesColorIsapply = TextPropertiesColorIsapplyType::value; } diff --git a/src/stream/fmt/text_properties/text_properties_front.h b/src/stream/fmt/text_properties/text_properties_front.h index 21309d2b..60aed559 100644 --- a/src/stream/fmt/text_properties/text_properties_front.h +++ b/src/stream/fmt/text_properties/text_properties_front.h @@ -49,16 +49,16 @@ namespace stream::fmt::detail FrontID CurrentID; public: - void ModifyReset() { *this = Front{}; } + void modify_reset() { *this = Front{}; } - void Apply(const TextProperties::TextFront::reset_front&) { ModifyReset(); } - void Apply(const TextProperties::TextFront::Front& given) { *this = given; } - void Apply(const TextProperties::TextFront::FrontID& given) { CurrentID = given; } + void apply(const TextProperties::TextFront::reset_front&) { modify_reset(); } + void apply(const TextProperties::TextFront::Front& given) { *this = given; } + void apply(const TextProperties::TextFront::FrontID& given) { CurrentID = given; } public: - bool NeedModif(const TextProperties::TextFront::reset_front&) { return true; } - bool NeedModif(const TextProperties::TextFront::Front& given) { return *this != given; } - bool NeedModif(const TextProperties::TextFront::FrontID& given) { return CurrentID != given; } + bool need_modif(const TextProperties::TextFront::reset_front&) { return true; } + bool need_modif(const TextProperties::TextFront::Front& given) { return *this != given; } + bool need_modif(const TextProperties::TextFront::FrontID& given) { return CurrentID != given; } }; inline bool operator==(const TextProperties::TextFront::Front& lhs, const TextProperties::TextFront::Front& rhs) @@ -67,19 +67,19 @@ namespace stream::fmt::detail } template - concept TextPropertiesFrontCanApply = requires(const T& value, TextProperties::TextFront::Front& data) + concept text_properties_front_can_apply = requires(const T& value, TextProperties::TextFront::Front& data) { - data.Apply(value); + data.apply(value); }; template - struct TextPropertiesFrontIsApplyType + struct TextPropertiesFrontIsapplyType { - using BaseType = GetBaseType; - static constexpr bool Value = std::is_same_v || std::is_same_v || + using BaseType = get_base_type; + static constexpr bool value = std::is_same_v || std::is_same_v || std::is_same_v; }; template - concept TextPropertiesFrontIsApply = TextPropertiesFrontIsApplyType::Value; + concept TextPropertiesFrontIsapply = TextPropertiesFrontIsapplyType::value; } diff --git a/src/stream/fmt/text_properties/text_properties_style.h b/src/stream/fmt/text_properties/text_properties_style.h index a1c74534..cffe3595 100644 --- a/src/stream/fmt/text_properties/text_properties_style.h +++ b/src/stream/fmt/text_properties/text_properties_style.h @@ -7,7 +7,7 @@ namespace stream::fmt::detail { struct TextProperties::TextStyle { - struct ResetStyle + struct reset_style { }; @@ -84,7 +84,7 @@ namespace stream::fmt::detail struct Color; }; - // No need of virtual destructor since Color24b is purely a renaming of BaseColor24b + // No need of virtual destructor since color24b is purely a renaming of BaseColor24b struct TextProperties::TextStyle::UnderlineColor::Color24b : public TextProperties::TextColor::BaseColor24b { constexpr Color24b(std::uint8_t r = 0, std::uint8_t g = 0, std::uint8_t b = 0) @@ -92,7 +92,7 @@ namespace stream::fmt::detail {} }; - // No need of virtual destructor since ColorCube is purely a renaming of BaseColorCube + // No need of virtual destructor since color_cube is purely a renaming of BaseColorCube struct TextProperties::TextStyle::UnderlineColor::ColorCube : public TextProperties::TextColor::BaseColorCube { constexpr ColorCube() @@ -135,30 +135,30 @@ namespace stream::fmt::detail union TextProperties::TextStyle::UnderlineColor::ColorData { constexpr ColorData() - : ColorCube() + : color_cube() {} - TextProperties::TextStyle::UnderlineColor::ColorCube ColorCube; - TextProperties::TextStyle::UnderlineColor::Color24b Color24b; + TextProperties::TextStyle::UnderlineColor::ColorCube color_cube; + TextProperties::TextStyle::UnderlineColor::Color24b color24b; }; struct TextProperties::TextStyle::UnderlineColor::Color { - TextProperties::TextStyle::UnderlineColor::ColorData Data; - TextProperties::TextStyle::UnderlineColor::ColorType Type = TextProperties::TextStyle::UnderlineColor::ColorType::Default; + TextProperties::TextStyle::UnderlineColor::ColorData data; + TextProperties::TextStyle::UnderlineColor::ColorType type = TextProperties::TextStyle::UnderlineColor::ColorType::Default; }; inline bool operator==(const TextProperties::TextStyle::UnderlineColor::Color& lhs, const TextProperties::TextStyle::UnderlineColor::Color& rhs) { - if (lhs.Type != rhs.Type) return false; - switch (lhs.Type) + if (lhs.type != rhs.type) return false; + switch (lhs.type) { case TextProperties::TextStyle::UnderlineColor::ColorType::Default: return true; case TextProperties::TextStyle::UnderlineColor::ColorType::ColorCube: - return lhs.Data.ColorCube == rhs.Data.ColorCube; + return lhs.data.color_cube == rhs.data.color_cube; case TextProperties::TextStyle::UnderlineColor::ColorType::Color24b: - return lhs.Data.Color24b == rhs.Data.Color24b; + return lhs.data.color24b == rhs.data.color24b; } return false; } @@ -170,80 +170,80 @@ namespace stream::fmt::detail public: constexpr Style() {} - TextProperties::TextStyle::Intensity Intensity = TextProperties::TextStyle::Intensity::Normal; - TextProperties::TextStyle::Italic Italic = TextProperties::TextStyle::Italic::Disable; - TextProperties::TextStyle::Blink Blink = TextProperties::TextStyle::Blink::Disable; - TextProperties::TextStyle::Inverted Inverted = TextProperties::TextStyle::Inverted::Disable; - TextProperties::TextStyle::Ideogram Ideogram = TextProperties::TextStyle::Ideogram::AllDisable; - TextProperties::TextStyle::Script Script = TextProperties::TextStyle::Script::AllDisable; + TextProperties::TextStyle::Intensity intensity = TextProperties::TextStyle::Intensity::Normal; + TextProperties::TextStyle::Italic italic = TextProperties::TextStyle::Italic::Disable; + TextProperties::TextStyle::Blink blink = TextProperties::TextStyle::Blink::Disable; + TextProperties::TextStyle::Inverted inverted = TextProperties::TextStyle::Inverted::Disable; + TextProperties::TextStyle::Ideogram ideogram = TextProperties::TextStyle::Ideogram::AllDisable; + TextProperties::TextStyle::Script script = TextProperties::TextStyle::Script::AllDisable; - TextProperties::TextStyle::Underline Underline = TextProperties::TextStyle::Underline::Disable; - TextProperties::TextStyle::UnderlineColor::Color UnderlineColor; + TextProperties::TextStyle::Underline underline = TextProperties::TextStyle::Underline::Disable; + TextProperties::TextStyle::UnderlineColor::Color underline_color; public: - void ModifyReset() { *this = Style{}; } - - void Apply(const TextProperties::TextStyle::ResetStyle&) { ModifyReset(); } - void Apply(const TextProperties::TextStyle::Style& given) { *this = given; } - void Apply(const TextProperties::TextStyle::Intensity& given) { Intensity = given; } - void Apply(const TextProperties::TextStyle::Italic& given) { Italic = given; } - void Apply(const TextProperties::TextStyle::Underline& given) { Underline = given; } - void Apply(const TextProperties::TextStyle::Blink& given) { Blink = given; } - void Apply(const TextProperties::TextStyle::Inverted& given) { Inverted = given; } - void Apply(const TextProperties::TextStyle::Ideogram& given) { Ideogram = given; } - void Apply(const TextProperties::TextStyle::Script& given) { Script = given; } - - void Apply(const TextProperties::TextStyle::UnderlineColor::Color& given) { UnderlineColor = given; } - void Apply(const TextProperties::TextStyle::UnderlineColor::ColorCube& given) + void modify_reset() { *this = Style{}; } + + void apply(const TextProperties::TextStyle::reset_style&) { modify_reset(); } + void apply(const TextProperties::TextStyle::Style& given) { *this = given; } + void apply(const TextProperties::TextStyle::Intensity& given) { intensity = given; } + void apply(const TextProperties::TextStyle::Italic& given) { italic = given; } + void apply(const TextProperties::TextStyle::Underline& given) { underline = given; } + void apply(const TextProperties::TextStyle::Blink& given) { blink = given; } + void apply(const TextProperties::TextStyle::Inverted& given) { inverted = given; } + void apply(const TextProperties::TextStyle::Ideogram& given) { ideogram = given; } + void apply(const TextProperties::TextStyle::Script& given) { script = given; } + + void apply(const TextProperties::TextStyle::UnderlineColor::Color& given) { underline_color = given; } + void apply(const TextProperties::TextStyle::UnderlineColor::ColorCube& given) { - UnderlineColor.Type = TextProperties::TextStyle::UnderlineColor::ColorType::ColorCube; - UnderlineColor.Data.ColorCube = given; + underline_color.type = TextProperties::TextStyle::UnderlineColor::ColorType::ColorCube; + underline_color.data.color_cube = given; } - void Apply(const TextProperties::TextStyle::UnderlineColor::Color24b& given) + void apply(const TextProperties::TextStyle::UnderlineColor::Color24b& given) { - UnderlineColor.Type = TextProperties::TextStyle::UnderlineColor::ColorType::Color24b; - UnderlineColor.Data.Color24b = given; + underline_color.type = TextProperties::TextStyle::UnderlineColor::ColorType::Color24b; + underline_color.data.color24b = given; } public: - bool NeedModif(const TextProperties::TextStyle::ResetStyle&) { return true; } - bool NeedModif(const TextProperties::TextStyle::Style& given) { return *this != given; } - bool NeedModif(const TextProperties::TextStyle::Intensity& given) { return Intensity != given; } - bool NeedModif(const TextProperties::TextStyle::Italic& given) { return Italic != given; } - bool NeedModif(const TextProperties::TextStyle::Underline& given) { return Underline != given; } - bool NeedModif(const TextProperties::TextStyle::Blink& given) { return Blink != given; } - bool NeedModif(const TextProperties::TextStyle::Inverted& given) { return Inverted != given; } - bool NeedModif(const TextProperties::TextStyle::Ideogram& given) { return Ideogram != given; } - bool NeedModif(const TextProperties::TextStyle::Script& given) { return Script != given; } - - bool NeedModif(const TextProperties::TextStyle::UnderlineColor::Color& given) { return UnderlineColor != given; } - bool NeedModif(const TextProperties::TextStyle::UnderlineColor::ColorCube& given) + bool need_modif(const TextProperties::TextStyle::reset_style&) { return true; } + bool need_modif(const TextProperties::TextStyle::Style& given) { return *this != given; } + bool need_modif(const TextProperties::TextStyle::Intensity& given) { return intensity != given; } + bool need_modif(const TextProperties::TextStyle::Italic& given) { return italic != given; } + bool need_modif(const TextProperties::TextStyle::Underline& given) { return underline != given; } + bool need_modif(const TextProperties::TextStyle::Blink& given) { return blink != given; } + bool need_modif(const TextProperties::TextStyle::Inverted& given) { return inverted != given; } + bool need_modif(const TextProperties::TextStyle::Ideogram& given) { return ideogram != given; } + bool need_modif(const TextProperties::TextStyle::Script& given) { return script != given; } + + bool need_modif(const TextProperties::TextStyle::UnderlineColor::Color& given) { return underline_color != given; } + bool need_modif(const TextProperties::TextStyle::UnderlineColor::ColorCube& given) { - return UnderlineColor.Type != TextProperties::TextStyle::UnderlineColor::ColorType::ColorCube || UnderlineColor.Data.ColorCube != given; + return underline_color.type != TextProperties::TextStyle::UnderlineColor::ColorType::ColorCube || underline_color.data.color_cube != given; } - bool NeedModif(const TextProperties::TextStyle::UnderlineColor::Color24b& given) + bool need_modif(const TextProperties::TextStyle::UnderlineColor::Color24b& given) { - return UnderlineColor.Type != TextProperties::TextStyle::UnderlineColor::ColorType::Color24b || UnderlineColor.Data.Color24b != given; + return underline_color.type != TextProperties::TextStyle::UnderlineColor::ColorType::Color24b || underline_color.data.color24b != given; } }; inline bool operator==(const TextProperties::TextStyle::Style& lhs, const TextProperties::TextStyle::Style& rhs) { - return lhs.Intensity == rhs.Intensity && lhs.Italic == rhs.Italic && lhs.Blink == rhs.Blink && lhs.Inverted == rhs.Inverted && lhs.Ideogram == rhs.Ideogram && - lhs.Script == rhs.Script && lhs.Underline == rhs.Underline && lhs.UnderlineColor == rhs.UnderlineColor; + return lhs.intensity == rhs.intensity && lhs.italic == rhs.italic && lhs.blink == rhs.blink && lhs.inverted == rhs.inverted && lhs.ideogram == rhs.ideogram && + lhs.script == rhs.script && lhs.underline == rhs.underline && lhs.underline_color == rhs.underline_color; } template - concept TextPropertiesStyleCanApply = requires(const T& value, TextProperties::TextStyle::Style& data) + concept text_properties_style_can_apply = requires(const T& value, TextProperties::TextStyle::Style& data) { - data.Apply(value); + data.apply(value); }; template - struct TextPropertiesStyleIsApplyType + struct TextPropertiesStyleIsapplyType { - using BaseType = GetBaseType; - static constexpr bool Value = std::is_same_v || std::is_same_v || + using BaseType = get_base_type; + static constexpr bool value = std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || @@ -253,7 +253,7 @@ namespace stream::fmt::detail }; template - concept TextPropertiesStyleIsApply = TextPropertiesStyleIsApplyType::Value; + concept TextPropertiesStyleIsapply = TextPropertiesStyleIsapplyType::value; } namespace stream::fmt::detail::OLD diff --git a/src/stream/json.h b/src/stream/json.h index fb82dfdb..3e4c6d08 100644 --- a/src/stream/json.h +++ b/src/stream/json.h @@ -1,7 +1,7 @@ #pragma once -#include "Json/JsonFactory.h" -#include "Json/JsonObjects.h" +#include "json/json_factory.h" +#include "json/json_objects.h" -#include "Json/JsonSerializer.h" -#include "Json/serializers/Serializers.h" +#include "json/json_serializer.h" +#include "json/serializers/serializers.h" diff --git a/src/stream/json/detail.h b/src/stream/json/detail.h index 95b2467f..f4c092e6 100644 --- a/src/stream/json/detail.h +++ b/src/stream/json/detail.h @@ -5,7 +5,7 @@ #include #include -namespace stream::JSON::detail +namespace stream::json::detail { class JsonError : public std::exception { @@ -64,7 +64,7 @@ namespace stream::JSON::detail }; } -namespace stream::JSON +namespace stream::json { template struct JsonObjectSerializer; diff --git a/src/stream/json/json_factory.h b/src/stream/json/json_factory.h index 39619d57..6ccce9f0 100644 --- a/src/stream/json/json_factory.h +++ b/src/stream/json/json_factory.h @@ -1,17 +1,17 @@ #pragma once -#include "JsonFormatter-inl.h" -#include "JsonFormatter.h" -#include "JsonObjects.h" -#include "JsonParser.h" -#include "JsonSerializer.h" -#include "serializers/JsonObjectsSerializer.h" -#include "serializers/Serializers.h" +#include "json_formatter_impl.h" +#include "json_formatter.h" +#include "json_objects.h" +#include "json_parser.h" +#include "json_serializer.h" +#include "serializers/json_objects_serializer.h" +#include "serializers/serializers.h" #include #include -namespace stream::JSON +namespace stream::json { class JsonFactory { @@ -27,18 +27,18 @@ namespace stream::JSON namespace stream::fmt { template - struct FormatterType + struct FormatterType { - [[nodiscard]] static std::expected format(const JSON::JsonObject& object, FormatterExecutor& executor) - { return executor.WriteType(JSON::FormatAsJson(object)); } + [[nodiscard]] static std::expected format(const json::JsonObject& object, FormatterExecutor& executor) + { return executor.write_type(json::FormatAsJson(object)); } }; } #include #include -#include "stream//fmt/buffer/buffer_out_manager/dynamic_buffer_out_manager.h" -#include "serializers/JsonObjectsSerializer.h" -namespace stream::JSON +#include "stream//fmt/buf/streamio_manager/dynamic_streamio_manager.h" +#include "serializers/json_objects_serializer.h" +namespace stream::json { template T JsonFactory::FromPath(const std::filesystem::path& path) @@ -56,7 +56,7 @@ namespace stream::JSON file.read(buffer.data(), size); file.close(); - fmt::detail::BufferInfoView input(buffer.data(), buffer.size()); + fmt::buf::StreamView input(buffer.data(), buffer.size()); detail::JsonParser parser(input); T res; JsonSerializer::parse(res, parser); @@ -70,12 +70,12 @@ namespace stream::JSON if (file.is_open() == false) throw std::runtime_error("unable to open file"); - fmt::detail::DynamicBufferOutManager BufferOutManager(256); - fmt::detail::BufferOutInfo bufferOut = fmt::detail::BufferOutInfo::Create(BufferOutManager).value(); - detail::JsonFormatter formatter(bufferOut, settings); + fmt::buf::DynamicStreamIOManager StreamIOManager(256); + fmt::buf::StreamIO ostream = fmt::buf::StreamIO::create(StreamIOManager).value(); + detail::JsonFormatter formatter(ostream, settings); JsonSerializer::format(json, formatter); - file.write(BufferOutManager.GetBuffer(), static_cast(BufferOutManager.GetLastGeneratedDataSize())); + file.write(StreamIOManager.get_buffer(), static_cast(StreamIOManager.get_last_generated_data_size())); file.flush(); file.close(); } diff --git a/src/stream/json/json_formatter.h b/src/stream/json/json_formatter.h index 97633a72..981271ba 100644 --- a/src/stream/json/json_formatter.h +++ b/src/stream/json/json_formatter.h @@ -1,32 +1,33 @@ #pragma once -#include "JsonObjects.h" -#include "stream/fmt/buffer/buffer_out_manip.h" +#include "json_objects.h" +#include "stream/fmt/buf/streamio.h" +#include "stream/fmt/buf/manip_io.h" -namespace stream::JSON::detail +namespace stream::json::detail { class JsonFormatter { public: struct FormatSettings { - std::size_t IndentSize = 4; - bool IndentWithSpaces = true; - bool OneLine = false; - bool OrderedStruct = false; - std::int32_t FloatPrecision = 7; + std::size_t indent_size = 4; + bool indent_with_spaces = true; + bool one_line = false; + bool ordered_struct = false; + std::int32_t float_precision = 7; }; public: - JsonFormatter(stream::fmt::detail::BufferOutInfo& bufferOut) - : BufferOut(bufferOut) - , Settings() - , m_Indent(0) + JsonFormatter(stream::fmt::buf::StreamIO& ostream_) + : ostream(ostream_) + , settings() + , indent_(0) {} - JsonFormatter(stream::fmt::detail::BufferOutInfo& bufferOut, FormatSettings settings) - : BufferOut(bufferOut) - , Settings(settings) - , m_Indent(0) + JsonFormatter(stream::fmt::buf::StreamIO& ostream_, FormatSettings settings_) + : ostream(ostream_) + , settings(settings_) + , indent_(0) {} public: @@ -35,39 +36,39 @@ namespace stream::JSON::detail struct StructIntermediate; struct ArrayIntermediate; - StructIntermediate GetStructIntermediate(); - ArrayIntermediate GetArrayIntermediate(); + StructIntermediate get_struct_intermediate(); + ArrayIntermediate get_array_intermediate(); public: - void Indent() + void indent() { - if (Settings.OneLine) return; + if (settings.one_line) return; - if (Settings.IndentWithSpaces) - fmt::detail::BufferOutManip(BufferOut).Pushback(' ', m_Indent * Settings.IndentSize).value(); + if (settings.indent_with_spaces) + fmt::buf::ManipIO(ostream).pushback(' ', indent_ * settings.indent_size).value(); else - fmt::detail::BufferOutManip(BufferOut).Pushback('\t', m_Indent * Settings.IndentSize).value(); + fmt::buf::ManipIO(ostream).pushback('\t', indent_ * settings.indent_size).value(); } void NewLine() { - if (Settings.OneLine) return; - fmt::detail::BufferOutManip(BufferOut).Pushback('\n').value(); - Indent(); + if (settings.one_line) return; + fmt::buf::ManipIO(ostream).pushback('\n').value(); + indent(); } - void BeginNewObject() { ++m_Indent; } - void EndNewObject() { --m_Indent; } + void begin_new_object() { ++indent_; } + void end_new_object() { --indent_; } public: - stream::fmt::detail::BufferOutInfo& BufferOut; - FormatSettings Settings; + fmt::buf::StreamIO& ostream; + FormatSettings settings; protected: - std::size_t m_Indent; + std::size_t indent_; }; } -namespace stream::JSON::detail +namespace stream::json::detail { struct JsonFormatter::StructIntermediate { @@ -99,12 +100,12 @@ namespace stream::JSON::detail std::uint32_t Idx; }; - inline JsonFormatter::StructIntermediate JsonFormatter::GetStructIntermediate() + inline JsonFormatter::StructIntermediate JsonFormatter::get_struct_intermediate() { return JsonFormatter::StructIntermediate(*this); } - inline JsonFormatter::ArrayIntermediate JsonFormatter::GetArrayIntermediate() + inline JsonFormatter::ArrayIntermediate JsonFormatter::get_array_intermediate() { return JsonFormatter::ArrayIntermediate(*this); } diff --git a/src/stream/json/json_formatter_impl.h b/src/stream/json/json_formatter_impl.h index 642cad3e..866eff5b 100644 --- a/src/stream/json/json_formatter_impl.h +++ b/src/stream/json/json_formatter_impl.h @@ -1,8 +1,8 @@ -#include "JsonFormatter.h" +#include "json_formatter.h" -#include "JsonSerializer.h" +#include "json_serializer.h" -namespace stream::JSON::detail +namespace stream::json::detail { inline JsonFormatter::StructIntermediate::StructIntermediate(JsonFormatter& formatter) : Formatter(formatter) diff --git a/src/stream/json/json_objects.cpp b/src/stream/json/json_objects.cpp index 1cb6979b..d64b1666 100644 --- a/src/stream/json/json_objects.cpp +++ b/src/stream/json/json_objects.cpp @@ -1,7 +1,7 @@ -#include "JsonObjects.h" -#include "serializers/JsonObjectsSerializer.h" +#include "json_objects.h" +#include "serializers/json_objects_serializer.h" -namespace stream::JSON +namespace stream::json { void JsonStringObject::ParserExecute(detail::JsonParser& parser) { diff --git a/src/stream/json/json_objects.h b/src/stream/json/json_objects.h index 43905ff4..8ed5d515 100644 --- a/src/stream/json/json_objects.h +++ b/src/stream/json/json_objects.h @@ -9,13 +9,13 @@ #include #include -namespace stream::JSON::detail +namespace stream::json::detail { class JsonParser; class JsonFormatter; } -namespace stream::JSON +namespace stream::json { struct JsonObject { @@ -45,11 +45,11 @@ namespace stream::JSON public: ObjectType GetType() { return m_Type; } - JsonObject& operator[](const std::size_t index) { return Get(index); } - JsonObject& operator[](const std::string_view subObject) { return Get(subObject); } + JsonObject& operator[](const std::size_t index) { return get(index); } + JsonObject& operator[](const std::string_view subObject) { return get(subObject); } - virtual JsonObject& Get(const std::size_t) { throw detail::JsonIndexingError{}; } - virtual JsonObject& Get(const std::string_view) { throw detail::JsonIndexingError{}; } + virtual JsonObject& get(const std::size_t) { throw detail::JsonIndexingError{}; } + virtual JsonObject& get(const std::string_view) { throw detail::JsonIndexingError{}; } public: template @@ -83,7 +83,7 @@ namespace stream::JSON JsonObjectSerializer::WriteObject(t, *this); } - std::string ToString() { return fmt::FormatString(*this).value(); } + std::string ToString() { return fmt::format_string(*this).value(); } public: virtual void ParserExecute(detail::JsonParser& parser) = 0; @@ -109,9 +109,9 @@ namespace stream::JSON std::string String; public: - static std::unique_ptr Create() { return std::make_unique(); } - static std::unique_ptr Create(const std::string_view value) { return std::make_unique(value); } - static std::unique_ptr Create(std::string&& value) { return std::make_unique(std::move(value)); } + static std::unique_ptr create() { return std::make_unique(); } + static std::unique_ptr create(const std::string_view value) { return std::make_unique(value); } + static std::unique_ptr create(std::string&& value) { return std::make_unique(std::move(value)); } public: void ParserExecute(detail::JsonParser& parser) override; @@ -130,7 +130,7 @@ namespace stream::JSON double Number; public: - static std::unique_ptr Create(double value = 0.0) { return std::make_unique(value); } + static std::unique_ptr create(double value = 0.0) { return std::make_unique(value); } public: void ParserExecute(detail::JsonParser& parser) override; @@ -149,7 +149,7 @@ namespace stream::JSON bool Boolean; public: - static std::unique_ptr Create(bool value = false) { return std::make_unique(value); } + static std::unique_ptr create(bool value = false) { return std::make_unique(value); } public: void ParserExecute(detail::JsonParser& parser) override; @@ -165,7 +165,7 @@ namespace stream::JSON ~JsonStructObject() override = default; public: - static std::unique_ptr Create() { return std::make_unique(); } + static std::unique_ptr create() { return std::make_unique(); } public: std::unordered_map> Objects; @@ -173,7 +173,7 @@ namespace stream::JSON public: void Add(const std::string& name, std::unique_ptr&& object) { Objects.insert({name, std::move(object)}); } void Add(std::string&& name, std::unique_ptr&& object) { Objects.insert({std::move(name), std::move(object)}); } - JsonObject& Get(const std::string_view subObject) override + JsonObject& get(const std::string_view subObject) override { try { @@ -199,14 +199,14 @@ namespace stream::JSON ~JsonArrayObject() override = default; public: - static std::unique_ptr Create() { return std::make_unique(); } + static std::unique_ptr create() { return std::make_unique(); } public: std::vector> Objects; public: void Add(std::unique_ptr&& object) { Objects.emplace_back(std::move(object)); } - JsonObject& Get(const std::size_t index) override { return *Objects[index]; } + JsonObject& get(const std::size_t index) override { return *Objects[index]; } public: void ParserExecute(detail::JsonParser& parser) override; @@ -222,7 +222,7 @@ namespace stream::JSON ~JsonNullObject() override = default; public: - static std::unique_ptr Create() { return std::make_unique(); } + static std::unique_ptr create() { return std::make_unique(); } public: void ParserExecute(detail::JsonParser& parser) override; diff --git a/src/stream/json/json_parser.cpp b/src/stream/json/json_parser.cpp index 6d524823..1731e1dd 100644 --- a/src/stream/json/json_parser.cpp +++ b/src/stream/json/json_parser.cpp @@ -4,60 +4,60 @@ #include #include -#include "JsonSerializer.h" +#include "json_serializer.h" -namespace stream::JSON::detail +namespace stream::json::detail { void JsonParser::Intermediate::parse(detail::JsonParser& parser) { - fmt::detail::BufferTestAccess access(parser.BufferIn); - fmt::detail::BufferTestManip manip(parser.BufferIn); + fmt::buf::TestAccess access(parser.istream); + fmt::buf::TestManip manip(parser.istream); manip.IgnoreEveryBlanks(); - const char* begin = parser.BufferIn.CurrentPos; + const char* begin = parser.istream.current_pos; - if (parser.IsJsonStringBegin()) + if (parser.is_json_string_begin()) { - manip.SkipOneOf('"').value(); + manip.skip_one_of('"').value(); while (true) { manip.GoTo('"'); - if (fmt::detail::BufferTestAccess(parser.BufferIn).PrevIsNotEqualTo('\\')) + if (fmt::buf::Access(parser.istream).get_prev_force() != '\\') break; } - manip.SkipOneOf('"').value(); + manip.skip_one_of('"').value(); } - else if (parser.IsJsonNumberBegin()) + else if (parser.is_json_number_begin()) { float k; JsonNumberSerializer::ParseFloat(k, parser); } - else if (parser.IsJsonBooleanBegin()) + else if (parser.is_json_boolean_begin()) { bool k; JsonBooleanSerializer::ParseBool(k, parser); } - else if (parser.IsJsonStructBegin()) + else if (parser.is_json_struct_begin()) { JsonStructSerializer::LoadAllSubObjects(*this, parser, [](JsonParser::Intermediate&, std::size_t, std::string&&, JsonParser& jsonParser) { JsonParser::Intermediate intermediate; intermediate.parse(jsonParser); }); } - else if (parser.IsJsonArrayBegin()) + else if (parser.is_json_array_begin()) { JsonArraySerializer::LoadAllSubObjects(*this, parser, [](JsonParser::Intermediate&, std::size_t, JsonParser& jsonParser) { JsonParser::Intermediate intermediate; intermediate.parse(jsonParser); }); } - else if (parser.IsJsonNullBegin()) + else if (parser.is_json_null_begin()) { JsonNullSerializer::ParseNull(parser); } - const char* end = parser.BufferIn.CurrentPos; - Data = std::string_view(begin, end); + const char* end = parser.istream.current_pos; + data = std::string_view(begin, end); }; void JsonParser::StructIntermediate::parse(detail::JsonParser& parser) diff --git a/src/stream/json/json_parser.h b/src/stream/json/json_parser.h index 6bf17362..45d52f1c 100644 --- a/src/stream/json/json_parser.h +++ b/src/stream/json/json_parser.h @@ -1,32 +1,32 @@ #pragma once -#include "stream/fmt/buffer/buffer_info.h" +#include "stream/fmt/buf/stream.h" -#include "JsonObjects.h" +#include "json_objects.h" -namespace stream::JSON::detail +namespace stream::json::detail { class JsonParser { public: JsonParser() - : BufferIn() + : istream() {} - JsonParser(fmt::detail::BufferInfoView& input) - : BufferIn(input) + JsonParser(fmt::buf::StreamView& input) + : istream(input) {} public: - inline bool IsJsonStringBegin() const { return fmt::detail::BufferTestAccess(BufferIn).IsEqualTo('"'); } - inline bool IsJsonNumberBegin() const { return fmt::detail::BufferTestAccess(BufferIn).IsADigit() || fmt::detail::BufferTestAccess(BufferIn).IsEqualTo('+', '-', '.'); } - inline bool IsJsonBooleanBegin() const { return fmt::detail::BufferTestAccess(BufferIn).IsEqualTo('t', 'f'); } - inline bool IsJsonStructBegin() const { return fmt::detail::BufferTestAccess(BufferIn).IsEqualTo('{'); } - inline bool IsJsonArrayBegin() const { return fmt::detail::BufferTestAccess(BufferIn).IsEqualTo('['); } - inline bool IsJsonNullBegin() const { return fmt::detail::BufferTestAccess(BufferIn).IsEqualTo('n'); } + inline bool is_json_string_begin() const { return fmt::buf::TestAccess(istream).is_equal_to('"'); } + inline bool is_json_number_begin() const { return fmt::buf::TestAccess(istream).is_a_digit() || fmt::buf::TestAccess(istream).is_equal_to('+', '-', '.'); } + inline bool is_json_boolean_begin() const { return fmt::buf::TestAccess(istream).is_equal_to('t', 'f'); } + inline bool is_json_struct_begin() const { return fmt::buf::TestAccess(istream).is_equal_to('{'); } + inline bool is_json_array_begin() const { return fmt::buf::TestAccess(istream).is_equal_to('['); } + inline bool is_json_null_begin() const { return fmt::buf::TestAccess(istream).is_equal_to('n'); } public: - fmt::detail::BufferInfo BufferIn; + fmt::buf::Stream istream; public: struct Intermediate; @@ -37,16 +37,16 @@ namespace stream::JSON::detail struct StructIntermediate; struct ArrayIntermediate; - StructIntermediate GetStructIntermediate(); - ArrayIntermediate GetArrayIntermediate(); + StructIntermediate get_struct_intermediate(); + ArrayIntermediate get_array_intermediate(); }; } -namespace stream::JSON::detail +namespace stream::json::detail { struct JsonParser::Intermediate { - std::string_view Data; + std::string_view data; void parse(detail::JsonParser& parser); @@ -96,13 +96,13 @@ namespace stream::JSON::detail } }; - inline JsonParser::StructIntermediate JsonParser::GetStructIntermediate() + inline JsonParser::StructIntermediate JsonParser::get_struct_intermediate() { JsonParser::StructIntermediate res; res.parse(*this); return res; } - inline JsonParser::ArrayIntermediate JsonParser::GetArrayIntermediate() + inline JsonParser::ArrayIntermediate JsonParser::get_array_intermediate() { JsonParser::ArrayIntermediate res; res.parse(*this); diff --git a/src/stream/json/json_serializer.h b/src/stream/json/json_serializer.h index d6583d18..8f377a5c 100644 --- a/src/stream/json/json_serializer.h +++ b/src/stream/json/json_serializer.h @@ -1,17 +1,17 @@ #pragma once -#include "JsonFormatter.h" -#include "JsonParser.h" +#include "json_formatter.h" +#include "json_parser.h" #include "stream/fmt.h" -#include "stream/fmt/buffer/buffer_read_manip.h" -#include "stream/fmt/buffer/buffer_write_manip.h" -#include "stream/fmt/buffer/utils/buffer_utils.h" +#include "stream/fmt/buf/read_manip.h" +#include "stream/fmt/buf/write_manip.h" +#include "stream/fmt/buf/utils/buffer_utils.h" #include #include -namespace stream::JSON +namespace stream::json { template struct JsonSerializer @@ -19,7 +19,7 @@ namespace stream::JSON static inline void parse(T&, detail::JsonParser&) { #ifdef UNKOWN_TYPE_MESSAGE - fmt::FilePrint(std::cerr, "{C:red}JsonSerializer::Parse<{}> not impl", typeid(T).name()).value(); + fmt::file_print(std::cerr, "{C:red}JsonSerializer::Parse<{}> not impl", typeid(T).name()).value(); #endif #ifdef UNKOWN_TYPE_THROW throw detail::JsonTypeSerializerNotImpl{}; @@ -35,11 +35,11 @@ namespace stream::JSON static inline void format(const T&, detail::JsonFormatter& formatter) { - fmt::detail::BufferWriteManip(formatter.buffer_out).FastWriteString(std::string_view("Unknown JsonFormatter for type : ")).value(); - fmt::detail::BufferWriteManip(formatter.buffer_out).FastWriteString(std::string_view(typeid(T).name())).value(); + fmt::buf::WriteManip(formatter.ostream).fast_write_string(std::string_view("Unknown JsonFormatter for type : ")).value(); + fmt::buf::WriteManip(formatter.ostream).fast_write_string(std::string_view(typeid(T).name())).value(); #ifdef UNKOWN_TYPE_MESSAGE - fmt::FilePrint(std::cerr, "{C:red}JsonSerializer::Format<{}> not impl", typeid(T).name()).value(); + fmt::file_print(std::cerr, "{C:red}JsonSerializer::Format<{}> not impl", typeid(T).name()).value(); #endif #ifdef UNKOWN_TYPE_THROW throw detail::JsonTypeSerializerNotImpl{}; @@ -60,7 +60,7 @@ namespace stream::JSON static inline void ReadObject(T&, const JsonObject&) { #ifdef UNKOWN_TYPE_MESSAGE - fmt::FilePrint(std::cerr, "{C:red}JsonObjectSerializer::ReadObject<{}> not impl", typeid(T).name()).value(); + fmt::file_print(std::cerr, "{C:red}JsonObjectSerializer::ReadObject<{}> not impl", typeid(T).name()).value(); #endif #ifdef UNKOWN_TYPE_THROW throw detail::JsonTypeSerializerNotImpl{}; @@ -77,7 +77,7 @@ namespace stream::JSON static inline void WriteObject(const T&, JsonObject&) { #ifdef UNKOWN_TYPE_MESSAGE - fmt::FilePrint(std::cerr, "{C:red}JsonObjectSerializer::WriteObject<{}> not impl", typeid(T).name()).value(); + fmt::file_print(std::cerr, "{C:red}JsonObjectSerializer::WriteObject<{}> not impl", typeid(T).name()).value(); #endif #ifdef UNKOWN_TYPE_THROW throw detail::JsonTypeSerializerNotImpl{}; @@ -96,17 +96,17 @@ namespace stream::JSON { static inline void ParseSTDString(std::string& t, detail::JsonParser& parser) { - fmt::detail::DynamicBufferOutManager bufferData; - fmt::detail::BufferOutInfo buffer = fmt::detail::BufferOutInfo::Create(bufferData).value(); - fmt::detail::BufferUtils::parse_escaped_quoted_string(parser.BufferIn, buffer).value(); - fmt::detail::BufferOutManip(buffer).ComputeGeneratedSize(); - t = bufferData.GetLastGeneratedString(); + fmt::buf::DynamicStreamIOManager bufferData; + fmt::buf::StreamIO buffer = fmt::buf::StreamIO::create(bufferData).value(); + fmt::buf::utils::parse_escaped_quoted_string(parser.istream, buffer).value(); + fmt::buf::ManipIO(buffer).compute_generated_size(); + t = bufferData.get_last_generated_string_view(); } static inline void FormatSTDString(const std::string_view t, detail::JsonFormatter& formatter) { - fmt::detail::BufferInfo buffer(t.data(), t.size()); - fmt::detail::BufferUtils::FormatEscapedQuotedString(formatter.buffer_out, buffer).value(); + fmt::buf::Stream buffer(t.data(), t.size()); + fmt::buf::utils::format_escaped_quoted_string(formatter.ostream, buffer).value(); } }; @@ -115,32 +115,32 @@ namespace stream::JSON template static inline void ParseFloat(FloatType& t, detail::JsonParser& parser) { - fmt::detail::BufferReadManip(parser.BufferIn).FastReadFloat(t).value(); + fmt::buf::ReadManip(parser.istream).fast_read_float(t).value(); } template static inline void ParseInteger(IntType& t, detail::JsonParser& parser) { - const char* begin = parser.BufferIn.CurrentPos; + const char* begin = parser.istream.current_pos; float tmp = 0; - fmt::detail::BufferReadManip(parser.BufferIn).FastReadFloat(tmp).value(); - const char* end = parser.BufferIn.CurrentPos; + fmt::buf::ReadManip(parser.istream).fast_read_float(tmp).value(); + const char* end = parser.istream.current_pos; - parser.BufferIn.CurrentPos = begin; - fmt::detail::BufferReadManip(parser.BufferIn).FastReadInteger(t).value(); - parser.BufferIn.CurrentPos = end; + parser.istream.current_pos = begin; + fmt::buf::ReadManip(parser.istream).fast_read_integer(t).value(); + parser.istream.current_pos = end; } template static inline void FormatFloat(const FloatType& t, detail::JsonFormatter& formatter) { - fmt::detail::BufferWriteManip(formatter.buffer_out).FastWriteFloat(t, formatter.Settings.FloatPrecision).value(); + fmt::buf::WriteManip(formatter.ostream).fast_write_float(t, formatter.settings.float_precision).value(); } template static inline void FormatInteger(const IntType& t, detail::JsonFormatter& formatter) { - fmt::detail::BufferWriteManip(formatter.buffer_out).FastWriteInteger(t).value(); + fmt::buf::WriteManip(formatter.ostream).fast_write_integer(t).value(); } }; @@ -148,18 +148,18 @@ namespace stream::JSON { static inline void ParseBool(bool& t, detail::JsonParser& parser) { - if (fmt::detail::BufferTestManip(parser.BufferIn).is_same_forward("true", 5).value()) + if (fmt::buf::TestManip(parser.istream).is_same_forward("true", 5).value()) t = true; - else if (fmt::detail::BufferTestManip(parser.BufferIn).is_same_forward("false", 5).value()) + else if (fmt::buf::TestManip(parser.istream).is_same_forward("false", 5).value()) t = false; } static inline void FormatBool(const bool& t, detail::JsonFormatter& formatter) { if (t) - fmt::detail::BufferWriteManip(formatter.buffer_out).FastWriteCharArray("true", 5).value(); + fmt::buf::WriteManip(formatter.ostream).fast_write_char_array("true", 5).value(); else - fmt::detail::BufferWriteManip(formatter.buffer_out).FastWriteCharArray("false", 5).value(); + fmt::buf::WriteManip(formatter.ostream).fast_write_char_array("false", 5).value(); } }; @@ -168,31 +168,31 @@ namespace stream::JSON template static inline void LoadAllSubObjects(T& t, detail::JsonParser& parser, std::function subObjectParsingFunction) { - fmt::detail::BufferTestAccess access(parser.BufferIn); - fmt::detail::BufferTestManip manip(parser.BufferIn); + fmt::buf::TestAccess access(parser.istream); + fmt::buf::TestManip manip(parser.istream); - manip.SkipOneOf('{').value(); + manip.skip_one_of('{').value(); std::size_t idx = 0; - while (fmt::detail::BufferAccess(parser.BufferIn).IsEndOfString() == false) + while (fmt::buf::Access(parser.istream).is_end_of_string() == false) { manip.GoTo('"', '}'); - if (access.IsEqualTo('}')) break; + if (access.is_equal_to('}')) break; std::string name; JsonStringSerializer::ParseSTDString(name, parser); manip.IgnoreEveryBlanks(); - manip.SkipOneOf(':').value(); + manip.skip_one_of(':').value(); manip.IgnoreEveryBlanks(); subObjectParsingFunction(t, idx++, std::move(name), parser); manip.GoTo(',', '}'); - manip.SkipOneOf(',').value(); + manip.skip_one_of(',').value(); } - manip.SkipOneOf('}').value(); + manip.skip_one_of('}').value(); } template @@ -205,26 +205,26 @@ namespace stream::JSON }); } - static inline void FormatBegin(detail::JsonFormatter& formatter) { fmt::detail::BufferOutManip(formatter.buffer_out).Pushback('{').value(); } + static inline void FormatBegin(detail::JsonFormatter& formatter) { fmt::buf::ManipIO(formatter.ostream).pushback('{').value(); } static inline void FormatEnd(detail::JsonFormatter& formatter) { formatter.NewLine(); - fmt::detail::BufferOutManip(formatter.buffer_out).Pushback('}').value(); + fmt::buf::ManipIO(formatter.ostream).pushback('}').value(); } template static inline void FormatObject(const std::string_view name, const SubObject& subObject, const std::size_t idx, detail::JsonFormatter& formatter) { - if (idx != 0) fmt::detail::BufferOutManip(formatter.buffer_out).Pushback(',').value(); + if (idx != 0) fmt::buf::ManipIO(formatter.ostream).pushback(',').value(); - formatter.BeginNewObject(); + formatter.begin_new_object(); formatter.NewLine(); JsonStringSerializer::FormatSTDString(name, formatter); - fmt::detail::BufferOutManip(formatter.buffer_out).Pushback(':').value(); - fmt::detail::BufferOutManip(formatter.buffer_out).Pushback(' ').value(); + fmt::buf::ManipIO(formatter.ostream).pushback(':').value(); + fmt::buf::ManipIO(formatter.ostream).pushback(' ').value(); formatter.format(subObject); - formatter.EndNewObject(); + formatter.end_new_object(); } }; @@ -233,25 +233,25 @@ namespace stream::JSON template static inline void LoadAllSubObjects(T& t, detail::JsonParser& parser, std::function subObjectParsingFunction) { - fmt::detail::BufferTestAccess access(parser.BufferIn); - fmt::detail::BufferTestManip manip(parser.BufferIn); + fmt::buf::TestAccess access(parser.istream); + fmt::buf::TestManip manip(parser.istream); - manip.SkipOneOf('[').value(); + manip.skip_one_of('[').value(); std::size_t idx = 0; - while (fmt::detail::BufferAccess(parser.BufferIn).IsEndOfString() == false) + while (fmt::buf::Access(parser.istream).is_end_of_string() == false) { manip.IgnoreEveryBlanks(); - if (access.IsEqualTo(']')) break; + if (access.is_equal_to(']')) break; subObjectParsingFunction(t, idx++, parser); manip.GoTo(',', ']'); - manip.SkipOneOf(',').value(); + manip.skip_one_of(',').value(); } - manip.SkipOneOf(']').value(); + manip.skip_one_of(']').value(); } template @@ -264,35 +264,35 @@ namespace stream::JSON }); } - static inline void FormatBegin(detail::JsonFormatter& formatter) { fmt::detail::BufferOutManip(formatter.buffer_out).Pushback('[').value(); } + static inline void FormatBegin(detail::JsonFormatter& formatter) { fmt::buf::ManipIO(formatter.ostream).pushback('[').value(); } static inline void FormatEnd(detail::JsonFormatter& formatter) { formatter.NewLine(); - fmt::detail::BufferOutManip(formatter.buffer_out).Pushback(']').value(); + fmt::buf::ManipIO(formatter.ostream).pushback(']').value(); } template static inline void FormatObject(const SubObject& subObject, const std::size_t idx, detail::JsonFormatter& formatter) { - if (idx != 0) fmt::detail::BufferOutManip(formatter.buffer_out).Pushback(',').value(); + if (idx != 0) fmt::buf::ManipIO(formatter.ostream).pushback(',').value(); - formatter.BeginNewObject(); + formatter.begin_new_object(); formatter.NewLine(); formatter.format(subObject); - formatter.EndNewObject(); + formatter.end_new_object(); } }; struct JsonNullSerializer { - static inline void ParseNull(detail::JsonParser& parser) { fmt::detail::BufferTestManip(parser.BufferIn).is_same_forward("null", 4).value(); } + static inline void ParseNull(detail::JsonParser& parser) { fmt::buf::TestManip(parser.istream).is_same_forward("null", 4).value(); } - static inline void FormatNull(detail::JsonFormatter& formatter) { fmt::detail::BufferWriteManip(formatter.buffer_out).FastWriteCharArray("null", 4).value(); } + static inline void FormatNull(detail::JsonFormatter& formatter) { fmt::buf::WriteManip(formatter.ostream).fast_write_char_array("null", 4).value(); } }; } -namespace stream::JSON::detail +namespace stream::json::detail { template void JsonFormatter::format(const T& t) @@ -307,18 +307,18 @@ namespace stream::JSON::detail } } -namespace stream::JSON +namespace stream::json { template struct FormatAsJson { public: FormatAsJson(const T& value) - : Value(value) + : value(value) {} public: - const T& Value; + const T& value; }; } @@ -327,14 +327,14 @@ namespace stream::fmt { #ifdef STREAMFORMAT_FORMATTER_DECLARED template - struct FormatterType, FormatterExecutor> + struct FormatterType, FormatterExecutor> { - [[nodiscard]] static std::expected format(const JSON::FormatAsJson& json, FormatterExecutor& executor) + [[nodiscard]] static std::expected format(const json::FormatAsJson& json, FormatterExecutor& executor) { - bool ordered_struct = executor.Data.Specifiers.Has("ordered_struct"); - JSON::detail::JsonFormatter::FormatSettings settings{.OrderedStruct = ordered_struct, .FloatPrecision = executor.Data.FloatPrecision}; - JSON::detail::JsonFormatter jsonFormatter(executor.buffer_out, settings); - JSON::JsonSerializer::format(json.Value, jsonFormatter); + bool ordered_struct = executor.data.specifiers.has("ordered_struct"); + json::detail::JsonFormatter::FormatSettings settings{.ordered_struct = ordered_struct, .float_precision = executor.data.float_precision}; + json::detail::JsonFormatter jsonFormatter(executor.ostream, settings); + json::JsonSerializer::format(json.value, jsonFormatter); return {}; } }; @@ -342,15 +342,15 @@ namespace stream::fmt #ifdef STREAMFORMAT_PARSER_DECLARED template - struct ParserType, ParserExecutor> + struct ParserType, ParserExecutor> { [[nodiscard]] static std::expected parse(T& json, ParserExecutor& executor) { - JSON::detail::JsonParser jsonParser(*executor.BufferIn.Manager); - jsonParser.BufferIn.CurrentPos = executor.BufferIn.CurrentPos; + json::detail::JsonParser jsonParser(*executor.istream.Manager); + jsonParser.istream.current_pos = executor.istream.current_pos; // TODO: - // JSON::JsonSerializer::parse(json.Value, jsonParser); - executor.BufferIn.CurrentPos = jsonParser.BufferIn.CurrentPos; + // json::JsonSerializer::parse(json.value, jsonParser); + executor.istream.current_pos = jsonParser.istream.current_pos; return {}; } }; diff --git a/src/stream/json/serializers/base_serializers.h b/src/stream/json/serializers/base_serializers.h index 7706cae9..8f102401 100644 --- a/src/stream/json/serializers/base_serializers.h +++ b/src/stream/json/serializers/base_serializers.h @@ -1,11 +1,11 @@ #pragma once -#include "../JsonObjects.h" -#include "../JsonSerializer.h" +#include "../json_objects.h" +#include "../json_serializer.h" #include -namespace stream::JSON +namespace stream::json { template requires (std::is_integral_v && !std::is_floating_point_v) @@ -31,7 +31,7 @@ namespace stream::JSON static inline void parse(T (&t)[SIZE], detail::JsonParser& parser) { - if constexpr (fmt::detail::IsCharType::Value) + if constexpr (fmt::detail::IsCharType::value) { // TODO } @@ -43,7 +43,7 @@ namespace stream::JSON static inline void format(const T (&t)[SIZE], detail::JsonFormatter& formatter) { - if constexpr (fmt::detail::IsCharType::Value) + if constexpr (fmt::detail::IsCharType::value) { // TODO } diff --git a/src/stream/json/serializers/json_objects_serializer.h b/src/stream/json/serializers/json_objects_serializer.h index c279ded7..d6eea785 100644 --- a/src/stream/json/serializers/json_objects_serializer.h +++ b/src/stream/json/serializers/json_objects_serializer.h @@ -1,32 +1,32 @@ #pragma once -#include "../JsonObjects.h" -#include "../JsonSerializer.h" +#include "../json_objects.h" +#include "../json_serializer.h" -#include "STDSerializers/JSON_unordered_map.h" -#include "STDSerializers/JSON_vector.h" +#include "std_serializers/json_unordered_map.h" +#include "std_serializers/json_vector.h" #include -namespace stream::JSON +namespace stream::json { template <> struct JsonSerializer> { static inline void parse(std::unique_ptr& t, detail::JsonParser& parser) { - fmt::detail::BufferTestManip(parser.BufferIn).IgnoreEveryBlanks(); - if (parser.IsJsonStringBegin()) + fmt::buf::TestManip(parser.istream).IgnoreEveryBlanks(); + if (parser.is_json_string_begin()) t = std::make_unique(); - else if (parser.IsJsonNumberBegin()) + else if (parser.is_json_number_begin()) t = std::make_unique(); - else if (parser.IsJsonBooleanBegin()) + else if (parser.is_json_boolean_begin()) t = std::make_unique(); - else if (parser.IsJsonStructBegin()) + else if (parser.is_json_struct_begin()) t = std::make_unique(); - else if (parser.IsJsonArrayBegin()) + else if (parser.is_json_array_begin()) t = std::make_unique(); - else if (parser.IsJsonNullBegin()) + else if (parser.is_json_null_begin()) t = std::make_unique(); t->ParserExecute(parser); @@ -83,7 +83,7 @@ namespace stream::JSON static inline void parse(JsonStructObject& t, detail::JsonParser& parser) { parser.parse(t.Objects); } static inline void format(const JsonStructObject& t, detail::JsonFormatter& formatter) { - if (formatter.Settings.OrderedStruct == false) + if (formatter.settings.ordered_struct == false) { formatter.format(t.Objects); return; diff --git a/src/stream/json/serializers/serializers.h b/src/stream/json/serializers/serializers.h index 619981f0..1c4e5668 100644 --- a/src/stream/json/serializers/serializers.h +++ b/src/stream/json/serializers/serializers.h @@ -1,5 +1,5 @@ #pragma once -#include "BaseSerializers.h" -#include "JsonObjectsSerializer.h" -#include "STDSerializers/BasicSTDSerializers.h" +#include "base_serializers.h" +#include "json_objects_serializer.h" +#include "std_serializers/basic_std_serializers.h" diff --git a/src/stream/json/serializers/std_serializers/basic_std_serializers.h b/src/stream/json/serializers/std_serializers/basic_std_serializers.h index 43222675..93a7c9d5 100644 --- a/src/stream/json/serializers/std_serializers/basic_std_serializers.h +++ b/src/stream/json/serializers/std_serializers/basic_std_serializers.h @@ -1,10 +1,10 @@ #pragma once -#include "stream/Json/JsonSerializer.h" +#include "stream/json/json_serializer.h" #include -namespace stream::JSON +namespace stream::json { template <> struct JsonSerializer diff --git a/src/stream/json/serializers/std_serializers/json_map.h b/src/stream/json/serializers/std_serializers/json_map.h index 947dcb60..2c13f25c 100644 --- a/src/stream/json/serializers/std_serializers/json_map.h +++ b/src/stream/json/serializers/std_serializers/json_map.h @@ -1,10 +1,10 @@ #pragma once -#include "stream/Json/JsonSerializer.h" +#include "stream/json/json_serializer.h" #include -namespace stream::JSON +namespace stream::json { template struct JsonSerializer> diff --git a/src/stream/json/serializers/std_serializers/json_unordered_map.h b/src/stream/json/serializers/std_serializers/json_unordered_map.h index 9a39d85c..69922eab 100644 --- a/src/stream/json/serializers/std_serializers/json_unordered_map.h +++ b/src/stream/json/serializers/std_serializers/json_unordered_map.h @@ -1,11 +1,11 @@ #pragma once -#include "stream/Json/JsonObjects.h" -#include "stream/Json/JsonSerializer.h" +#include "stream/json/json_objects.h" +#include "stream/json/json_serializer.h" #include -namespace stream::JSON +namespace stream::json { template struct JsonSerializer> diff --git a/src/stream/json/serializers/std_serializers/json_vector.h b/src/stream/json/serializers/std_serializers/json_vector.h index d1159116..710526b3 100644 --- a/src/stream/json/serializers/std_serializers/json_vector.h +++ b/src/stream/json/serializers/std_serializers/json_vector.h @@ -1,11 +1,11 @@ #pragma once -#include "stream/Json/JsonObjects.h" -#include "stream/Json/JsonSerializer.h" +#include "stream/json/json_objects.h" +#include "stream/json/json_serializer.h" #include -namespace stream::JSON +namespace stream::json { template struct JsonSerializer> diff --git a/src/stream/profiler.h b/src/stream/profiler.h index 1f005310..32e2ce5f 100644 --- a/src/stream/profiler.h +++ b/src/stream/profiler.h @@ -1,4 +1,4 @@ #pragma once -#include "ProfilerManager/Profiler.h" -#include "ProfilerManager/ProfilerFactory.h" +#include "profiler/profiler.h" +#include "profiler/profiler_factory.h" diff --git a/src/stream/profiler/all_events.h b/src/stream/profiler/all_events.h index bdb9701d..2a11d59a 100644 --- a/src/stream/profiler/all_events.h +++ b/src/stream/profiler/all_events.h @@ -1,8 +1,8 @@ #pragma once -#include "Event.h" +#include "event.h" -namespace stream::ProfilerManager +namespace stream::profiler { class DurationEvent : public Event { @@ -18,8 +18,8 @@ namespace stream::ProfilerManager ~DurationEvent() override = default; public: - void Start() { Trigger(); } - void Stop() { Info.Duration = ProfilerManager::GetMicroseconds() - Info.TimeOfEvent; } + void start() { trigger(); } + void Stop() { info.Duration = profiler::get_microseconds() - info.TimeOfEvent; } }; class SampleEvent : public Event diff --git a/src/stream/profiler/detail.h b/src/stream/profiler/detail.h index 12352320..5ab5d3cc 100644 --- a/src/stream/profiler/detail.h +++ b/src/stream/profiler/detail.h @@ -2,9 +2,9 @@ #include -namespace stream::ProfilerManager +namespace stream::profiler { - inline double GetMicroseconds() + inline double get_microseconds() { return (double)std::chrono::time_point_cast(std::chrono::high_resolution_clock::now()).time_since_epoch().count() / 1000; } diff --git a/src/stream/profiler/event.h b/src/stream/profiler/event.h index 7a3c0a3e..5564399b 100644 --- a/src/stream/profiler/event.h +++ b/src/stream/profiler/event.h @@ -1,7 +1,7 @@ #pragma once #include "detail.h" -#include "EventData.h" +#include "event_data.h" #include "stream/core/prelude.h" #include "stream/fmt.h" @@ -11,7 +11,7 @@ // https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview -namespace stream::ProfilerManager +namespace stream::profiler { int GetPid(); @@ -19,7 +19,7 @@ namespace stream::ProfilerManager { Unknow = '.', - DurationBegin = 'B', + DurationBegin = 'b', DurationEnd = 'E', AsyncStart = 'b', @@ -30,8 +30,8 @@ namespace stream::ProfilerManager FlowStep = 't', FlowEnd = 'f', - ObjectCreated = 'N', - ObjectSnapshot = 'O', + Objectcreated = 'N', + Objectsnapshot = 'O', ObjectDestroyed = 'D', MemoryDumpGlobal = 'V', @@ -42,7 +42,7 @@ namespace stream::ProfilerManager Counter = 'C', Sample = 'P', MetaData = 'M', - Mark = 'R', + Mark = 'r', ClockSyncEvents = 'c', Context = ',' // '(' ')' }; @@ -51,54 +51,54 @@ namespace stream::ProfilerManager { public: EventInfo() - : Name("Unknow") + : name("Unknow") , Category("Unknow") - , Type(EventType::Unknow) + , type(EventType::Unknow) , Id(0) - , TimeOfEvent(ProfilerManager::GetMicroseconds()) + , TimeOfEvent(profiler::get_microseconds()) , ThreadTimeOfEvent(0) , Duration(0) , PID(GetPid()) , TID(std::hash{}(std::this_thread::get_id())) - , Data(nullptr) + , data(nullptr) {} EventInfo(const std::string& name, const std::string& category, EventType type, EventData* data = nullptr) - : Name(name) + : name(name) , Category(category) - , Type(type) + , type(type) , Id(0) - , TimeOfEvent(ProfilerManager::GetMicroseconds()) + , TimeOfEvent(profiler::get_microseconds()) , ThreadTimeOfEvent(0) , Duration(0) , PID(GetPid()) , TID(std::hash{}(std::this_thread::get_id())) - , Data(data) + , data(data) {} EventInfo(std::string&& name, std::string&& category, EventType type, EventData* data = nullptr) - : Name(std::move(name)) + : name(std::move(name)) , Category(std::move(category)) - , Type(type) + , type(type) , Id(0) - , TimeOfEvent(ProfilerManager::GetMicroseconds()) + , TimeOfEvent(profiler::get_microseconds()) , ThreadTimeOfEvent(0) , Duration(0) , PID(GetPid()) , TID(std::hash{}(std::this_thread::get_id())) - , Data(data) + , data(data) {} public: - std::string Name; + std::string name; std::string Category; - EventType Type; + EventType type; std::size_t Id; double TimeOfEvent, ThreadTimeOfEvent; double Duration; int PID; std::size_t TID; - std::shared_ptr Data; + std::shared_ptr data; }; struct Event @@ -117,19 +117,19 @@ namespace stream::ProfilerManager virtual ~Event() = default; public: - void Trigger() { Info.TimeOfEvent = ProfilerManager::GetMicroseconds(); } + void trigger() { info.TimeOfEvent = profiler::get_microseconds(); } public: - EventInfo Info; + EventInfo info; }; } namespace stream::fmt { template - struct FormatterType + struct FormatterType { - [[nodiscard]] static std::expected format(const stream::ProfilerManager::EventType& t, FormatterExecutor& executor) - { return executor.buffer_out.Pushback(static_cast(t)); } + [[nodiscard]] static std::expected format(const stream::profiler::EventType& t, FormatterExecutor& executor) + { return executor.ostream.pushback(static_cast(t)); } }; } diff --git a/src/stream/profiler/event_data.h b/src/stream/profiler/event_data.h index 7f91642f..9c4df2ae 100644 --- a/src/stream/profiler/event_data.h +++ b/src/stream/profiler/event_data.h @@ -1,8 +1,8 @@ #pragma once -#include "stream/Json.h" +#include "stream/json.h" -namespace stream::ProfilerManager +namespace stream::profiler { class EventData { @@ -10,8 +10,8 @@ namespace stream::ProfilerManager virtual ~EventData() = default; public: - virtual void ToJson(JSON::detail::JsonFormatter& formatter) const = 0; - virtual void FromJson(JSON::detail::JsonParser& parser) = 0; + virtual void ToJson(json::detail::JsonFormatter& formatter) const = 0; + virtual void FromJson(json::detail::JsonParser& parser) = 0; }; class EventDataJsonObject final : public EventData @@ -20,8 +20,8 @@ namespace stream::ProfilerManager ~EventDataJsonObject() override = default; public: - void ToJson(JSON::detail::JsonFormatter& formatter) const override { JSON::JsonSerializer::format(Data, formatter); } - void FromJson(JSON::detail::JsonParser& parser) override { JSON::JsonSerializer::parse(Data, parser); } - JSON::JsonStructObject Data; + void ToJson(json::detail::JsonFormatter& formatter) const override { json::JsonSerializer::format(data, formatter); } + void FromJson(json::detail::JsonParser& parser) override { json::JsonSerializer::parse(data, parser); } + json::JsonStructObject data; }; } diff --git a/src/stream/profiler/get_pid.cpp b/src/stream/profiler/get_pid.cpp index 2732b4f9..eefd61ff 100644 --- a/src/stream/profiler/get_pid.cpp +++ b/src/stream/profiler/get_pid.cpp @@ -9,7 +9,7 @@ #include #endif -namespace stream::ProfilerManager +namespace stream::profiler { int GetPid() { diff --git a/src/stream/profiler/profiler.h b/src/stream/profiler/profiler.h index d27ae38b..adfa5dba 100644 --- a/src/stream/profiler/profiler.h +++ b/src/stream/profiler/profiler.h @@ -3,43 +3,43 @@ #include "stream/core/prelude.h" #include "stream/flog.h" -#include "AllEvents.h" -#include "Event.h" -#include "ProfilerEventCreator.h" +#include "all_events.h" +#include "event.h" +#include "profiler_event_creator.h" -namespace stream::ProfilerManager +namespace stream::profiler { class Profiler { public: explicit Profiler(std::string&& name) - : Name(name) - , Logger(name) - , ProfilerDuration(name) + : name(name) + , logger(name) + , profiler_duration(name) { - Events.clear(); - Events.push_back(EventInfo{}); - ProfilerDuration.Start(); + events.clear(); + events.push_back(EventInfo{}); + profiler_duration.start(); } ~Profiler() {} public: - void AddEvent(const Event& event) { AddEventInfo(event.Info); } - void AddEventInfo(const EventInfo& eventInfo) { Events.push_back(eventInfo); } - inline stream::flog::BasicLogger& GetLogger() { return Logger; } + void add_event(const Event& event) { add_event_info(event.info); } + void add_event_info(const EventInfo& eventInfo) { events.push_back(eventInfo); } + inline stream::flog::BasicLogger& get_logger() { return logger; } public: - static Profiler& GetInstance() + static Profiler& get_instance() { - static Profiler profiler("Profiler"); + static Profiler profiler("profiler"); return profiler; } public: - std::string Name; - flog::BasicLogger Logger; - DurationEvent ProfilerDuration; - std::vector Events; + std::string name; + flog::BasicLogger logger; + DurationEvent profiler_duration; + std::vector events; }; } diff --git a/src/stream/profiler/profiler_event_creator.cpp b/src/stream/profiler/profiler_event_creator.cpp index c6715ece..6db6c6b4 100644 --- a/src/stream/profiler/profiler_event_creator.cpp +++ b/src/stream/profiler/profiler_event_creator.cpp @@ -1,62 +1,62 @@ -#include "ProfilerEventCreator.h" -#include "Profiler.h" +#include "profiler_event_creator.h" +#include "profiler.h" -namespace stream::ProfilerManager +namespace stream::profiler { ScopeProfile::~ScopeProfile() { Stop(); - double millis = Info.Duration / 1000; + double millis = info.Duration / 1000; double sec = millis / 1000; if (sec > 1.5) - m_Profiler.GetLogger().trace("{} : {} seconds", Info.Name, sec); + profiler_.get_logger().trace("{} : {} seconds", info.name, sec); else if (millis > 5.0) - m_Profiler.GetLogger().trace("{} : {} ms", Info.Name, millis); + profiler_.get_logger().trace("{} : {} ms", info.name, millis); else - m_Profiler.GetLogger().trace("{} : {} us", Info.Name, Info.Duration); + profiler_.get_logger().trace("{} : {} us", info.name, info.Duration); - m_Profiler.AddEvent(*this); + profiler_.add_event(*this); } ObjectTracker::ObjectTracker(Profiler& profiler, const std::string& name, const std::string& category) - : m_Profiler(profiler) - , m_Name(name) - , m_Category(category) + : profiler_(profiler) + , name_(name) + , category_(category) { - Event created(m_Name, m_Category, EventType::ObjectCreated); - m_Profiler.AddEvent(created); + Event created(name_, category_, EventType::Objectcreated); + profiler_.add_event(created); } ObjectTracker::ObjectTracker(Profiler& profiler, std::string&& name, std::string&& category) - : m_Profiler(profiler) - , m_Name(std::move(name)) - , m_Category(std::move(category)) + : profiler_(profiler) + , name_(std::move(name)) + , category_(std::move(category)) { - Event created(m_Name, m_Category, EventType::ObjectCreated); - created.Info.Id = 10; - m_Profiler.AddEvent(created); + Event created(name_, category_, EventType::Objectcreated); + created.info.Id = 10; + profiler_.add_event(created); } ObjectTracker::~ObjectTracker() { - Event destroyed(m_Name, m_Category, EventType::ObjectDestroyed); - destroyed.Info.Id = 10; - m_Profiler.AddEvent(destroyed); + Event destroyed(name_, category_, EventType::ObjectDestroyed); + destroyed.info.Id = 10; + profiler_.add_event(destroyed); } - void ObjectTracker::Snapshot() + void ObjectTracker::snapshot() { - Event snapshot(m_Name, m_Category, EventType::ObjectSnapshot); - snapshot.Info.Id = 10; - m_Profiler.AddEvent(snapshot); + Event snapshot(name_, category_, EventType::Objectsnapshot); + snapshot.info.Id = 10; + profiler_.add_event(snapshot); } - void EventCounter::Snapshot() + void EventCounter::snapshot() { - m_Idx++; - Event snapshot(m_Name, m_Category, EventType::Counter); - m_Profiler.AddEvent(snapshot); + idx_++; + Event snapshot(name_, category_, EventType::Counter); + profiler_.add_event(snapshot); } } diff --git a/src/stream/profiler/profiler_event_creator.h b/src/stream/profiler/profiler_event_creator.h index 93377bbd..88d2575c 100644 --- a/src/stream/profiler/profiler_event_creator.h +++ b/src/stream/profiler/profiler_event_creator.h @@ -1,8 +1,8 @@ #pragma once -#include "AllEvents.h" +#include "all_events.h" -namespace stream::ProfilerManager +namespace stream::profiler { class Profiler; @@ -11,22 +11,22 @@ namespace stream::ProfilerManager public: ScopeProfile(Profiler& profiler, const std::string& name, const std::string& category = "ScopeProfiler") : DurationEvent(name, category) - , m_Profiler(profiler) + , profiler_(profiler) { - Start(); + start(); } ScopeProfile(Profiler& profiler, std::string&& name, std::string&& category = "ScopeProfiler") : DurationEvent(std::move(name), std::move(category)) - , m_Profiler(profiler) + , profiler_(profiler) { - Start(); + start(); } ~ScopeProfile() override; private: - Profiler& m_Profiler; + Profiler& profiler_; }; class ObjectTracker @@ -37,38 +37,38 @@ namespace stream::ProfilerManager virtual ~ObjectTracker(); public: - void Snapshot(); + void snapshot(); private: - Profiler& m_Profiler; - std::string m_Name; - std::string m_Category; + Profiler& profiler_; + std::string name_; + std::string category_; }; class EventCounter { public: EventCounter(Profiler& profiler, const std::string& name, const std::string& category = "EventCounter") - : m_Profiler(profiler) - , m_Name(name) - , m_Category(category) - , m_Idx(0) + : profiler_(profiler) + , name_(name) + , category_(category) + , idx_(0) {} EventCounter(Profiler& profiler, std::string&& name, std::string&& category = "EventCounter") - : m_Profiler(profiler) - , m_Name(std::move(name)) - , m_Category(std::move(category)) - , m_Idx(0) + : profiler_(profiler) + , name_(std::move(name)) + , category_(std::move(category)) + , idx_(0) {} public: - void Snapshot(); + void snapshot(); private: - Profiler& m_Profiler; - std::string m_Name; - std::string m_Category; - std::uint64_t m_Idx; + Profiler& profiler_; + std::string name_; + std::string category_; + std::uint64_t idx_; }; } diff --git a/src/stream/profiler/profiler_factory.cpp b/src/stream/profiler/profiler_factory.cpp index c06ce71a..4ecbb5cb 100644 --- a/src/stream/profiler/profiler_factory.cpp +++ b/src/stream/profiler/profiler_factory.cpp @@ -1,20 +1,20 @@ -#include "ProfilerFactory.h" -#include "ProfilerJsonSerializers.h" +#include "profiler_factory.h" +#include "profiler_json_serializers.h" #include -namespace stream::ProfilerManager +namespace stream::profiler { void ProfilerFactory::ToJson(Profiler& profiler, std::filesystem::path path) { - profiler.ProfilerDuration.Stop(); - profiler.Events[0] = profiler.ProfilerDuration.Info; + profiler.profiler_duration.Stop(); + profiler.events[0] = profiler.profiler_duration.info; - if (path == "") path = std::string(profiler.Name) + ".json"; + if (path == "") path = std::string(profiler.name) + ".json"; std::ofstream file(path.string(), std::ios::out); - JSON::FormatAsJson formatProfiler(profiler); - fmt::FilePrint(file, formatProfiler).value(); + json::FormatAsJson format_profiler(profiler); + fmt::file_print(file, format_profiler).value(); file.close(); } } diff --git a/src/stream/profiler/profiler_factory.h b/src/stream/profiler/profiler_factory.h index 842fb2c6..1b3b4bdb 100644 --- a/src/stream/profiler/profiler_factory.h +++ b/src/stream/profiler/profiler_factory.h @@ -1,10 +1,10 @@ #pragma once -#include "Profiler.h" +#include "profiler.h" #include -namespace stream::ProfilerManager +namespace stream::profiler { class ProfilerFactory { diff --git a/src/stream/profiler/profiler_json_serializers.h b/src/stream/profiler/profiler_json_serializers.h index 1a30c5e1..cef4c6fb 100644 --- a/src/stream/profiler/profiler_json_serializers.h +++ b/src/stream/profiler/profiler_json_serializers.h @@ -1,83 +1,83 @@ #pragma once -#include "ProfilerFactory.h" -#include "stream/Json.h" +#include "profiler_factory.h" +#include "stream/json.h" -namespace stream::JSON +namespace stream::json { template <> - struct JsonSerializer + struct JsonSerializer { - static inline void format(const ProfilerManager::Profiler& t, detail::JsonFormatter& formatter) + static inline void format(const profiler::Profiler& t, detail::JsonFormatter& formatter) { - auto intermediate = formatter.GetStructIntermediate(); + auto intermediate = formatter.get_struct_intermediate(); intermediate.format("displayTimeUnit", "us"); - intermediate.format("traceEvents", t.Events); + intermediate.format("traceEvents", t.events); } - static inline void parse(ProfilerManager::Profiler& t, detail::JsonParser& parser) + static inline void parse(profiler::Profiler& t, detail::JsonParser& parser) { - auto intermediate = parser.GetStructIntermediate(); - intermediate.parse("traceEvents", t.Events); + auto intermediate = parser.get_struct_intermediate(); + intermediate.parse("traceEvents", t.events); } }; template <> - struct JsonSerializer + struct JsonSerializer { - static inline void format(const ProfilerManager::EventType& t, detail::JsonFormatter& formatter) { formatter.format(static_cast(t)); } + static inline void format(const profiler::EventType& t, detail::JsonFormatter& formatter) { formatter.format(static_cast(t)); } - static inline void parse(ProfilerManager::EventType& t, detail::JsonParser& parser) { parser.parse(reinterpret_cast(t)); } + static inline void parse(profiler::EventType& t, detail::JsonParser& parser) { parser.parse(reinterpret_cast(t)); } }; template <> - struct JsonSerializer + struct JsonSerializer { - static inline void format(const ProfilerManager::EventData& t, detail::JsonFormatter& formatter) { t.ToJson(formatter); } + static inline void format(const profiler::EventData& t, detail::JsonFormatter& formatter) { t.ToJson(formatter); } - static inline void parse(ProfilerManager::EventData& t, detail::JsonParser& parser) { t.FromJson(parser); } + static inline void parse(profiler::EventData& t, detail::JsonParser& parser) { t.FromJson(parser); } }; template <> - struct JsonSerializer + struct JsonSerializer { - static inline void format(const ProfilerManager::EventInfo& t, detail::JsonFormatter& formatter) + static inline void format(const profiler::EventInfo& t, detail::JsonFormatter& formatter) { - auto intermediate = formatter.GetStructIntermediate(); - intermediate.format("name", t.Name); + auto intermediate = formatter.get_struct_intermediate(); + intermediate.format("name", t.name); intermediate.format("cat", t.Category); - intermediate.format("ph", t.Type); + intermediate.format("ph", t.type); intermediate.format("pid", t.PID); intermediate.format("tid", t.TID); intermediate.format("ts", t.TimeOfEvent); intermediate.format("dur", t.Duration); intermediate.format("id", t.Id); - if (t.Data != nullptr) intermediate.format("args", *t.Data); + if (t.data != nullptr) intermediate.format("args", *t.data); } - static inline void parse(ProfilerManager::EventInfo& t, detail::JsonParser& parser) + static inline void parse(profiler::EventInfo& t, detail::JsonParser& parser) { - auto intermediate = parser.GetStructIntermediate(); - intermediate.parse("name", t.Name); + auto intermediate = parser.get_struct_intermediate(); + intermediate.parse("name", t.name); intermediate.parse("cat", t.Category); - intermediate.parse("ph", t.Type); + intermediate.parse("ph", t.type); intermediate.parse("pid", t.PID); intermediate.parse("tid", t.TID); intermediate.parse("ts", t.TimeOfEvent); intermediate.parse("dur", t.Duration); intermediate.parse("id", t.Id); - intermediate.parse("args", *t.Data); + intermediate.parse("args", *t.data); } }; template <> - struct JsonSerializer + struct JsonSerializer { - static inline void format(const ProfilerManager::Event& t, detail::JsonFormatter& formatter) + static inline void format(const profiler::Event& t, detail::JsonFormatter& formatter) { - return JsonSerializer::format(t.Info, formatter); + return JsonSerializer::format(t.info, formatter); } - static inline void parse(ProfilerManager::Event& t, detail::JsonParser& parser) { return JsonSerializer::parse(t.Info, parser); } + static inline void parse(profiler::Event& t, detail::JsonParser& parser) { return JsonSerializer::parse(t.info, parser); } }; } diff --git a/src/stream/profiler/profiler_macros.h b/src/stream/profiler/profiler_macros.h index 943a508e..7d98c7cf 100644 --- a/src/stream/profiler/profiler_macros.h +++ b/src/stream/profiler/profiler_macros.h @@ -2,11 +2,11 @@ #ifdef STREAMFORMAT_PROFILING_ENABLE -#define SFP_PROFILE_FUNCTION() stream::ProfilerManager::ScopeProfile profile##__LINE__(stream::ProfilerManager::Profiler::GetInstance(), __FUNCSIG__, "Function") +#define SFP_PROFILE_FUNCTION() stream::profiler::ScopeProfile profile##__LINE__(stream::profiler::Profiler::get_instance(), __FUNCSIG__, "Function") #define SFP_PROFILE_FUNCTION_FMT(...) \ - stream::ProfilerManager::ScopeProfile profile##__LINE__(stream::ProfilerManager::Profiler::GetInstance(), \ - stream::ProfilerManager::fmt::FormatString(__VA_ARGS__), "Function") -#define SFP_SAVE_DEFAULT_PROFILER() stream::ProfilerManager::ProfilerFactory::ToJson(stream::ProfilerManager::Profiler::GetInstance()) + stream::profiler::ScopeProfile profile##__LINE__(stream::profiler::Profiler::get_instance(), \ + stream::profiler::fmt::format_string(__VA_ARGS__), "Function") +#define SFP_SAVE_DEFAULT_PROFILER() stream::profiler::ProfilerFactory::ToJson(stream::profiler::Profiler::get_instance()) #else // STREAMFORMAT_PROFILING_ENABLE diff --git a/src/stream/tester/copy_move_check.h b/src/stream/tester/copy_move_check.h index 7e9c4a51..1507e046 100644 --- a/src/stream/tester/copy_move_check.h +++ b/src/stream/tester/copy_move_check.h @@ -2,83 +2,83 @@ #include "stream/flog.h" -namespace stream::Tester +namespace stream::tester { class CopyMoveCheck { public: - static inline flog::BasicLogger Logger; + static inline flog::BasicLogger logger; public: CopyMoveCheck(const std::string& name) - : m_Name(name) + : name_(name) { - Logger.info("CopyMoveCheck {} : {:C:red} ( {:C:red} )", m_Name, "Default (copy string) Constructor", "TestCopy(const std::string& name)"); + logger.info("CopyMoveCheck {} : {:C:red} ( {:C:red} )", name_, "Default (copy string) Constructor", "TestCopy(const std::string& name)"); } CopyMoveCheck(std::string&& name) - : m_Name(std::move(name)) + : name_(std::move(name)) { - Logger.info("CopyMoveCheck {} : {:C:red} ( {:C:red} )", m_Name, "Default (move string) Constructor", "TestCopy(std::string&& name)"); + logger.info("CopyMoveCheck {} : {:C:red} ( {:C:red} )", name_, "Default (move string) Constructor", "TestCopy(std::string&& name)"); } CopyMoveCheck(CopyMoveCheck& other) - : m_Name("Copy of " + other.m_Name) + : name_("Copy of " + other.name_) { - Logger.info("CopyMoveCheck {} : {:C:red} ( {:C:red} )", m_Name, "Copy Constructor", "TestCopy(TestCopy&)"); + logger.info("CopyMoveCheck {} : {:C:red} ( {:C:red} )", name_, "Copy Constructor", "TestCopy(TestCopy&)"); } CopyMoveCheck(const CopyMoveCheck& other) - : m_Name("Copy of " + other.m_Name) + : name_("Copy of " + other.name_) { - Logger.info("CopyMoveCheck {} : {:C:red} ( {:C:red} )", m_Name, "Const Copy Constructor", "TestCopy(const TestCopy&)"); + logger.info("CopyMoveCheck {} : {:C:red} ( {:C:red} )", name_, "Const Copy Constructor", "TestCopy(const TestCopy&)"); } CopyMoveCheck(CopyMoveCheck&& other) noexcept - : m_Name("Move of " + other.m_Name) + : name_("Move of " + other.name_) { - Logger.info("CopyMoveCheck {} : {:C:red} ( {:C:red} )", m_Name, "Move Constructor", "TestCopy(TestCopy&&)"); + logger.info("CopyMoveCheck {} : {:C:red} ( {:C:red} )", name_, "Move Constructor", "TestCopy(TestCopy&&)"); } CopyMoveCheck(const CopyMoveCheck&& other) noexcept - : m_Name("Move of " + other.m_Name) + : name_("Move of " + other.name_) { - Logger.info("CopyMoveCheck {} : {:C:red} ( {:C:red} )", m_Name, "Const Move Constructor", "TestCopy(const TestCopy&&)"); + logger.info("CopyMoveCheck {} : {:C:red} ( {:C:red} )", name_, "Const Move Constructor", "TestCopy(const TestCopy&&)"); } CopyMoveCheck& operator=(CopyMoveCheck& other) { - m_Name = "Copy Of " + other.m_Name; + name_ = "Copy Of " + other.name_; - Logger.info("CopyMoveCheck {} : {:C:red} ( {:C:red} )", m_Name, "Copy Assignment", "TestCopy& operator=(TestCopy&)"); + logger.info("CopyMoveCheck {} : {:C:red} ( {:C:red} )", name_, "Copy Assignment", "TestCopy& operator=(TestCopy&)"); return *this; } CopyMoveCheck& operator=(const CopyMoveCheck& other) { - m_Name = "Copy Of " + other.m_Name; + name_ = "Copy Of " + other.name_; - Logger.info("CopyMoveCheck {} : {:C:red} ( {:C:red} )", m_Name, "Const Copy Assignment", "TestCopy& operator=(const TestCopy&)"); + logger.info("CopyMoveCheck {} : {:C:red} ( {:C:red} )", name_, "Const Copy Assignment", "TestCopy& operator=(const TestCopy&)"); return *this; } CopyMoveCheck& operator=(CopyMoveCheck&& other) noexcept { - m_Name = "Move Of " + other.m_Name; + name_ = "Move Of " + other.name_; - Logger.info("CopyMoveCheck {} : {:C:red} ( {:C:red} )", m_Name, "Move Assignment", "TestCopy& operator=(TestCopy&&)"); + logger.info("CopyMoveCheck {} : {:C:red} ( {:C:red} )", name_, "Move Assignment", "TestCopy& operator=(TestCopy&&)"); return *this; } CopyMoveCheck& operator=(const CopyMoveCheck&& other) noexcept { - m_Name = "Move Of " + other.m_Name; + name_ = "Move Of " + other.name_; - Logger.info("CopyMoveCheck {} : {:C:red} ( {:C:red} )", m_Name, "Const Move Assignment", "TestCopy& operator=(const TestCopy&&)"); + logger.info("CopyMoveCheck {} : {:C:red} ( {:C:red} )", name_, "Const Move Assignment", "TestCopy& operator=(const TestCopy&&)"); return *this; } private: - std::string m_Name; + std::string name_; }; } diff --git a/src/stream/tester/test_suite/all_test_suite.h b/src/stream/tester/test_suite/all_test_suite.h index a2fa9582..f3e01254 100644 --- a/src/stream/tester/test_suite/all_test_suite.h +++ b/src/stream/tester/test_suite/all_test_suite.h @@ -1,2 +1,2 @@ -#include "BasicTest.h" -#include "TestSuite.h" +#include "basic_test.h" +#include "test_suite.h" diff --git a/src/stream/tester/test_suite/basic_test.h b/src/stream/tester/test_suite/basic_test.h index 93d6e8b1..d7b54382 100644 --- a/src/stream/tester/test_suite/basic_test.h +++ b/src/stream/tester/test_suite/basic_test.h @@ -1,10 +1,10 @@ #pragma once -#include "TestSuite.h" +#include "test_suite.h" #include "stream/core/prelude.h" -namespace stream::Tester::detail +namespace stream::tester::detail { struct TestFunction : public Test { @@ -16,7 +16,7 @@ namespace stream::Tester::detail : Test(std::move(name), link, location) , Func(func) { - Link.Tests.insert({Name, this}); + Link.tests.insert({name, this}); } ~TestFunction() override = default; @@ -55,29 +55,29 @@ namespace stream::Tester::detail T expected_as_T = static_cast(expected); if (result != expected_as_T) { - Link.TestLogger.error("{C:red}{} return {} instead of {}", testView, result, expected, FORMAT_SV("test_name", Name)).value(); + Link.test_logger.error("{C:red}{} return {} instead of {}", testView, result, expected, FORMAT_SV("test_name", name)).value(); throw TestFailure{}; } - Link.TestLogger.trace("{C:green}{} return {}", testView, result, FORMAT_SV("test_name", Name)).value(); + Link.test_logger.trace("{C:green}{} return {}", testView, result, FORMAT_SV("test_name", name)).value(); } template void TestFunction::TestNotEq(T result, std::convertible_to auto notExpected, std::string_view testView, [[maybe_unused]] int line) { if (result == static_cast(notExpected)) { - Link.TestLogger.error("{C:red}{} return {} but that result was prohibited", testView, result, FORMAT_SV("test_name", Name)).value(); + Link.test_logger.error("{C:red}{} return {} but that result was prohibited", testView, result, FORMAT_SV("test_name", name)).value(); throw TestFailure{}; } - Link.TestLogger.trace("{C:green}{} return {}", testView, result, FORMAT_SV("test_name", Name)).value(); + Link.test_logger.trace("{C:green}{} return {}", testView, result, FORMAT_SV("test_name", name)).value(); } inline void TestFunction::TestAssert(bool assert, std::string_view assertView, [[maybe_unused]] int line) { if (assert == false) { - Link.TestLogger.error("{C:red}ASSERT FAILED : {}", assertView, FORMAT_SV("test_name", Name)).value(); + Link.test_logger.error("{C:red}ASSERT FAILED : {}", assertView, FORMAT_SV("test_name", name)).value(); throw TestFailure{}; } - Link.TestLogger.trace("{C:green}ASSERT SUCCED : {}", assertView, FORMAT_SV("test_name", Name)).value(); + Link.test_logger.trace("{C:green}ASSERT SUCCED : {}", assertView, FORMAT_SV("test_name", name)).value(); } @@ -104,7 +104,7 @@ namespace stream::Tester::detail { if (result.has_value() == false) { - Link.TestLogger.error("{C:red}{} return an error: {}", testView, result.error(), FORMAT_SV("test_name", Name)).value(); + Link.test_logger.error("{C:red}{} return an error: {}", testView, result.error(), FORMAT_SV("test_name", name)).value(); throw TestFailure{}; } } @@ -113,22 +113,22 @@ namespace stream::Tester::detail { if (result.has_value() == false) { - Link.TestLogger.error("{C:red}{} didn't return any value", testView, FORMAT_SV("test_name", Name)).value(); + Link.test_logger.error("{C:red}{} didn't return any value", testView, FORMAT_SV("test_name", name)).value(); throw TestFailure{}; } } } #define STREAMFORMAT_TESTINTERNAL_FUNC_DECLARE_EXEC(TestSuiteName, TestName) \ - void STREAMFORMAT_TESTINTERNAL_FUNC_EXEC_NAME(TestSuiteName, TestName)(stream::Tester::detail::TestFunction & link); + void STREAMFORMAT_TESTINTERNAL_FUNC_EXEC_NAME(TestSuiteName, TestName)(stream::tester::detail::TestFunction & link); #define STREAMFORMAT_TESTINTERNAL_FUNC_CREATE(TestSuiteName, TestName, ...) \ - volatile stream::Tester::detail::TestFunction STREAMFORMAT_TESTINTERNAL_FUNC_NAME(TestSuiteName, TestName)( \ + volatile stream::tester::detail::TestFunction STREAMFORMAT_TESTINTERNAL_FUNC_NAME(TestSuiteName, TestName)( \ #TestName, STREAMFORMAT_TESTINTERNAL_SUITE_NAME(TestSuiteName), STREAMFORMAT_TESTINTERNAL_FUNC_EXEC_NAME(TestSuiteName, TestName), STREAMFORMAT_FMT_FILE_LOCATION()) #define SFT_TEST_FUNC(TestSuiteName, TestName) \ STREAMFORMAT_TESTINTERNAL_FUNC_DECLARE_EXEC(TestSuiteName, TestName) \ STREAMFORMAT_TESTINTERNAL_FUNC_CREATE(TestSuiteName, TestName); \ - void STREAMFORMAT_TESTINTERNAL_FUNC_EXEC_NAME(TestSuiteName, TestName)(stream::Tester::detail::TestFunction & link) + void STREAMFORMAT_TESTINTERNAL_FUNC_EXEC_NAME(TestSuiteName, TestName)(stream::tester::detail::TestFunction & link) #define SFT_ASSERT(Test) link.TestAssert(Test, #Test, __LINE__) #define SFT_EQ(Test, Expected) link.TestEq(Test, Expected, #Test, __LINE__) diff --git a/src/stream/tester/test_suite/test_suite.cpp b/src/stream/tester/test_suite/test_suite.cpp index d14f0fac..202364fd 100644 --- a/src/stream/tester/test_suite/test_suite.cpp +++ b/src/stream/tester/test_suite/test_suite.cpp @@ -1,15 +1,15 @@ -#include "TestSuite.h" +#include "test_suite.h" -#include "stream/ProfilerManager.h" +#include "stream/profiler.h" -namespace stream::Tester +namespace stream::tester { - bool TestSuitesManager::ExecAllTestSuites() + bool TestSuitesManager::exec_all_test_suites() { detail::TestStatusBank status; - for (auto& [name, testSuite] : TestSuites) - status.Add(testSuite->ExecAllTests()); + for (auto& [name, test_suite] : test_suites) + status.Add(test_suite->exec_all_tests()); flog::BasicLogger logger("TestSuite"); if (status.IsAllOk()) @@ -21,135 +21,134 @@ namespace stream::Tester } } -namespace stream::Tester::detail +namespace stream::tester::detail { - TestStatusBank TestSuite::ExecAllTests() + TestStatusBank TestSuite::exec_all_tests() { - if (Parent == nullptr) Profiler = new ProfilerManager::Profiler("TestSuite_" + Name); - InitLogger(); - - ProfilerManager::Profiler& profiler = GetProfiler(); - Logger.info("{C:+black}{}", "BEGIN"); - ProfilerManager::DurationEvent testSuiteDuration(GetFullName(), "Profile"); - testSuiteDuration.Start(); - bool firstTestSuite = true; - TestStatusBank testSuiteStatus; - ProfilerManager::DurationEvent testsDuration("Tests", "Profile"); - testsDuration.Start(); - for (auto& [name, test] : Tests) + if (parent == nullptr) profiler = new profiler::Profiler("TestSuite_" + name); + init_logger(); + + logger.info("{C:+black}{}", "BEGIN"); + profiler::DurationEvent test_suite_duration(get_full_name(), "Profile"); + test_suite_duration.start(); + bool first_test_suite = true; + TestStatusBank test_suite_status; + profiler::DurationEvent tests_duration("tests", "Profile"); + tests_duration.start(); + for (auto& [name, test] : tests) { - firstTestSuite = false; - ProfilerManager::DurationEvent currentTestDuration(test->Name, "Profile"); + first_test_suite = false; + profiler::DurationEvent currentTestDuration(test->name, "Profile"); TestStatus testStatus = TestStatus::Fail; - currentTestDuration.Start(); + currentTestDuration.start(); if (TestSuitesManager::PerformanceTest.Enable == false) - testStatus = test->Run(); + testStatus = test->run(); else { for (std::uint32_t i = 0; i < TestSuitesManager::PerformanceTest.NbSamples; ++i) { - testStatus = test->Run(); + testStatus = test->run(); if (testStatus != TestStatus::Ok) break; } } currentTestDuration.Stop(); if (testStatus != TestStatus::Ok) {} - testSuiteStatus.AddTestStatus(testStatus); - Logger.debug("{} -> {}", testStatus, name); - profiler.AddEvent(currentTestDuration); + test_suite_status.AddTestStatus(testStatus); + logger.debug("{} -> {}", testStatus, name); + profiler->add_event(currentTestDuration); } - testsDuration.Stop(); + tests_duration.Stop(); - ProfilerManager::DurationEvent groupsDuration("Groups", "Profile"); - groupsDuration.Start(); - for (auto& [name, testSuite] : TestSuitesLinked) + profiler::DurationEvent groupsDuration("Groups", "Profile"); + groupsDuration.start(); + for (auto& [name, test_suite] : test_suites_linked) { - if (firstTestSuite) - firstTestSuite = false; + if (first_test_suite) + first_test_suite = false; else std::cout << std::endl; - testSuiteStatus.Add(testSuite->ExecAllTests()); + test_suite_status.Add(test_suite->exec_all_tests()); } groupsDuration.Stop(); - testSuiteDuration.Stop(); - profiler.AddEvent(testsDuration); - profiler.AddEvent(groupsDuration); - profiler.AddEvent(testSuiteDuration); + test_suite_duration.Stop(); + profiler->add_event(tests_duration); + profiler->add_event(groupsDuration); + profiler->add_event(test_suite_duration); - if (testSuiteStatus.IsAllOk()) - Logger.info("{C:+black}{}", testSuiteStatus); + if (test_suite_status.IsAllOk()) + logger.info("{C:+black}{}", test_suite_status); else - Logger.error("{C:+black}{}", testSuiteStatus); + logger.error("{C:+black}{}", test_suite_status); - if (Parent == nullptr) + if (parent == nullptr) { - ProfilerManager::ProfilerFactory::ToJson(*Profiler); - delete Profiler; + profiler::ProfilerFactory::ToJson(*profiler); + delete profiler; } - return testSuiteStatus; + return test_suite_status; } - void TestSuite::InitLogger() + void TestSuite::init_logger() { - if (TestSuitesManager::Verbose == false) + if (TestSuitesManager::verbose == false) { - Logger.SetSeverity(flog::LogSeverity::Debug); - TestLogger.SetSeverity(flog::LogSeverity::Debug); + logger.SetSeverity(flog::LogSeverity::Debug); + test_logger.SetSeverity(flog::LogSeverity::Debug); } else { - Logger.SetSeverity(flog::LogSeverity::Trace); - TestLogger.SetSeverity(flog::LogSeverity::Trace); + logger.SetSeverity(flog::LogSeverity::Trace); + test_logger.SetSeverity(flog::LogSeverity::Trace); } std::string timePattern = ""; if (TestSuitesManager::PrintTime) timePattern = "[{T:pattern='%h:%m:%s:%ms'}] "; - if (Parent == nullptr) + if (parent == nullptr) { - Logger.SetName(Name); - Logger.SetRealPattern("{C:+black}" + timePattern + "{name} >> {color}{data}"); - TestLogger.SetName(Name + ".{test_name}"); - TestLogger.SetRealPattern("{C:+black}" + timePattern + "{name} >> {color}{data}"); + logger.set_name(name); + logger.SetRealPattern("{C:+black}" + timePattern + "{name} >> {color}{data}"); + test_logger.set_name(name + ".{test_name}"); + test_logger.SetRealPattern("{C:+black}" + timePattern + "{name} >> {color}{data}"); } else { - std::string correctedName = GetCorrectedSizeName(); - Logger.SetName(correctedName); - Logger.SetRealPatternStrmv("{C:+black}" + timePattern + "{name} >> {color}{data}"); - TestLogger.SetName(correctedName + ".{test_name}"); - TestLogger.SetRealPatternStrmv("{C:+black}" + timePattern + "{name} >> {color}{data}"); + std::string correctedName = get_corrected_size_name(); + logger.set_name(correctedName); + logger.SetRealPatternStrmv("{C:+black}" + timePattern + "{name} >> {color}{data}"); + test_logger.set_name(correctedName + ".{test_name}"); + test_logger.SetRealPatternStrmv("{C:+black}" + timePattern + "{name} >> {color}{data}"); } } - std::string TestSuite::GetFullName() + std::string TestSuite::get_full_name() { - if (Parent == nullptr) return Name; - return Parent->GetFullName() + "::" + Name; + if (parent == nullptr) return name; + return parent->get_full_name() + "::" + name; } - std::string TestSuite::GetCorrectedSizeName() + std::string TestSuite::get_corrected_size_name() { - if (Parent == nullptr) return Name; + if (parent == nullptr) return name; std::size_t biggestName = 0; - for (auto& [name, testSuite] : Parent->TestSuitesLinked) + for (auto& [name, test_suite] : parent->test_suites_linked) { - std::size_t tmp = testSuite->Name.size(); + std::size_t tmp = test_suite->name.size(); if (tmp > biggestName) biggestName = tmp; } - std::string res = GetFullName(); - biggestName -= Name.size(); + std::string res = get_full_name(); + biggestName -= name.size(); res.reserve(res.size() + biggestName); for (std::uint32_t i = 0; i < biggestName; ++i) res.push_back(' '); return res; } - ProfilerManager::Profiler& TestSuite::GetProfiler() + profiler::Profiler& TestSuite::get_profiler() { - if (Parent == nullptr) return *Profiler; - return Parent->GetProfiler(); + if (parent == nullptr) return *profiler; + return parent->get_profiler(); } } diff --git a/src/stream/tester/test_suite/test_suite.h b/src/stream/tester/test_suite/test_suite.h index fc9fc5ff..651a8c9f 100644 --- a/src/stream/tester/test_suite/test_suite.h +++ b/src/stream/tester/test_suite/test_suite.h @@ -2,15 +2,15 @@ #include "stream/flog.h" #include "stream/fmt.h" -#include "stream/ProfilerManager.h" +#include "stream/profiler.h" -#include "stream/fmt/serializers/CompilationData.h" +#include "stream/fmt/serializers/compilation_data.h" #include #include #include -namespace stream::Tester +namespace stream::tester { class TestFailure { @@ -24,16 +24,16 @@ namespace stream::Tester }; } -namespace stream::Tester::detail +namespace stream::tester::detail { class TestSuite; class Test { public: Test(std::string&& name, TestSuite& link, const fmt::detail::FileLocation& location) - : Name(std::move(name)) + : name(std::move(name)) , Link(link) - , Location(location) + , location(location) , LastStatus(TestStatus::Ok) {} @@ -43,7 +43,7 @@ namespace stream::Tester::detail virtual TestStatus RunImpl() = 0; public: - TestStatus Run() + TestStatus run() { try { @@ -60,9 +60,9 @@ namespace stream::Tester::detail } public: - std::string Name; + std::string name; TestSuite& Link; - fmt::detail::FileLocation Location; + fmt::detail::FileLocation location; TestStatus LastStatus; }; @@ -70,50 +70,50 @@ namespace stream::Tester::detail { void Reset() { - TestsDone = 0; - TestsOk = 0; - TestsFail = 0; - TestsCrash = 0; + testsDone = 0; + testsOk = 0; + testsFail = 0; + testsCrash = 0; } void AddTestStatus(TestStatus status) { - TestsDone++; + testsDone++; switch (status) { case TestStatus::Ok: - TestsOk++; + testsOk++; break; case TestStatus::Fail: - TestsFail++; + testsFail++; break; case TestStatus::Crash: - TestsCrash++; + testsCrash++; break; } } void Add(TestStatusBank status) { - TestsDone += status.TestsDone; - TestsOk += status.TestsOk; - TestsFail += status.TestsFail; - TestsCrash += status.TestsCrash; + testsDone += status.testsDone; + testsOk += status.testsOk; + testsFail += status.testsFail; + testsCrash += status.testsCrash; } - bool IsAllOk() { return TestsDone == TestsOk && TestsCrash == 0 && TestsFail == 0; } + bool IsAllOk() { return testsDone == testsOk && testsCrash == 0 && testsFail == 0; } - std::uint32_t ErrorStatus() { return TestsDone - TestsOk; } + std::uint32_t ErrorStatus() { return testsDone - testsOk; } - std::uint32_t TestsDone = 0; - std::uint32_t TestsOk = 0; - std::uint32_t TestsFail = 0; - std::uint32_t TestsCrash = 0; + std::uint32_t testsDone = 0; + std::uint32_t testsOk = 0; + std::uint32_t testsFail = 0; + std::uint32_t testsCrash = 0; }; class TestSuite; } -namespace stream::Tester +namespace stream::tester { struct PerformanceTestData { @@ -129,17 +129,17 @@ namespace stream::Tester class TestSuitesManager { public: - static bool ExecAllTestSuites(); - static inline std::unordered_map TestSuites; + static bool exec_all_test_suites(); + static inline std::unordered_map test_suites; public: - static inline bool Verbose = false; + static inline bool verbose = false; static inline bool PrintTime = false; static inline PerformanceTestData PerformanceTest = PerformanceTestData{}; static inline ConcurenceSpecificationData ConcurenceSpecification = ConcurenceSpecificationData{}; }; } -namespace stream::Tester::detail +namespace stream::tester::detail { struct TestSuiteData { @@ -152,108 +152,108 @@ namespace stream::Tester::detail { public: TestSuite(std::string&& name, TestSuiteData extra = TestSuiteData{}, TestSuite* parent = nullptr) - : Name(std::move(name)) - , Tests() - , Extra(extra) - , Logger() - , TestLogger() - , Profiler(nullptr) - , Parent(parent) + : name(std::move(name)) + , tests() + , extra(extra) + , logger() + , test_logger() + , profiler(nullptr) + , parent(parent) { if (parent == nullptr) - TestSuitesManager::TestSuites.insert({Name, this}); + TestSuitesManager::test_suites.insert({name, this}); else - Parent->TestSuitesLinked.insert({Name, this}); + parent->test_suites_linked.insert({name, this}); } - std::string Name; - std::unordered_map Tests; - std::unordered_map TestSuitesLinked; + std::string name; + std::unordered_map tests; + std::unordered_map test_suites_linked; - TestSuiteData Extra; - flog::BasicLogger Logger; - flog::BasicLogger TestLogger; - ProfilerManager::Profiler* Profiler; + TestSuiteData extra; + flog::BasicLogger logger; + flog::BasicLogger test_logger; + profiler::Profiler* profiler; - TestSuite* Parent; + TestSuite* parent; public: - void InitLogger(); + void init_logger(); private: - std::string GetFullName(); - std::string GetCorrectedSizeName(); - ProfilerManager::Profiler& GetProfiler(); + std::string get_full_name(); + std::string get_corrected_size_name(); + profiler::Profiler& get_profiler(); public: - TestStatusBank ExecAllTests(); + TestStatusBank exec_all_tests(); }; } namespace stream::fmt { template - struct FormatterType + struct FormatterType { - [[nodiscard]] static std::expected format(const stream::Tester::detail::TestSuite& t, FormatterExecutor& executor) - { return executor.buffer_out.FastWriteString(t.Name); } + [[nodiscard]] static std::expected format(const stream::tester::detail::TestSuite& t, FormatterExecutor& executor) + { return executor.ostream.fast_write_string(t.name); } }; template - struct FormatterType + struct FormatterType { - [[nodiscard]] static std::expected format(const stream::Tester::detail::Test& t, FormatterExecutor& executor) + [[nodiscard]] static std::expected format(const stream::tester::detail::Test& t, FormatterExecutor& executor) { - SF_TRY(detail::BufferWriteManip(executor.buffer_out).FastWriteString(t.Link.Name)); - SF_TRY(detail::BufferWriteManip(executor.buffer_out).FastWriteStringLitteral("::")); - SF_TRY(detail::BufferWriteManip(executor.buffer_out).FastWriteString(t.Name)); + SF_TRY(buf::WriteManip(executor.ostream).fast_write_string(t.Link.name)); + SF_TRY(buf::WriteManip(executor.ostream).fast_write_string_literal("::")); + SF_TRY(buf::WriteManip(executor.ostream).fast_write_string(t.name)); return {}; } }; template - struct FormatterType + struct FormatterType { - [[nodiscard]] static std::expected format(const stream::Tester::TestStatus& status, FormatterExecutor& executor) + [[nodiscard]] static std::expected format(const stream::tester::TestStatus& status, FormatterExecutor& executor) { switch (status) { - case stream::Tester::TestStatus::Ok: - return executor.Run("[ {C:green}OK{C} ]"); - case stream::Tester::TestStatus::Fail: - return executor.Run("[ {C:red}FAIL{C} ]"); - case stream::Tester::TestStatus::Crash: - return executor.Run("[{C:magenta}Crash{C} ]"); + case stream::tester::TestStatus::Ok: + return executor.run("[ {C:green}OK{C} ]"); + case stream::tester::TestStatus::Fail: + return executor.run("[ {C:red}FAIL{C} ]"); + case stream::tester::TestStatus::Crash: + return executor.run("[{C:magenta}Crash{C} ]"); } return {}; } }; template - struct FormatterType + struct FormatterType { - [[nodiscard]] static std::expected format(const stream::Tester::detail::TestStatusBank& statusBank, FormatterExecutor& executor) + [[nodiscard]] static std::expected format(const stream::tester::detail::TestStatusBank& statusBank, FormatterExecutor& executor) { - SF_TRY(detail::BufferWriteManip(executor.buffer_out).FastWriteStringLitteral("TestsDone ")); - SF_TRY(executor.Run("{:C:white}", statusBank.TestsDone)); + SF_TRY(buf::WriteManip(executor.ostream).fast_write_string_literal("testsDone ")); + SF_TRY(executor.run("{:C:white}", statusBank.testsDone)); - SF_TRY(detail::BufferWriteManip(executor.buffer_out).FastWriteStringLitteral(" | TestsOK ")); - if (statusBank.TestsOk == statusBank.TestsDone) - { SF_TRY(executor.Run("{:C:green}", statusBank.TestsOk)); } + SF_TRY(buf::WriteManip(executor.ostream).fast_write_string_literal(" | testsOK ")); + if (statusBank.testsOk == statusBank.testsDone) + { SF_TRY(executor.run("{:C:green}", statusBank.testsOk)); } else - { SF_TRY(executor.Run("{:C:yellow}", statusBank.TestsOk)); } + { SF_TRY(executor.run("{:C:yellow}", statusBank.testsOk)); } - SF_TRY(detail::BufferWriteManip(executor.buffer_out).FastWriteStringLitteral(" | TestsFAIL ")); - if (statusBank.TestsFail == 0) - { SF_TRY(executor.Run("{:C:green}", statusBank.TestsFail)); } + SF_TRY(buf::WriteManip(executor.ostream).fast_write_string_literal(" | testsFAIL ")); + if (statusBank.testsFail == 0) + { SF_TRY(executor.run("{:C:green}", statusBank.testsFail)); } else - { SF_TRY(executor.Run("{:C:red}", statusBank.TestsFail)); } + { SF_TRY(executor.run("{:C:red}", statusBank.testsFail)); } - SF_TRY(detail::BufferWriteManip(executor.buffer_out).FastWriteStringLitteral(" | TestCrash ")); - if (statusBank.TestsCrash == 0) - { SF_TRY(executor.Run("{:C:green}", statusBank.TestsCrash)); } + SF_TRY(buf::WriteManip(executor.ostream).fast_write_string_literal(" | TestCrash ")); + if (statusBank.testsCrash == 0) + { SF_TRY(executor.run("{:C:green}", statusBank.testsCrash)); } else - { SF_TRY(executor.Run("{:C:magenta}", statusBank.TestsCrash)); } + { SF_TRY(executor.run("{:C:magenta}", statusBank.testsCrash)); } return {}; } @@ -265,17 +265,17 @@ namespace stream::fmt #define STREAMFORMAT_TESTINTERNAL_FUNC_NAME(TestSuiteName, TestName) TestSuite_##TestSuiteName##TestName #define STREAMFORMAT_TESTINTERNAL_FUNC_EXEC_NAME(TestSuiteName, TestName) TestSuite_##TestSuiteName##TestName##_ExecMethod #define STREAMFORMAT_TESTINTERNAL_SUITE_EXTRA(...) \ - stream::Tester::detail::TestSuiteData \ + stream::tester::detail::TestSuiteData \ { \ __VA_ARGS__ \ } //-------------------- TestSuite --------------------// #define SFT_TEST_SUITE(TestSuiteName, ...) \ - stream::Tester::detail::TestSuite STREAMFORMAT_TESTINTERNAL_SUITE_NAME(TestSuiteName)(#TestSuiteName, STREAMFORMAT_TESTINTERNAL_SUITE_EXTRA(__VA_ARGS__)) + stream::tester::detail::TestSuite STREAMFORMAT_TESTINTERNAL_SUITE_NAME(TestSuiteName)(#TestSuiteName, STREAMFORMAT_TESTINTERNAL_SUITE_EXTRA(__VA_ARGS__)) #define SFT_TEST_GROUP(TestSuiteName, GroupName, ...) \ - stream::Tester::detail::TestSuite STREAMFORMAT_TESTINTERNAL_SUITE_NAME(GroupName)(#GroupName, STREAMFORMAT_TESTINTERNAL_SUITE_EXTRA(__VA_ARGS__), \ + stream::tester::detail::TestSuite STREAMFORMAT_TESTINTERNAL_SUITE_NAME(GroupName)(#GroupName, STREAMFORMAT_TESTINTERNAL_SUITE_EXTRA(__VA_ARGS__), \ &STREAMFORMAT_TESTINTERNAL_SUITE_NAME(TestSuiteName)) -#define SFT_TEST_SUITE_DECLARATION(TestSuiteName, ...) stream::Tester::detail::TestSuite STREAMFORMAT_TESTINTERNAL_SUITE_NAME(TestSuiteName) -#define SFT_TEST_GROUP_DECLARATION(TestSuiteName, GroupName, ...) stream::Tester::detail::TestSuite STREAMFORMAT_TESTINTERNAL_SUITE_NAME(GroupName) +#define SFT_TEST_SUITE_DECLARATION(TestSuiteName, ...) stream::tester::detail::TestSuite STREAMFORMAT_TESTINTERNAL_SUITE_NAME(TestSuiteName) +#define SFT_TEST_GROUP_DECLARATION(TestSuiteName, GroupName, ...) stream::tester::detail::TestSuite STREAMFORMAT_TESTINTERNAL_SUITE_NAME(GroupName) diff --git a/src/stream/tester/tests_macros.h b/src/stream/tester/tests_macros.h index ca7f2877..ec52cc34 100644 --- a/src/stream/tester/tests_macros.h +++ b/src/stream/tester/tests_macros.h @@ -2,21 +2,21 @@ #include "stream/flog.h" -#define STREAMFORMAT_TEST_TRACE(...) stream::Test::TestCore::GetLogger().trace(__VA_ARGS__) -#define STREAMFORMAT_TEST_INFO(...) stream::Test::TestCore::GetLogger().info(__VA_ARGS__) -#define STREAMFORMAT_TEST_WARN(...) stream::Test::TestCore::GetLogger().warn(__VA_ARGS__) -#define STREAMFORMAT_TEST_ERROR(...) stream::Test::TestCore::GetLogger().error(__VA_ARGS__) -#define STREAMFORMAT_TEST_FATAL(...) stream::Test::TestCore::GetLogger().fatal(__VA_ARGS__) -#define STREAMFORMAT_TEST_OK(...) stream::Test::TestCore::GetLogger().Ok(__VA_ARGS__) -#define STREAMFORMAT_TEST_FAIL(...) stream::Test::TestCore::GetLogger().Fail(__VA_ARGS__) -#define STREAMFORMAT_TEST_BASIC(...) stream::Test::TestCore::GetLogger().Basic(__VA_ARGS__) +#define STREAMFORMAT_TEST_TRACE(...) stream::Test::TestCore::get_logger().trace(__VA_ARGS__) +#define STREAMFORMAT_TEST_INFO(...) stream::Test::TestCore::get_logger().info(__VA_ARGS__) +#define STREAMFORMAT_TEST_WARN(...) stream::Test::TestCore::get_logger().warn(__VA_ARGS__) +#define STREAMFORMAT_TEST_ERROR(...) stream::Test::TestCore::get_logger().error(__VA_ARGS__) +#define STREAMFORMAT_TEST_FATAL(...) stream::Test::TestCore::get_logger().fatal(__VA_ARGS__) +#define STREAMFORMAT_TEST_OK(...) stream::Test::TestCore::get_logger().Ok(__VA_ARGS__) +#define STREAMFORMAT_TEST_FAIL(...) stream::Test::TestCore::get_logger().Fail(__VA_ARGS__) +#define STREAMFORMAT_TEST_BASIC(...) stream::Test::TestCore::get_logger().Basic(__VA_ARGS__) namespace stream::Test { class TestCore { public: - static flog::BasicLogger& GetLogger() + static flog::BasicLogger& get_logger() { static flog::BasicLogger instance("stream-Test", "{name} {color} -> {data}"); return instance; diff --git a/tests/BUILD.bazel b/tests/BUILD.bazel new file mode 100644 index 00000000..14210557 --- /dev/null +++ b/tests/BUILD.bazel @@ -0,0 +1,24 @@ +"" + +load("@rules_cc//cc:defs.bzl", "cc_test") + +cc_test( + name = "units", + srcs = glob([ "**/*.h", "**/*.cpp" ]), + copts = select({ + "@rules_cc//cc/compiler:msvc-cl": ["/std:latest"], + "//conditions:default": [ + "-std=c++23", + "-Wall", "-Wextra", "-Wpedantic", + "-Wshadow", + "-Wconversion", "-Wsign-conversion", + "-Werror=return-type" + ], + }), + deps = [ "//:stream" ], + linkopts = select({ + "@rules_cc//cc/compiler:msvc-cl": [""], + "//conditions:default": ["-pthread"], + }), + visibility = ["//visibility:public"], +) diff --git a/tests/fmt/base_fmt_tests.h b/tests/fmt/base_fmt_tests.h index 3c1090f3..9327aecc 100644 --- a/tests/fmt/base_fmt_tests.h +++ b/tests/fmt/base_fmt_tests.h @@ -1,5 +1,5 @@ #pragma once -#include "stream/Tester/TestSuite/AllTestSuite.h" +#include "stream/tester/test_suite/all_test_suite.h" inline SFT_TEST_SUITE(FMT); diff --git a/tests/fmt/complex_pattern.cpp b/tests/fmt/complex_pattern.cpp index 932a006b..1a2fc0a3 100644 --- a/tests/fmt/complex_pattern.cpp +++ b/tests/fmt/complex_pattern.cpp @@ -1,11 +1,11 @@ #include "stream/fmt.h" -#include "stream/Tester/TestSuite/AllTestSuite.h" +#include "stream/tester/test_suite/all_test_suite.h" -#include "BaseFMTTests.h" +#include "base_fmt_tests.h" SFT_TEST_GROUP(FMT, COMPLEX_PATTERN); -#define TEST_FMT(fmt_test, expected, ...) SFT_EQ(stream::fmt::FormatString(fmt_test, __VA_ARGS__).value(), std::string(expected)) +#define TEST_FMT(fmt_test, expected, ...) SFT_EQ(stream::fmt::format_string(fmt_test, __VA_ARGS__).value(), std::string(expected)) SFT_TEST_FUNC(COMPLEX_PATTERN, UNESCAPED_ESCAPE_PATTERN) { diff --git a/tests/fmt/globber.cpp b/tests/fmt/globber.cpp index cf0a6bf6..a0c6c25c 100644 --- a/tests/fmt/globber.cpp +++ b/tests/fmt/globber.cpp @@ -1,18 +1,18 @@ -#include "BaseFMTTests.h" +#include "base_fmt_tests.h" -#include "stream/fmt/context/ParserExecutor/utility_functions.h" +#include "stream/fmt/context/parser_executor/utility_functions.h" -#include "stream/fmt/buffer/utils/BufferGlobberManip.h" +#include "stream/fmt/buf/utils/buffer_globber_manip.h" SFT_TEST_GROUP(FMT, GLOBBER); #define TEST_GLOBBER(data, glob) \ { \ - stream::fmt::detail::BufferInfoView p_buffer(data); \ - stream::fmt::detail::BufferInfoView p_glob(glob); \ - stream::fmt::detail::Globber::BufferInExecGlob(p_buffer, \ + stream::fmt::buf::StreamView p_buffer(data); \ + stream::fmt::buf::StreamView p_glob(glob); \ + stream::fmt::buf::Globber::buffer_exec_glob(p_buffer, \ p_glob).value(); \ SFT_ASSERT( \ - stream::fmt::detail::BufferAccess(p_buffer).IsEndOfString()); \ + stream::fmt::buf::Access(p_buffer).is_end_of_string()); \ } SFT_TEST_FUNC(GLOBBER, BASIC_WILDCARD){ diff --git a/tests/fmt/index.cpp b/tests/fmt/index.cpp index 26fcb531..de2ce128 100644 --- a/tests/fmt/index.cpp +++ b/tests/fmt/index.cpp @@ -1,7 +1,7 @@ #include "stream/fmt.h" -#include "stream/Tester/TestSuite/AllTestSuite.h" +#include "stream/tester/test_suite/all_test_suite.h" -#include "BaseFMTTests.h" +#include "base_fmt_tests.h" /* SFT_TEST_GROUP(FMT, INDEX); diff --git a/tests/fmt/limits.cpp b/tests/fmt/limits.cpp index 3d67d872..c004e5bd 100644 --- a/tests/fmt/limits.cpp +++ b/tests/fmt/limits.cpp @@ -1,14 +1,14 @@ #include "stream/fmt.h" -#include "stream/Tester/TestSuite/AllTestSuite.h" +#include "stream/tester/test_suite/all_test_suite.h" -#include "BaseFMTTests.h" +#include "base_fmt_tests.h" SFT_TEST_GROUP(FMT, LIMITS); #define SFT_TEST_FUNC_LowBufferSize(k) \ SFT_TEST_FUNC(LIMITS, LowBufferSize##k) { \ char buffer[k] = {0}; \ - auto res = stream::fmt::FormatInChar(buffer, "0123456789"); \ + auto res = stream::fmt::format_in_char(buffer, "0123456789"); \ SFT_EXPECTED_VALUE(res); \ for (int i = 0; i < k; ++i) \ SFT_EQ(buffer[i] - '0', i); \ @@ -27,7 +27,7 @@ SFT_TEST_FUNC_LowBufferSize(1); SFT_TEST_FUNC(LIMITS, PlainLowBufferSize10) { char buffer[10] = {0}; - auto res = stream::fmt::FormatInChar(buffer, "0123456789"); + auto res = stream::fmt::format_in_char(buffer, "0123456789"); SFT_EXPECTED_VALUE(res); for (int i = 0; i < 10; ++i) SFT_EQ(buffer[i] - '0', i); @@ -35,7 +35,7 @@ SFT_TEST_FUNC(LIMITS, PlainLowBufferSize10) { SFT_TEST_FUNC(LIMITS, PlainLowBufferSize1) { char buffer[1] = {0}; - auto res = stream::fmt::FormatInChar(buffer, "0"); + auto res = stream::fmt::format_in_char(buffer, "0"); SFT_EXPECTED_VALUE(res); for (int i = 0; i < 1; ++i) SFT_EQ(buffer[i] - '0', i); @@ -46,9 +46,9 @@ SFT_TEST_FUNC(LIMITS, PlainLowBufferSize1) { char buffer[k] = {0}; \ const char fmtBuffer[] = { \ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; \ - stream::fmt::detail::BufferInfoView format(fmtBuffer, k); \ - stream::fmt::detail::GivenBufferOutManager manager(buffer, k); \ - auto res = stream::fmt::detail::FormatInManager(manager, false, format); \ + stream::fmt::buf::StreamView format(fmtBuffer, k); \ + stream::fmt::buf::GivenStreamIOManager manager(buffer, k); \ + auto res = stream::fmt::detail::format_in_manager(manager, false, format); \ SFT_EXPECTED_VALUE(res); \ for (int i = 0; i < k; ++i) \ SFT_EQ(buffer[i] - '0', i); \ @@ -68,9 +68,9 @@ SFT_TEST_FUNC_LowBufferSizeArray(1); SFT_TEST_FUNC(LIMITS, PlainLowBufferSizeArray10) { char buffer[10] = {0}; const char fmtBuffer[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; - stream::fmt::detail::BufferInfoView fmt(fmtBuffer, 10); - stream::fmt::detail::GivenBufferOutManager manager(buffer, 10); - auto res = stream::fmt::detail::FormatInManager(manager, false, fmt); + stream::fmt::buf::StreamView fmt(fmtBuffer, 10); + stream::fmt::buf::GivenStreamIOManager manager(buffer, 10); + auto res = stream::fmt::detail::format_in_manager(manager, false, fmt); SFT_EXPECTED_VALUE(res); for (int i = 0; i < 10; ++i) SFT_EQ(buffer[i] - '0', i); @@ -79,9 +79,9 @@ SFT_TEST_FUNC(LIMITS, PlainLowBufferSizeArray10) { SFT_TEST_FUNC(LIMITS, PlainLowBufferSizeArray1) { char buffer[1] = {0}; const char fmtBuffer[] = {'0'}; - stream::fmt::detail::BufferInfoView fmt(fmtBuffer, 1); - stream::fmt::detail::GivenBufferOutManager manager(buffer, 1); - auto res = stream::fmt::detail::FormatInManager(manager, false, fmt); + stream::fmt::buf::StreamView fmt(fmtBuffer, 1); + stream::fmt::buf::GivenStreamIOManager manager(buffer, 1); + auto res = stream::fmt::detail::format_in_manager(manager, false, fmt); SFT_EXPECTED_VALUE(res); for (int i = 0; i < 1; ++i) SFT_EQ(buffer[i] - '0', i); @@ -92,9 +92,9 @@ SFT_TEST_FUNC(LIMITS, LowBufferSizeArray10FMT30) { const char fmtBuffer[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; - stream::fmt::detail::BufferInfoView fmt(fmtBuffer, 30); - stream::fmt::detail::GivenBufferOutManager manager(buffer, 10); - auto res = stream::fmt::detail::FormatInManager(manager, false, fmt); + stream::fmt::buf::StreamView fmt(fmtBuffer, 30); + stream::fmt::buf::GivenStreamIOManager manager(buffer, 10); + auto res = stream::fmt::detail::format_in_manager(manager, false, fmt); SFT_EXPECTED_VALUE(res); for (int k = 0; k < 10; ++k) SFT_EQ(buffer[k] - '0', k); @@ -102,10 +102,10 @@ SFT_TEST_FUNC(LIMITS, LowBufferSizeArray10FMT30) { SFT_TEST_FUNC(LIMITS, LowBufferSizeArray5Number9) { char buffer[10] = {0}; - stream::fmt::detail::BufferInfoView fmt("{}"); - stream::fmt::detail::GivenBufferOutManager manager(buffer, 10); + stream::fmt::buf::StreamView fmt("{}"); + stream::fmt::buf::GivenStreamIOManager manager(buffer, 10); std::uint64_t i = 9'876'543'210; - auto res = stream::fmt::detail::FormatInManager(manager, false, fmt, i); + auto res = stream::fmt::detail::format_in_manager(manager, false, fmt, i); SFT_EXPECTED_VALUE(res); for (int k = 0; k < 10; ++k) SFT_EQ(buffer[k] - '0', 9 - k); diff --git a/tests/fmt/shift.cpp b/tests/fmt/shift.cpp index 8dc55675..74306891 100644 --- a/tests/fmt/shift.cpp +++ b/tests/fmt/shift.cpp @@ -1,11 +1,11 @@ #include "stream/fmt.h" -#include "stream/Tester/TestSuite/AllTestSuite.h" +#include "stream/tester/test_suite/all_test_suite.h" -#include "BaseFMTTests.h" +#include "base_fmt_tests.h" SFT_TEST_GROUP(FMT, SHIFT); -#define TEST_FMT(fmt_test, expected, ...) SFT_EQ(stream::fmt::FormatString(fmt_test, __VA_ARGS__), expected) +#define TEST_FMT(fmt_test, expected, ...) SFT_EQ(stream::fmt::format_string(fmt_test, __VA_ARGS__), expected) SFT_TEST_GROUP(SHIFT, NUMBER_SHIFT); SFT_TEST_GROUP(NUMBER_SHIFT, ONE_DIGIT); diff --git a/tests/fmt/specifier.cpp b/tests/fmt/specifier.cpp index 042b062d..5907eeed 100644 --- a/tests/fmt/specifier.cpp +++ b/tests/fmt/specifier.cpp @@ -1,11 +1,11 @@ #include "stream/fmt.h" -#include "stream/Tester/TestSuite/AllTestSuite.h" +#include "stream/tester/test_suite/all_test_suite.h" -#include "BaseFMTTests.h" +#include "base_fmt_tests.h" SFT_TEST_GROUP(FMT, SPECIFIER); -#define TEST_FMT_ARRAY_SPECIFIERS(fmt_test, test_data, expected) SFT_EQ(stream::fmt::FormatString(fmt_test, test_data), expected) +#define TEST_FMT_ARRAY_SPECIFIERS(fmt_test, test_data, expected) SFT_EQ(stream::fmt::format_string(fmt_test, test_data), expected) SFT_TEST_FUNC(SPECIFIER, BEGIN_END) { diff --git a/tests/fmt/text_properties.cpp b/tests/fmt/text_properties.cpp index 6befe4ab..4939ed86 100644 --- a/tests/fmt/text_properties.cpp +++ b/tests/fmt/text_properties.cpp @@ -1,11 +1,11 @@ #include "stream/fmt.h" -#include "stream/Tester/TestSuite/AllTestSuite.h" +#include "stream/tester/test_suite/all_test_suite.h" -#include "BaseFMTTests.h" +#include "base_fmt_tests.h" SFT_TEST_GROUP(FMT, TEXT_PROPERTIES); -#define TEST_FMT(fmt_test, expected) SFT_EQ(Escaper(stream::fmt::FormatString(fmt_test, 0).value()), Escaper(expected)) +#define TEST_FMT(fmt_test, expected) SFT_EQ(Escaper(stream::fmt::format_string(fmt_test, 0).value()), Escaper(expected)) static std::string Escaper(const std::string& str) { @@ -32,7 +32,7 @@ SFT_TEST_FUNC(ESCAPER_VALIDATING, BasicTest) TEST_ESCAPER("\033k", "\\ek"); } -SFT_TEST_FUNC(TEXT_PROPERTIES, BasicColor) +SFT_TEST_FUNC(TEXT_PROPERTIES, basic_color) { TEST_FMT("123", "123"); @@ -83,7 +83,7 @@ class TEST_FMT_ContextOut }; STREAMFORMAT_AUTO_FORMATTER_T(TEST_FMT_ContextOut, "{C:red} TEST_FMT_ContextOut {} ", 0); -#define TEST_FMT_CONTEXT(fmt_test, expected) SFT_EQ(Escaper(stream::fmt::FormatString(fmt_test, TEST_FMT_ContextOut{}).value()), Escaper(expected)) +#define TEST_FMT_CONTEXT(fmt_test, expected) SFT_EQ(Escaper(stream::fmt::format_string(fmt_test, TEST_FMT_ContextOut{}).value()), Escaper(expected)) SFT_TEST_FUNC(TEXT_PROPERTIES, ContextOut) { diff --git a/tests/tests.cpp b/tests/tests.cpp index 55308fe0..71fc519e 100644 --- a/tests/tests.cpp +++ b/tests/tests.cpp @@ -1,9 +1,9 @@ -#include "stream/Tester/TestSuite/AllTestSuite.h" -#include "stream/flog/DefaultLogger.h" +#include "stream/tester/test_suite/all_test_suite.h" +#include "stream/default_logger.h" int main() { - stream::Tester::TestSuitesManager::Verbose = false; - return stream::Tester::TestSuitesManager::ExecAllTestSuites(); + stream::tester::TestSuitesManager::verbose = false; + return stream::tester::TestSuitesManager::exec_all_test_suites(); } From 1673a9767157865e3ba6d2d84c11e67362d37c5b Mon Sep 17 00:00:00 2001 From: Sacha Bellier Date: Sun, 23 Mar 2025 15:33:39 +0100 Subject: [PATCH 18/42] feat: CI --- .buildkite/linux_amd64.yml | 8 +-- .buildkite/windows_amd64.yml | 6 +- .github/workflows/CodeChecker.yml.nop | 37 ------------ .github/workflows/StreamFormat.yml | 87 --------------------------- .github/workflows/linter.yml | 33 ++++++++++ .github/workflows/tests_linux.yml | 48 +++++++++++++++ .github/workflows/tests_windows.yml | 35 +++++++++++ .gitmodules | 3 + buildbuddy.yaml | 2 +- conf | 1 + custom/BUILD.bazel | 4 +- scripts/clang-tidy.sh | 3 + 12 files changed, 133 insertions(+), 134 deletions(-) delete mode 100644 .github/workflows/CodeChecker.yml.nop delete mode 100644 .github/workflows/StreamFormat.yml create mode 100644 .github/workflows/linter.yml create mode 100644 .github/workflows/tests_linux.yml create mode 100644 .github/workflows/tests_windows.yml create mode 100644 .gitmodules create mode 160000 conf create mode 100755 scripts/clang-tidy.sh diff --git a/.buildkite/linux_amd64.yml b/.buildkite/linux_amd64.yml index 187bd166..fa315d22 100644 --- a/.buildkite/linux_amd64.yml +++ b/.buildkite/linux_amd64.yml @@ -4,10 +4,10 @@ agents: steps: - label: ":bazel: Build and Test on gcc (W asan)" commands: - - CC=gcc-14 bazelisk build --features=asan //:streamTests - - CC=gcc-14 bazelisk test --features=asan //:streamTests + - CC=gcc-14 bazelisk build --features=asan //tests:units + - CC=gcc-14 bazelisk test --features=asan //tests:units - label: ":bazel: Build and Test on Clang (W asan)" commands: - - CC=clang-20 bazelisk build --features=asan //:streamTests - - CC=clang-20 bazelisk test --features=asan //:streamTests + - CC=clang-20 bazelisk build --features=asan //tests:units + - CC=clang-20 bazelisk test --features=asan //tests:units diff --git a/.buildkite/windows_amd64.yml b/.buildkite/windows_amd64.yml index fe79bee9..8208a33e 100644 --- a/.buildkite/windows_amd64.yml +++ b/.buildkite/windows_amd64.yml @@ -4,11 +4,11 @@ agents: steps: # - label: ":bazel: Build And Test MSVC" # commands: - # - bazelisk test //:streamTests + # - bazelisk test //tests:units - label: ":bazel: Build And Test Winlibs/clang" commands: - - bazelisk build --config=winlibs-clang //:streamTests + - bazelisk build --config=winlibs-clang //tests:units - label: ":bazel: Build And Test Winlibs/gcc" commands: - - bazelisk build --config=winlibs-gcc //:streamTests + - bazelisk build --config=winlibs-gcc //tests:units diff --git a/.github/workflows/CodeChecker.yml.nop b/.github/workflows/CodeChecker.yml.nop deleted file mode 100644 index 601952e8..00000000 --- a/.github/workflows/CodeChecker.yml.nop +++ /dev/null @@ -1,37 +0,0 @@ -name: CodeChecker - -on: - push: - branches: - - '**' - pull_request: - branches: - - '**' - -jobs: - codechecker-ubuntu-latest: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: bazelbuild/setup-bazelisk@v3 - - name: Mount bazel cache - uses: actions/cache@v4 - with: - path: "~/.cache/bazel" - key: bazel - - - name: build & retreive compile_commands.json - run: | - bazelisk clean - bazelisk build //:streamTests - bazelisk run //conf:compile_commands - - - uses: whisperity/CodeChecker-Action@v1.0.4 - id: codechecker - with: - logfile: ${{ github.workspace }}/compile_commands.json - - - uses: actions/upload-artifact@v4 - with: - name: "CodeChecker Bug Reports" - path: ${{ steps.codechecker.outputs.result-html-dir }} diff --git a/.github/workflows/StreamFormat.yml b/.github/workflows/StreamFormat.yml deleted file mode 100644 index 6de47744..00000000 --- a/.github/workflows/StreamFormat.yml +++ /dev/null @@ -1,87 +0,0 @@ -name: stream - -on: - push: - branches: - - '**' - pull_request: - branches: - - '**' - -jobs: - # windows-latest-msvc: - # runs-on: windows-latest - # steps: - # - uses: actions/checkout@v4 - # - uses: bazelbuild/setup-bazelisk@v3 - # - name: Mount bazel cache - # uses: actions/cache@v4 - # with: - # path: "~/.cache/bazel" - # key: bazel - # - name: Building... - # run: bazelisk build //:streamTests - # - name: Testing... - # run: bazelisk test //:streamTests - - windows-latest-winlibs: - runs-on: windows-latest - steps: - - uses: actions/checkout@v4 - - uses: bazelbuild/setup-bazelisk@v3 - - name: Mount bazel cache - uses: actions/cache@v4 - with: - path: "~/.cache/bazel" - key: bazel - - name: Build Winlibs/clang... - run: bazelisk build --config=winlibs-clang //:streamTests - - name: Build Winlibs/gcc... - run: bazelisk build --config=winlibs-gcc //:streamTests - - ubuntu-latest-gcc: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: bazelbuild/setup-bazelisk@v3 - - name: Mount bazel cache - uses: actions/cache@v4 - with: - path: "~/.cache/bazel" - key: bazel - - name: Install Gcc 13 - run: | - sudo apt install software-properties-common - sudo add-apt-repository ppa:ubuntu-toolchain-r/test - sudo apt-get update - sudo apt install gcc-13 - - name: Version - run: gcc --version - - name: Version - run: gcc-13 --version - - name: Building... - run: CC=gcc-13 bazelisk build //:streamTests - - name: Testing... (W asan) - run: CC=gcc-13 bazelisk test --features=asan //:streamTests - - ubuntu-latest-clang: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: bazelbuild/setup-bazelisk@v3 - - name: Mount bazel cache - uses: actions/cache@v4 - with: - path: "~/.cache/bazel" - key: bazel - - name: Install clang 20 - run: | - wget https://apt.llvm.org/llvm.sh - chmod +x ./llvm.sh - sudo ./llvm.sh 20 - - name: Version - run: clang++-20 --version - - name: Building... - run: CC=clang++-20 bazelisk build //:streamTests - - name: Testing... (W asan) - run: CC=clang++-20 bazelisk test --features=asan //:streamTests diff --git a/.github/workflows/linter.yml b/.github/workflows/linter.yml new file mode 100644 index 00000000..319c12ce --- /dev/null +++ b/.github/workflows/linter.yml @@ -0,0 +1,33 @@ +name: linter + +on: + push: + branches: + - '**' + +jobs: + clang-format: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + submodules: true + - name: Install clang-format... + run: sudo apt install clang-format + - run: ./conf/linter/clang-format.sh + + clang-tidy: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + submodules: true + - uses: bazelbuild/setup-bazelisk@v3 + - uses: actions/cache@v4 + with: + path: "~/.cache/bazel" + key: bazel + - name: Install clang-tidy... + run: sudo apt install clang-tidy + - name: Running clang-tidy... + run: ./scripts/clang-tidy.sh diff --git a/.github/workflows/tests_linux.yml b/.github/workflows/tests_linux.yml new file mode 100644 index 00000000..3dfb58d2 --- /dev/null +++ b/.github/workflows/tests_linux.yml @@ -0,0 +1,48 @@ +name: Tests Linux + +on: + push: + branches: + - '**' + +jobs: + ubuntu-latest-gcc: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: bazelbuild/setup-bazelisk@v3 + - uses: actions/cache@v4 + with: + path: "~/.cache/bazel" + key: bazel + - name: Version + run: gcc --version + - name: Building... + run: CC=gcc bazelisk build //tests:units + - name: Testing (asan)... + run: CC=gcc bazelisk test //tests:units + - name: Testing (asan)... + run: CC=gcc bazelisk test --features=asan //tests:units + + ubuntu-latest-clang: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: bazelbuild/setup-bazelisk@v3 + - uses: actions/cache@v4 + with: + path: "~/.cache/bazel" + key: bazel + - name: Install clang + run: | + wget https://apt.llvm.org/llvm.sh + chmod +x ./llvm.sh + sudo ./llvm.sh 17 + - name: Version + run: clang --version + - name: Building... + run: CC=clang++-17 bazelisk build //tests:units + - name: Testing... + run: CC=clang++-17 bazelisk test //tests:units + - name: Testing (asan)... + run: CC=clang++-17 bazelisk test --features=asan //tests:units diff --git a/.github/workflows/tests_windows.yml b/.github/workflows/tests_windows.yml new file mode 100644 index 00000000..48fbcdf1 --- /dev/null +++ b/.github/workflows/tests_windows.yml @@ -0,0 +1,35 @@ +name: Tests Windows + +on: + push: + branches: + - '**' + +jobs: + windows-latest-msvc: + runs-on: windows-latest + steps: + - uses: actions/checkout@v4 + - uses: bazelbuild/setup-bazelisk@v3 + - uses: actions/cache@v4 + with: + path: "~/.cache/bazel" + key: bazel + - name: Building... + run: bazelisk build //tests:units + - name: Testing... + run: bazelisk test //tests:units + + windows-latest-winlibs: + runs-on: windows-latest + steps: + - uses: actions/checkout@v4 + - uses: bazelbuild/setup-bazelisk@v3 + - uses: actions/cache@v4 + with: + path: "~/.cache/bazel" + key: bazel + - name: Build winlibs/clang... + run: bazelisk build --config=winlibs-clang //tests:units + - name: Build winlibs/gcc... + run: bazelisk build --config=winlibs-gcc //tests:units diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 00000000..e5cd7320 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "conf"] + path = conf + url = git@github.com:0-Sacha/conf.git diff --git a/buildbuddy.yaml b/buildbuddy.yaml index f8fcbba6..14e75bb8 100644 --- a/buildbuddy.yaml +++ b/buildbuddy.yaml @@ -15,4 +15,4 @@ actions: branches: - "*" bazel_commands: - - "test -s --config=buildbuddy --remote_header=x-buildbuddy-api-key=${BUILDBUDDY_WINDOWS_WSL} //:streamTests" + - "test -s --config=buildbuddy --remote_header=x-buildbuddy-api-key=${BUILDBUDDY_WINDOWS_WSL} //tests:units" diff --git a/conf b/conf new file mode 160000 index 00000000..6cc31a2b --- /dev/null +++ b/conf @@ -0,0 +1 @@ +Subproject commit 6cc31a2b5c9afbeef30af8bcc391e846fa12fe1f diff --git a/custom/BUILD.bazel b/custom/BUILD.bazel index 247112d4..ccbe9270 100644 --- a/custom/BUILD.bazel +++ b/custom/BUILD.bazel @@ -4,10 +4,10 @@ load("@hedron_compile_commands//:refresh_compile_commands.bzl", "refresh_compile_commands") refresh_compile_commands( - name = "compile_commands", + name = "compile_commands_tests", exclude_external_sources = True, exclude_headers = "external", targets = { - "//:stream": "", + "//tests:units": "", }, ) diff --git a/scripts/clang-tidy.sh b/scripts/clang-tidy.sh new file mode 100755 index 00000000..699a7fc5 --- /dev/null +++ b/scripts/clang-tidy.sh @@ -0,0 +1,3 @@ +#!/bin/bash + +./conf/linter/clang-tidy.sh //custom:compile_commands_tests --enable-headers From 2b7b5c323a77903a3ae7cb94cd90059577ddc4ee Mon Sep 17 00:00:00 2001 From: Sacha Bellier Date: Sun, 23 Mar 2025 17:59:33 +0100 Subject: [PATCH 19/42] wip: examples now run correctly --- .buildbuddy/workspace_status.ps1 | 2 +- examples/hello/BUILD.bazel | 2 +- src/stream/flog/backends/basic_logger.h | 4 +- src/stream/fmt/buf/fmt_write_manip.h | 4 +- src/stream/fmt/buf/write_manip.h | 12 +-- .../fmt/context/basic_context/basic_context.h | 4 +- .../basic_context/basic_context_parse_impl.h | 10 +-- .../basic_context/text_properties_manager.h | 4 +- .../text_properties_manager_impl.h | 10 +-- .../basic_formatter_executor.h | 6 +- .../format_text_properties_impl.h | 16 ++-- .../formatter_executor/formatter_args.h | 20 ++--- .../parser_executor/basic_parser_executor.h | 6 +- .../parse_text_properties_impl.h | 16 ++-- .../fmt/context/parser_executor/parser_args.h | 20 ++--- .../text_properties/text_properties_color.h | 4 +- .../text_properties/text_properties_style.h | 8 +- src/stream/json/json_objects.h | 6 +- src/stream/profiler/all_events.h | 2 +- src/stream/profiler/event_data.h | 4 +- src/stream/profiler/profiler.h | 4 +- .../profiler/profiler_event_creator.cpp | 2 +- src/stream/profiler/profiler_factory.cpp | 4 +- src/stream/profiler/profiler_factory.h | 2 +- .../profiler/profiler_json_serializers.h | 2 +- src/stream/profiler/profiler_macros.h | 2 +- src/stream/tester/test_suite/test_suite.cpp | 80 +++++++++--------- src/stream/tester/test_suite/test_suite.h | 82 +++++++++---------- 28 files changed, 172 insertions(+), 166 deletions(-) diff --git a/.buildbuddy/workspace_status.ps1 b/.buildbuddy/workspace_status.ps1 index a2c1a204..e6726f2b 100755 --- a/.buildbuddy/workspace_status.ps1 +++ b/.buildbuddy/workspace_status.ps1 @@ -8,7 +8,7 @@ # If the script exits with a non-zero code, it's considered as a failure # and the output will be discarded. -$ErrorActionPreference = "Stop" +$ErrorActionPreference = "stop" # Get the repository URL without credentials $repo_url = (git config --get remote.origin.url) -replace '//.*?:.*?@', '//' diff --git a/examples/hello/BUILD.bazel b/examples/hello/BUILD.bazel index f981b427..e4978637 100644 --- a/examples/hello/BUILD.bazel +++ b/examples/hello/BUILD.bazel @@ -4,7 +4,7 @@ load("@rules_cc//cc:defs.bzl", "cc_binary") cc_binary( name = "hello", - srcs = glob([ "*.h", "*.cpp" ]), + srcs = [ "main.cpp" ], includes = [ "" ], copts = select({ "@rules_cc//cc/compiler:msvc-cl": ["/std:latest"], diff --git a/src/stream/flog/backends/basic_logger.h b/src/stream/flog/backends/basic_logger.h index 5a34bb45..f1a48e41 100644 --- a/src/stream/flog/backends/basic_logger.h +++ b/src/stream/flog/backends/basic_logger.h @@ -49,11 +49,11 @@ namespace stream::flog::detail virtual ~BasicLoggerImpl() = default; public: - void SetSeverity(const SeverityValueType& severity) { m_Severity = severity; } + void set_severity(const SeverityValueType& severity) { m_Severity = severity; } void set_name(const std::string& name) { name_ = name; } void set_name(std::string&& name) { name_ = std::move(name); } void SetRealPattern(std::string_view pattern) { m_Pattern = pattern; } - void SetRealPatternStrmv(std::string&& pattern) { m_Pattern = std::move(pattern); } + void set_real_pattern_strmv(std::string&& pattern) { m_Pattern = std::move(pattern); } void SetPattern(std::string_view pattern) { m_Pattern = "{color}"; diff --git a/src/stream/fmt/buf/fmt_write_manip.h b/src/stream/fmt/buf/fmt_write_manip.h index 9af282c2..038ebb56 100644 --- a/src/stream/fmt/buf/fmt_write_manip.h +++ b/src/stream/fmt/buf/fmt_write_manip.h @@ -101,8 +101,8 @@ namespace stream::fmt::buf std::int32_t nb_digit_ = nb_digit; while (nb_digit_ > 0) { - buffer.set(char(std::fmod(i, 10)) + '0'); Manip(buffer).backward_force(); + buffer.set(char(std::fmod(i, 10)) + '0'); k /= 10; nb_digit_--; } @@ -154,8 +154,8 @@ namespace stream::fmt::buf std::int32_t k = digit_count + 1; while (--k != 0) { - buffer.set(lut[i & (0b1 << digitSize)]); Manip(buffer).backward_force(); + buffer.set(lut[i & (0b1 << digitSize)]); i = i >> digitSize; } SF_TRY(manip.forward(digit_count)); diff --git a/src/stream/fmt/buf/write_manip.h b/src/stream/fmt/buf/write_manip.h index dec65c41..4eb23a3f 100644 --- a/src/stream/fmt/buf/write_manip.h +++ b/src/stream/fmt/buf/write_manip.h @@ -72,8 +72,8 @@ namespace stream::fmt::buf SF_TRY(manip.forward(nb_digit)); while (i > 0) { - ManipIO(buffer).set(i % 10 + '0'); Manip(buffer).backward_force(); + ManipIO(buffer).set(i % 10 + '0'); i /= 10; } SF_TRY(manip.forward(nb_digit)); @@ -100,8 +100,8 @@ namespace stream::fmt::buf std::int32_t nb_digit_ = nb_digit; while (nb_digit_ > 0) { - buffer.set(char(std::fmod(k, 10)) + '0'); Manip(buffer).backward_force(); + buffer.set(char(std::fmod(k, 10)) + '0'); k /= 10; nb_digit_--; } @@ -122,13 +122,15 @@ namespace stream::fmt::buf template [[nodiscard]] constexpr std::expected fast_write_char_array(const CharInput* str, std::size_t size) { + if (size == 0) + return {}; + auto reserve = ManipIO(buffer).reserve(size); if (reserve.has_value() == false) return fast_write_char_array(str, Access(buffer).get_buffer_remaining_size()); - // TODO: Opti with bigger types - while (size-- != 0 && *str != 0) - ManipIO(buffer).pushback_force(*str++); + std::copy_n(str, size, buffer.current_pos); + buffer.current_pos += size; return {}; } diff --git a/src/stream/fmt/context/basic_context/basic_context.h b/src/stream/fmt/context/basic_context/basic_context.h index 11c048ba..52e7d448 100644 --- a/src/stream/fmt/context/basic_context/basic_context.h +++ b/src/stream/fmt/context/basic_context/basic_context.h @@ -25,7 +25,7 @@ namespace stream::fmt::context public: context_executor(detail::ITextPropertiesExecutor& text_properties_executor) : data{} - , TextManager{text_properties_executor} + , text_manager{text_properties_executor} {} virtual ~context_executor() = default; @@ -35,7 +35,7 @@ namespace stream::fmt::context public: detail::FormatData data; - detail::TextPropertiesManager TextManager; + detail::TextPropertiesManager text_manager; }; template diff --git a/src/stream/fmt/context/basic_context/basic_context_parse_impl.h b/src/stream/fmt/context/basic_context/basic_context_parse_impl.h index 969ab717..f7e14cae 100644 --- a/src/stream/fmt/context/basic_context/basic_context_parse_impl.h +++ b/src/stream/fmt/context/basic_context/basic_context_parse_impl.h @@ -60,17 +60,17 @@ namespace stream::fmt::context if (access.is_equal_to('C')) { SF_TRY(buf::Manip(fmtstream).forward()); - SF_TRY(executor.TextManager.parse_color(*this)); + SF_TRY(executor.text_manager.parse_color(*this)); } else if (access.is_equal_to('S')) { SF_TRY(buf::Manip(fmtstream).forward()); - SF_TRY(executor.TextManager.parse_style(*this)); + SF_TRY(executor.text_manager.parse_style(*this)); } else if (access.is_equal_to('F')) { SF_TRY(buf::Manip(fmtstream).forward()); - SF_TRY(executor.TextManager.parse_front(*this)); + SF_TRY(executor.text_manager.parse_front(*this)); } else if (access.is_equal_to('K')) @@ -340,7 +340,7 @@ namespace stream::fmt::context { detail::FormatData saveFormatData = executor.data; executor.data = detail::FormatData{}; - detail::TextProperties::Properties saveTextProperties = executor.TextManager.save(); + detail::TextProperties::Properties saveTextProperties = executor.text_manager.save(); if (buf::TestAccess(fmtstream).is_equal_to(':', '{')) { @@ -351,7 +351,7 @@ namespace stream::fmt::context SF_TRY(args_interface.run_type_at(formatIdx)); if (executor.data.keep_new_style == false) - { SF_TRY(executor.TextManager.reload(saveTextProperties)); } + { SF_TRY(executor.text_manager.reload(saveTextProperties)); } executor.data = saveFormatData; diff --git a/src/stream/fmt/context/basic_context/text_properties_manager.h b/src/stream/fmt/context/basic_context/text_properties_manager.h index 59693bd4..2f40ee7b 100644 --- a/src/stream/fmt/context/basic_context/text_properties_manager.h +++ b/src/stream/fmt/context/basic_context/text_properties_manager.h @@ -70,11 +70,11 @@ namespace stream::fmt::detail public: [[nodiscard]] std::expected reload_default() { - SF_TRY(reload_defaultColor()); + SF_TRY(reload_default_color()); SF_TRY(reload_default_style()); return reload_default_front(); } - [[nodiscard]] std::expected reload_defaultColor() + [[nodiscard]] std::expected reload_default_color() { SF_TRY(reload_default_color_fg()); return reload_default_color_bg(); diff --git a/src/stream/fmt/context/basic_context/text_properties_manager_impl.h b/src/stream/fmt/context/basic_context/text_properties_manager_impl.h index 4f555e1b..aff2b75f 100644 --- a/src/stream/fmt/context/basic_context/text_properties_manager_impl.h +++ b/src/stream/fmt/context/basic_context/text_properties_manager_impl.h @@ -93,19 +93,19 @@ namespace stream::fmt::detail if (color_bg.has_value() && color_fg.has_value()) { return ask_apply_color(detail::TextProperties::TextColor::BasicColor{color_fg.value(), color_bg.value()}); } else - { return reload_defaultColor(); } + { return reload_default_color(); } } else { if (color_fg.has_value()) { return ask_apply_color(color_fg.value()); } else - { return reload_defaultColor(); } + { return reload_default_color(); } } } } else - { return reload_defaultColor(); } + { return reload_default_color(); } return {}; } @@ -157,7 +157,7 @@ namespace stream::fmt::detail }; static constexpr std::pair, detail::TextProperties::TextStyle::Italic> styleItalic[] = { - {"italic", detail::TextProperties::TextStyle::Italic::Enable}, + {"italic", detail::TextProperties::TextStyle::Italic::enable}, {"n-italic", detail::TextProperties::TextStyle::Italic::Disable} }; @@ -173,7 +173,7 @@ namespace stream::fmt::detail {"n-blink", detail::TextProperties::TextStyle::Blink::Disable}}; static constexpr typename std::pair, detail::TextProperties::TextStyle::Inverted> styleInverted[] = { - {"inverted", detail::TextProperties::TextStyle::Inverted::Enable}, + {"inverted", detail::TextProperties::TextStyle::Inverted::enable}, {"n-inverted", detail::TextProperties::TextStyle::Inverted::Disable}, }; diff --git a/src/stream/fmt/context/formatter_executor/basic_formatter_executor.h b/src/stream/fmt/context/formatter_executor/basic_formatter_executor.h index deff9401..898ea0a4 100644 --- a/src/stream/fmt/context/formatter_executor/basic_formatter_executor.h +++ b/src/stream/fmt/context/formatter_executor/basic_formatter_executor.h @@ -39,7 +39,7 @@ namespace stream::fmt::context EndOfStringCharMode EndOfStringChar = EndOfStringCharMode::Optional; using context_executor::data; - using context_executor::TextManager; + using context_executor::text_manager; protected: [[nodiscard]] std::expected exec_raw_string(std::basic_string_view sv) override @@ -106,10 +106,10 @@ namespace stream::fmt::context { auto args_interface = detail::FormatterArgsInterface, Args...>(*this, std::forward(args)...); - detail::TextProperties::Properties saveTextProperties = TextManager.save(); + detail::TextProperties::Properties saveTextProperties = text_manager.save(); context::BasicContext context(*this, format, args_interface); SF_TRY(context.run()); - return TextManager.reload(saveTextProperties); + return text_manager.reload(saveTextProperties); } template diff --git a/src/stream/fmt/context/formatter_executor/format_text_properties_impl.h b/src/stream/fmt/context/formatter_executor/format_text_properties_impl.h index 5befd838..5e11a337 100644 --- a/src/stream/fmt/context/formatter_executor/format_text_properties_impl.h +++ b/src/stream/fmt/context/formatter_executor/format_text_properties_impl.h @@ -13,7 +13,7 @@ namespace stream::fmt { [[nodiscard]] static std::expected format(const detail::TextProperties::ResetProperties, FormatterExecutor& executor) { - return executor.TextManager.all_properties_reset(); + return executor.text_manager.all_properties_reset(); } }; @@ -22,7 +22,7 @@ namespace stream::fmt { [[nodiscard]] static std::expected format(const detail::TextProperties::TextColor::reset_color, FormatterExecutor& executor) { - return executor.TextManager.apply_color_reset(); + return executor.text_manager.apply_color_reset(); } }; @@ -31,7 +31,7 @@ namespace stream::fmt { [[nodiscard]] static std::expected format(const detail::TextProperties::TextStyle::reset_style, FormatterExecutor& executor) { - return executor.TextManager.apply_style_reset(); + return executor.text_manager.apply_style_reset(); } }; @@ -40,7 +40,7 @@ namespace stream::fmt { [[nodiscard]] static std::expected format(const detail::TextProperties::TextFront::reset_front, FormatterExecutor& executor) { - return executor.TextManager.apply_front_reset(); + return executor.text_manager.apply_front_reset(); } }; @@ -49,12 +49,12 @@ namespace stream::fmt //---------------------------------------// template - requires detail::TextPropertiesColorIsapply + requires detail::text_properties_color_is_apply struct FormatterType { [[nodiscard]] static std::expected format(const T& t, FormatterExecutor& executor) { - return executor.TextManager.ask_apply_color(t); + return executor.text_manager.ask_apply_color(t); } }; @@ -64,7 +64,7 @@ namespace stream::fmt { [[nodiscard]] static std::expected format(const T& t, FormatterExecutor& executor) { - return executor.TextManager.ask_apply_style(t); + return executor.text_manager.ask_apply_style(t); } }; @@ -74,7 +74,7 @@ namespace stream::fmt { [[nodiscard]] static std::expected format(const T& t, FormatterExecutor& executor) { - return executor.TextManager.ask_apply_front(t); + return executor.text_manager.ask_apply_front(t); } }; } diff --git a/src/stream/fmt/context/formatter_executor/formatter_args.h b/src/stream/fmt/context/formatter_executor/formatter_args.h index 551b64a6..e53e13fb 100644 --- a/src/stream/fmt/context/formatter_executor/formatter_args.h +++ b/src/stream/fmt/context/formatter_executor/formatter_args.h @@ -36,7 +36,7 @@ namespace stream::fmt::detail return std::unexpected(FMTResult::ArgsInterface_IndexOutOfBounds); } template - [[nodiscard]] inline std::expected GetConvertedTypeAt(std::int32_t) + [[nodiscard]] inline std::expected get_converted_type_at(std::int32_t) { return std::unexpected(FMTResult::ArgsInterface_IndexOutOfBounds); } @@ -73,15 +73,15 @@ namespace stream::fmt::detail public: template - [[nodiscard]] inline std::expected get_index_of_current_named_arg(buf::StreamView& format, std::int32_t beginSearchIndex) + [[nodiscard]] inline std::expected get_index_of_current_named_arg(buf::StreamView& format, std::int32_t begin_search_index) { if constexpr (detail::IsANamedArgs>::value) { - bool currentIsANamedArg = SF_TRY(buf::FMTParamsManip(format).next_is_named_args(m_Value.get_name())); - if (currentIsANamedArg) - return beginSearchIndex; + bool current_is_a_named_arg = SF_TRY(buf::FMTParamsManip(format).next_is_named_args(m_Value.get_name())); + if (current_is_a_named_arg) + return begin_search_index; } - return FormatterArgs::get_index_of_current_named_arg(format, beginSearchIndex + 1); + return FormatterArgs::get_index_of_current_named_arg(format, begin_search_index + 1); } public: @@ -94,7 +94,7 @@ namespace stream::fmt::detail public: template - [[nodiscard]] inline std::expected GetConvertedTypeAt(std::int32_t idx) + [[nodiscard]] inline std::expected get_converted_type_at(std::int32_t idx) { if (idx == 0) { @@ -103,7 +103,7 @@ namespace stream::fmt::detail else { return std::unexpected(FMTResult::ArgsInterface_InvalidConversion); } } - return FormatterArgs::template GetConvertedTypeAt(idx - 1); + return FormatterArgs::template get_converted_type_at(idx - 1); } }; @@ -144,11 +144,11 @@ namespace stream::fmt::detail public: [[nodiscard]] std::expected, FMTResult> get_string_at(std::int32_t idx) override { - return args_interface.template GetConvertedTypeAt>(idx); + return args_interface.template get_converted_type_at>(idx); } [[nodiscard]] std::expected get_int_at(std::int32_t idx) override { - return args_interface.template GetConvertedTypeAt(idx); + return args_interface.template get_converted_type_at(idx); } protected: diff --git a/src/stream/fmt/context/parser_executor/basic_parser_executor.h b/src/stream/fmt/context/parser_executor/basic_parser_executor.h index 0c7118dd..c07527a9 100644 --- a/src/stream/fmt/context/parser_executor/basic_parser_executor.h +++ b/src/stream/fmt/context/parser_executor/basic_parser_executor.h @@ -32,7 +32,7 @@ namespace stream::fmt::context buf::StreamView& istream; using context_executor::data; - using context_executor::TextManager; + using context_executor::text_manager; protected: [[nodiscard]] std::expected exec_raw_string(std::basic_string_view sv) override @@ -83,10 +83,10 @@ namespace stream::fmt::context { auto args_interface = detail::ParserArgsInterface, Args...>(*this, std::forward(args)...); - detail::TextProperties::Properties saveTextProperties = TextManager.save(); + detail::TextProperties::Properties saveTextProperties = text_manager.save(); context::BasicContext context(*this, format, args_interface); SF_TRY(context.run()); - return TextManager.reload(saveTextProperties); + return text_manager.reload(saveTextProperties); } template diff --git a/src/stream/fmt/context/parser_executor/parse_text_properties_impl.h b/src/stream/fmt/context/parser_executor/parse_text_properties_impl.h index 8e2168c9..48c51875 100644 --- a/src/stream/fmt/context/parser_executor/parse_text_properties_impl.h +++ b/src/stream/fmt/context/parser_executor/parse_text_properties_impl.h @@ -13,7 +13,7 @@ namespace stream::fmt { [[nodiscard]] static inline std::expected parse(detail::TextProperties::ResetProperties, ParserExecutor& executor) { - return executor.TextManager.all_properties_reset(); + return executor.text_manager.all_properties_reset(); } }; @@ -22,7 +22,7 @@ namespace stream::fmt { [[nodiscard]] static inline std::expected parse(detail::TextProperties::TextColor::reset_color, ParserExecutor& executor) { - return executor.TextManager.apply_color_reset(); + return executor.text_manager.apply_color_reset(); } }; @@ -31,7 +31,7 @@ namespace stream::fmt { [[nodiscard]] static inline std::expected parse(detail::TextProperties::TextStyle::reset_style, ParserExecutor& executor) { - return executor.TextManager.apply_style_reset(); + return executor.text_manager.apply_style_reset(); } }; @@ -40,7 +40,7 @@ namespace stream::fmt { [[nodiscard]] static inline std::expected parse(detail::TextProperties::TextFront::reset_front, ParserExecutor& executor) { - return executor.TextManager.apply_front_reset(); + return executor.text_manager.apply_front_reset(); } }; @@ -49,12 +49,12 @@ namespace stream::fmt //---------------------------------------// template - requires detail::TextPropertiesColorIsapply + requires detail::text_properties_color_is_apply struct ParserType { [[nodiscard]] static inline std::expected parse(T& t, ParserExecutor& executor) { - return executor.TextManager.ask_apply_color(t); + return executor.text_manager.ask_apply_color(t); } }; @@ -64,7 +64,7 @@ namespace stream::fmt { [[nodiscard]] static inline std::expected parse(T& t, ParserExecutor& executor) { - return executor.TextManager.ask_apply_style(t); + return executor.text_manager.ask_apply_style(t); } }; @@ -74,7 +74,7 @@ namespace stream::fmt { [[nodiscard]] static inline std::expected parse(T& t, ParserExecutor& executor) { - return executor.TextManager.ask_apply_front(t); + return executor.text_manager.ask_apply_front(t); } }; } diff --git a/src/stream/fmt/context/parser_executor/parser_args.h b/src/stream/fmt/context/parser_executor/parser_args.h index d9fa377a..af68175e 100644 --- a/src/stream/fmt/context/parser_executor/parser_args.h +++ b/src/stream/fmt/context/parser_executor/parser_args.h @@ -36,7 +36,7 @@ namespace stream::fmt::detail return std::unexpected(FMTResult::ArgsInterface_IndexOutOfBounds); } template - [[nodiscard]] inline std::expected GetConvertedTypeAt(std::int32_t) + [[nodiscard]] inline std::expected get_converted_type_at(std::int32_t) { return std::unexpected(FMTResult::ArgsInterface_IndexOutOfBounds); } @@ -73,15 +73,15 @@ namespace stream::fmt::detail public: template - [[nodiscard]] inline std::expected get_index_of_current_named_arg(buf::StreamView& format, std::int32_t beginSearchIndex) + [[nodiscard]] inline std::expected get_index_of_current_named_arg(buf::StreamView& format, std::int32_t begin_search_index) { if constexpr (detail::IsANamedArgs>::value) { - bool currentIsANamedArg = SF_TRY(buf::FMTParamsManip(format).next_is_named_args(m_Value.get_name())); - if (currentIsANamedArg) - return beginSearchIndex; + bool current_is_a_named_arg = SF_TRY(buf::FMTParamsManip(format).next_is_named_args(m_Value.get_name())); + if (current_is_a_named_arg) + return begin_search_index; } - return ParserArgs::get_index_of_current_named_arg(format, beginSearchIndex + 1); + return ParserArgs::get_index_of_current_named_arg(format, begin_search_index + 1); } public: @@ -93,7 +93,7 @@ namespace stream::fmt::detail public: template - [[nodiscard]] inline std::expected GetConvertedTypeAt(std::int32_t idx) + [[nodiscard]] inline std::expected get_converted_type_at(std::int32_t idx) { if (idx == 0) { @@ -102,7 +102,7 @@ namespace stream::fmt::detail else { return std::unexpected(FMTResult::ArgsInterface_InvalidConversion); } } - return ParserArgs::template GetConvertedTypeAt(idx - 1); + return ParserArgs::template get_converted_type_at(idx - 1); } }; @@ -144,11 +144,11 @@ namespace stream::fmt::detail public: [[nodiscard]] std::expected, FMTResult> get_string_at(std::int32_t idx) override { - return args_interface.template GetConvertedTypeAt>(idx); + return args_interface.template get_converted_type_at>(idx); } [[nodiscard]] std::expected get_int_at(std::int32_t idx) override { - return args_interface.template GetConvertedTypeAt(idx); + return args_interface.template get_converted_type_at(idx); } protected: diff --git a/src/stream/fmt/text_properties/text_properties_color.h b/src/stream/fmt/text_properties/text_properties_color.h index b4186c72..dfea46e6 100644 --- a/src/stream/fmt/text_properties/text_properties_color.h +++ b/src/stream/fmt/text_properties/text_properties_color.h @@ -536,7 +536,7 @@ namespace stream::fmt::detail }; template - struct TextPropertiesColorIsapplyType + struct TextPropertiesColorIsApplyType { using BaseType = get_base_type; static constexpr bool value = std::is_same_v || std::is_same_v || @@ -548,5 +548,5 @@ namespace stream::fmt::detail }; template - concept TextPropertiesColorIsapply = TextPropertiesColorIsapplyType::value; + concept text_properties_color_is_apply = TextPropertiesColorIsApplyType::value; } diff --git a/src/stream/fmt/text_properties/text_properties_style.h b/src/stream/fmt/text_properties/text_properties_style.h index cffe3595..7cd54bbb 100644 --- a/src/stream/fmt/text_properties/text_properties_style.h +++ b/src/stream/fmt/text_properties/text_properties_style.h @@ -32,7 +32,7 @@ namespace stream::fmt::detail enum class TextProperties::TextStyle::Italic : std::uint8_t { - Enable = 3, + enable = 3, Disable = 23 }; @@ -54,7 +54,7 @@ namespace stream::fmt::detail enum class TextProperties::TextStyle::Inverted : std::uint8_t { - Enable = 7, + enable = 7, Disable = 27 }; @@ -264,7 +264,7 @@ namespace stream::fmt::detail::OLD Intensity_Dim = static_cast(TextProperties::TextStyle::Intensity::Dim), Intensity_Normal = static_cast(TextProperties::TextStyle::Intensity::Normal), - Italic_Enable = static_cast(TextProperties::TextStyle::Italic::Enable), + Italic_Enable = static_cast(TextProperties::TextStyle::Italic::enable), Italic_Disable = static_cast(TextProperties::TextStyle::Italic::Disable), Underline_Underlined = static_cast(TextProperties::TextStyle::Underline::Underlined), @@ -276,7 +276,7 @@ namespace stream::fmt::detail::OLD Blink_FastBlink = static_cast(TextProperties::TextStyle::Blink::FastBlink), Blink_Disable = static_cast(TextProperties::TextStyle::Blink::Disable), - Inverted_Enable = static_cast(TextProperties::TextStyle::Inverted::Enable), + Inverted_Enable = static_cast(TextProperties::TextStyle::Inverted::enable), Inverted_Disable = static_cast(TextProperties::TextStyle::Inverted::Disable), Ideogram_Underlined = static_cast(TextProperties::TextStyle::Ideogram::Underlined), diff --git a/src/stream/json/json_objects.h b/src/stream/json/json_objects.h index 8ed5d515..cf8a3f1a 100644 --- a/src/stream/json/json_objects.h +++ b/src/stream/json/json_objects.h @@ -171,8 +171,8 @@ namespace stream::json std::unordered_map> Objects; public: - void Add(const std::string& name, std::unique_ptr&& object) { Objects.insert({name, std::move(object)}); } - void Add(std::string&& name, std::unique_ptr&& object) { Objects.insert({std::move(name), std::move(object)}); } + void add(const std::string& name, std::unique_ptr&& object) { Objects.insert({name, std::move(object)}); } + void add(std::string&& name, std::unique_ptr&& object) { Objects.insert({std::move(name), std::move(object)}); } JsonObject& get(const std::string_view subObject) override { try @@ -205,7 +205,7 @@ namespace stream::json std::vector> Objects; public: - void Add(std::unique_ptr&& object) { Objects.emplace_back(std::move(object)); } + void add(std::unique_ptr&& object) { Objects.emplace_back(std::move(object)); } JsonObject& get(const std::size_t index) override { return *Objects[index]; } public: diff --git a/src/stream/profiler/all_events.h b/src/stream/profiler/all_events.h index 2a11d59a..b315bf98 100644 --- a/src/stream/profiler/all_events.h +++ b/src/stream/profiler/all_events.h @@ -19,7 +19,7 @@ namespace stream::profiler public: void start() { trigger(); } - void Stop() { info.Duration = profiler::get_microseconds() - info.TimeOfEvent; } + void stop() { info.Duration = profiler::get_microseconds() - info.TimeOfEvent; } }; class SampleEvent : public Event diff --git a/src/stream/profiler/event_data.h b/src/stream/profiler/event_data.h index 9c4df2ae..6b357f34 100644 --- a/src/stream/profiler/event_data.h +++ b/src/stream/profiler/event_data.h @@ -10,7 +10,7 @@ namespace stream::profiler virtual ~EventData() = default; public: - virtual void ToJson(json::detail::JsonFormatter& formatter) const = 0; + virtual void to_json(json::detail::JsonFormatter& formatter) const = 0; virtual void FromJson(json::detail::JsonParser& parser) = 0; }; @@ -20,7 +20,7 @@ namespace stream::profiler ~EventDataJsonObject() override = default; public: - void ToJson(json::detail::JsonFormatter& formatter) const override { json::JsonSerializer::format(data, formatter); } + void to_json(json::detail::JsonFormatter& formatter) const override { json::JsonSerializer::format(data, formatter); } void FromJson(json::detail::JsonParser& parser) override { json::JsonSerializer::parse(data, parser); } json::JsonStructObject data; }; diff --git a/src/stream/profiler/profiler.h b/src/stream/profiler/profiler.h index adfa5dba..ffd8549a 100644 --- a/src/stream/profiler/profiler.h +++ b/src/stream/profiler/profiler.h @@ -25,8 +25,8 @@ namespace stream::profiler ~Profiler() {} public: - void add_event(const Event& event) { add_event_info(event.info); } - void add_event_info(const EventInfo& eventInfo) { events.push_back(eventInfo); } + void add_event(const Event& event) { add_event_info(event.info); } + void add_event_info(const EventInfo& eventInfo) { events.push_back(eventInfo); } inline stream::flog::BasicLogger& get_logger() { return logger; } public: diff --git a/src/stream/profiler/profiler_event_creator.cpp b/src/stream/profiler/profiler_event_creator.cpp index 6db6c6b4..2cde9e34 100644 --- a/src/stream/profiler/profiler_event_creator.cpp +++ b/src/stream/profiler/profiler_event_creator.cpp @@ -5,7 +5,7 @@ namespace stream::profiler { ScopeProfile::~ScopeProfile() { - Stop(); + stop(); double millis = info.Duration / 1000; double sec = millis / 1000; diff --git a/src/stream/profiler/profiler_factory.cpp b/src/stream/profiler/profiler_factory.cpp index 4ecbb5cb..728e4494 100644 --- a/src/stream/profiler/profiler_factory.cpp +++ b/src/stream/profiler/profiler_factory.cpp @@ -5,9 +5,9 @@ namespace stream::profiler { - void ProfilerFactory::ToJson(Profiler& profiler, std::filesystem::path path) + void ProfilerFactory::to_json(Profiler& profiler, std::filesystem::path path) { - profiler.profiler_duration.Stop(); + profiler.profiler_duration.stop(); profiler.events[0] = profiler.profiler_duration.info; if (path == "") path = std::string(profiler.name) + ".json"; diff --git a/src/stream/profiler/profiler_factory.h b/src/stream/profiler/profiler_factory.h index 1b3b4bdb..504112e3 100644 --- a/src/stream/profiler/profiler_factory.h +++ b/src/stream/profiler/profiler_factory.h @@ -9,6 +9,6 @@ namespace stream::profiler class ProfilerFactory { public: - static void ToJson(Profiler& profiler, std::filesystem::path path = ""); + static void to_json(Profiler& profiler, std::filesystem::path path = ""); }; } diff --git a/src/stream/profiler/profiler_json_serializers.h b/src/stream/profiler/profiler_json_serializers.h index cef4c6fb..88141bff 100644 --- a/src/stream/profiler/profiler_json_serializers.h +++ b/src/stream/profiler/profiler_json_serializers.h @@ -33,7 +33,7 @@ namespace stream::json template <> struct JsonSerializer { - static inline void format(const profiler::EventData& t, detail::JsonFormatter& formatter) { t.ToJson(formatter); } + static inline void format(const profiler::EventData& t, detail::JsonFormatter& formatter) { t.to_json(formatter); } static inline void parse(profiler::EventData& t, detail::JsonParser& parser) { t.FromJson(parser); } }; diff --git a/src/stream/profiler/profiler_macros.h b/src/stream/profiler/profiler_macros.h index 7d98c7cf..041f096b 100644 --- a/src/stream/profiler/profiler_macros.h +++ b/src/stream/profiler/profiler_macros.h @@ -6,7 +6,7 @@ #define SFP_PROFILE_FUNCTION_FMT(...) \ stream::profiler::ScopeProfile profile##__LINE__(stream::profiler::Profiler::get_instance(), \ stream::profiler::fmt::format_string(__VA_ARGS__), "Function") -#define SFP_SAVE_DEFAULT_PROFILER() stream::profiler::ProfilerFactory::ToJson(stream::profiler::Profiler::get_instance()) +#define SFP_SAVE_DEFAULT_PROFILER() stream::profiler::ProfilerFactory::to_json(stream::profiler::Profiler::get_instance()) #else // STREAMFORMAT_PROFILING_ENABLE diff --git a/src/stream/tester/test_suite/test_suite.cpp b/src/stream/tester/test_suite/test_suite.cpp index 202364fd..13137f79 100644 --- a/src/stream/tester/test_suite/test_suite.cpp +++ b/src/stream/tester/test_suite/test_suite.cpp @@ -9,10 +9,10 @@ namespace stream::tester detail::TestStatusBank status; for (auto& [name, test_suite] : test_suites) - status.Add(test_suite->exec_all_tests()); + status.add(test_suite->exec_all_tests()); flog::BasicLogger logger("TestSuite"); - if (status.IsAllOk()) + if (status.is_all_ok()) logger.info("{C:white}RESULT => {C:+black}{}", status); else logger.error("{C:white}RESULT => {C:+black}{}", status); @@ -25,7 +25,10 @@ namespace stream::tester::detail { TestStatusBank TestSuite::exec_all_tests() { - if (parent == nullptr) profiler = new profiler::Profiler("TestSuite_" + name); + if (parent == nullptr) + profiler = new profiler::Profiler("TestSuite_" + name); + else + profiler = &get_profiler(); init_logger(); logger.info("{C:+black}{}", "BEGIN"); @@ -38,27 +41,27 @@ namespace stream::tester::detail for (auto& [name, test] : tests) { first_test_suite = false; - profiler::DurationEvent currentTestDuration(test->name, "Profile"); - TestStatus testStatus = TestStatus::Fail; - currentTestDuration.start(); - if (TestSuitesManager::PerformanceTest.Enable == false) - testStatus = test->run(); + profiler::DurationEvent current_test_duration(test->name, "Profile"); + TestStatus test_status = TestStatus::Fail; + current_test_duration.start(); + if (TestSuitesManager::performance_test.enable == false) + test_status = test->run(); else { - for (std::uint32_t i = 0; i < TestSuitesManager::PerformanceTest.NbSamples; ++i) + for (std::uint32_t i = 0; i < TestSuitesManager::performance_test.nb_samples; ++i) { - testStatus = test->run(); - if (testStatus != TestStatus::Ok) break; + test_status = test->run(); + if (test_status != TestStatus::Ok) break; } } - currentTestDuration.Stop(); - if (testStatus != TestStatus::Ok) + current_test_duration.stop(); + if (test_status != TestStatus::Ok) {} - test_suite_status.AddTestStatus(testStatus); - logger.debug("{} -> {}", testStatus, name); - profiler->add_event(currentTestDuration); + test_suite_status.AddTestStatus(test_status); + logger.debug("{} -> {}", test_status, name); + profiler->add_event(current_test_duration); } - tests_duration.Stop(); + tests_duration.stop(); profiler::DurationEvent groupsDuration("Groups", "Profile"); groupsDuration.start(); @@ -68,22 +71,22 @@ namespace stream::tester::detail first_test_suite = false; else std::cout << std::endl; - test_suite_status.Add(test_suite->exec_all_tests()); + test_suite_status.add(test_suite->exec_all_tests()); } - groupsDuration.Stop(); - test_suite_duration.Stop(); + groupsDuration.stop(); + test_suite_duration.stop(); profiler->add_event(tests_duration); profiler->add_event(groupsDuration); profiler->add_event(test_suite_duration); - if (test_suite_status.IsAllOk()) + if (test_suite_status.is_all_ok()) logger.info("{C:+black}{}", test_suite_status); else logger.error("{C:+black}{}", test_suite_status); if (parent == nullptr) { - profiler::ProfilerFactory::ToJson(*profiler); + profiler::ProfilerFactory::to_json(*profiler); delete profiler; } @@ -94,32 +97,32 @@ namespace stream::tester::detail { if (TestSuitesManager::verbose == false) { - logger.SetSeverity(flog::LogSeverity::Debug); - test_logger.SetSeverity(flog::LogSeverity::Debug); + logger.set_severity(flog::LogSeverity::Debug); + test_logger.set_severity(flog::LogSeverity::Debug); } else { - logger.SetSeverity(flog::LogSeverity::Trace); - test_logger.SetSeverity(flog::LogSeverity::Trace); + logger.set_severity(flog::LogSeverity::Trace); + test_logger.set_severity(flog::LogSeverity::Trace); } - std::string timePattern = ""; - if (TestSuitesManager::PrintTime) timePattern = "[{T:pattern='%h:%m:%s:%ms'}] "; + std::string time_pattern = ""; + if (TestSuitesManager::print_time) time_pattern = "[{T:pattern='%h:%m:%s:%ms'}] "; if (parent == nullptr) { logger.set_name(name); - logger.SetRealPattern("{C:+black}" + timePattern + "{name} >> {color}{data}"); + logger.SetRealPattern("{C:+black}" + time_pattern + "{name} >> {color}{data}"); test_logger.set_name(name + ".{test_name}"); - test_logger.SetRealPattern("{C:+black}" + timePattern + "{name} >> {color}{data}"); + test_logger.SetRealPattern("{C:+black}" + time_pattern + "{name} >> {color}{data}"); } else { std::string correctedName = get_corrected_size_name(); logger.set_name(correctedName); - logger.SetRealPatternStrmv("{C:+black}" + timePattern + "{name} >> {color}{data}"); + logger.set_real_pattern_strmv("{C:+black}" + time_pattern + "{name} >> {color}{data}"); test_logger.set_name(correctedName + ".{test_name}"); - test_logger.SetRealPatternStrmv("{C:+black}" + timePattern + "{name} >> {color}{data}"); + test_logger.set_real_pattern_strmv("{C:+black}" + time_pattern + "{name} >> {color}{data}"); } } @@ -132,23 +135,24 @@ namespace stream::tester::detail std::string TestSuite::get_corrected_size_name() { if (parent == nullptr) return name; - std::size_t biggestName = 0; + std::size_t biggest_name = 0; for (auto& [name, test_suite] : parent->test_suites_linked) { std::size_t tmp = test_suite->name.size(); - if (tmp > biggestName) biggestName = tmp; + if (tmp > biggest_name) biggest_name = tmp; } std::string res = get_full_name(); - biggestName -= name.size(); - res.reserve(res.size() + biggestName); - for (std::uint32_t i = 0; i < biggestName; ++i) + biggest_name -= name.size(); + res.reserve(res.size() + biggest_name); + for (std::uint32_t i = 0; i < biggest_name; ++i) res.push_back(' '); return res; } profiler::Profiler& TestSuite::get_profiler() { - if (parent == nullptr) return *profiler; + if (parent == nullptr) + return *profiler; return parent->get_profiler(); } } diff --git a/src/stream/tester/test_suite/test_suite.h b/src/stream/tester/test_suite/test_suite.h index 651a8c9f..06586b3b 100644 --- a/src/stream/tester/test_suite/test_suite.h +++ b/src/stream/tester/test_suite/test_suite.h @@ -70,22 +70,22 @@ namespace stream::tester::detail { void Reset() { - testsDone = 0; - testsOk = 0; - testsFail = 0; + tests_done = 0; + tests_ok = 0; + tests_failed = 0; testsCrash = 0; } void AddTestStatus(TestStatus status) { - testsDone++; + tests_done++; switch (status) { case TestStatus::Ok: - testsOk++; + tests_ok++; break; case TestStatus::Fail: - testsFail++; + tests_failed++; break; case TestStatus::Crash: testsCrash++; @@ -93,21 +93,21 @@ namespace stream::tester::detail } } - void Add(TestStatusBank status) + void add(TestStatusBank status) { - testsDone += status.testsDone; - testsOk += status.testsOk; - testsFail += status.testsFail; + tests_done += status.tests_done; + tests_ok += status.tests_ok; + tests_failed += status.tests_failed; testsCrash += status.testsCrash; } - bool IsAllOk() { return testsDone == testsOk && testsCrash == 0 && testsFail == 0; } + bool is_all_ok() { return tests_done == tests_ok && testsCrash == 0 && tests_failed == 0; } - std::uint32_t ErrorStatus() { return testsDone - testsOk; } + std::uint32_t ErrorStatus() { return tests_done - tests_ok; } - std::uint32_t testsDone = 0; - std::uint32_t testsOk = 0; - std::uint32_t testsFail = 0; + std::uint32_t tests_done = 0; + std::uint32_t tests_ok = 0; + std::uint32_t tests_failed = 0; std::uint32_t testsCrash = 0; }; @@ -115,15 +115,15 @@ namespace stream::tester::detail } namespace stream::tester { - struct PerformanceTestData + struct performance_testData { - bool Enable = false; - std::uint32_t NbSamples = 10; + bool enable = false; + std::uint32_t nb_samples = 10; }; - struct ConcurenceSpecificationData + struct ConcurrencySpecificationData { - bool Enable = false; + bool enable = false; }; class TestSuitesManager @@ -133,19 +133,19 @@ namespace stream::tester static inline std::unordered_map test_suites; public: - static inline bool verbose = false; - static inline bool PrintTime = false; - static inline PerformanceTestData PerformanceTest = PerformanceTestData{}; - static inline ConcurenceSpecificationData ConcurenceSpecification = ConcurenceSpecificationData{}; + static inline bool verbose = false; + static inline bool print_time = false; + static inline performance_testData performance_test = performance_testData{}; + static inline ConcurrencySpecificationData concurrency_specification = ConcurrencySpecificationData{}; }; } namespace stream::tester::detail { struct TestSuiteData { - bool Redirect_stdout = false; - bool Redirect_stdin = false; - bool Redirect_stderr = false; + bool redirect_stdout = false; + bool redirect_stdin = false; + bool redirect_stderr = false; }; class TestSuite @@ -181,8 +181,8 @@ namespace stream::tester::detail void init_logger(); private: - std::string get_full_name(); - std::string get_corrected_size_name(); + std::string get_full_name(); + std::string get_corrected_size_name(); profiler::Profiler& get_profiler(); public: @@ -232,28 +232,28 @@ namespace stream::fmt template struct FormatterType { - [[nodiscard]] static std::expected format(const stream::tester::detail::TestStatusBank& statusBank, FormatterExecutor& executor) + [[nodiscard]] static std::expected format(const stream::tester::detail::TestStatusBank& status_bank, FormatterExecutor& executor) { - SF_TRY(buf::WriteManip(executor.ostream).fast_write_string_literal("testsDone ")); - SF_TRY(executor.run("{:C:white}", statusBank.testsDone)); + SF_TRY(buf::WriteManip(executor.ostream).fast_write_string_literal("tests_done ")); + SF_TRY(executor.run("{:C:white}", status_bank.tests_done)); SF_TRY(buf::WriteManip(executor.ostream).fast_write_string_literal(" | testsOK ")); - if (statusBank.testsOk == statusBank.testsDone) - { SF_TRY(executor.run("{:C:green}", statusBank.testsOk)); } + if (status_bank.tests_ok == status_bank.tests_done) + { SF_TRY(executor.run("{:C:green}", status_bank.tests_ok)); } else - { SF_TRY(executor.run("{:C:yellow}", statusBank.testsOk)); } + { SF_TRY(executor.run("{:C:yellow}", status_bank.tests_ok)); } SF_TRY(buf::WriteManip(executor.ostream).fast_write_string_literal(" | testsFAIL ")); - if (statusBank.testsFail == 0) - { SF_TRY(executor.run("{:C:green}", statusBank.testsFail)); } + if (status_bank.tests_failed == 0) + { SF_TRY(executor.run("{:C:green}", status_bank.tests_failed)); } else - { SF_TRY(executor.run("{:C:red}", statusBank.testsFail)); } + { SF_TRY(executor.run("{:C:red}", status_bank.tests_failed)); } SF_TRY(buf::WriteManip(executor.ostream).fast_write_string_literal(" | TestCrash ")); - if (statusBank.testsCrash == 0) - { SF_TRY(executor.run("{:C:green}", statusBank.testsCrash)); } + if (status_bank.testsCrash == 0) + { SF_TRY(executor.run("{:C:green}", status_bank.testsCrash)); } else - { SF_TRY(executor.run("{:C:magenta}", statusBank.testsCrash)); } + { SF_TRY(executor.run("{:C:magenta}", status_bank.testsCrash)); } return {}; } From 7990cc911ad468cb867590c99982b0d7fdf738d2 Mon Sep 17 00:00:00 2001 From: Sacha Bellier Date: Sun, 23 Mar 2025 18:21:00 +0100 Subject: [PATCH 20/42] fix: integer write --- src/stream/fmt/buf/fmt_write_manip.h | 2 +- src/stream/tester/test_suite/basic_test.h | 76 ++++++++++----------- src/stream/tester/test_suite/test_suite.cpp | 10 +-- src/stream/tester/test_suite/test_suite.h | 70 +++++++++---------- src/stream/tester/tests_macros.h | 6 +- tests/BUILD.bazel | 2 +- 6 files changed, 83 insertions(+), 83 deletions(-) diff --git a/src/stream/fmt/buf/fmt_write_manip.h b/src/stream/fmt/buf/fmt_write_manip.h index 038ebb56..3948011e 100644 --- a/src/stream/fmt/buf/fmt_write_manip.h +++ b/src/stream/fmt/buf/fmt_write_manip.h @@ -52,8 +52,8 @@ namespace stream::fmt::buf std::int32_t nb_digit_ = nb_digit; while (nb_digit_ > 0) { + Manip(buffer).backward_force(); buffer.set(i % 10 + '0'); - SF_TRY(Manip(buffer).backward(nb_digit)); i /= 10; nb_digit_--; } diff --git a/src/stream/tester/test_suite/basic_test.h b/src/stream/tester/test_suite/basic_test.h index d7b54382..0a72e22c 100644 --- a/src/stream/tester/test_suite/basic_test.h +++ b/src/stream/tester/test_suite/basic_test.h @@ -12,108 +12,108 @@ namespace stream::tester::detail using FuncType = std::function; public: - TestFunction(std::string&& name, TestSuite& link, FuncType func, const fmt::detail::FileLocation& location) - : Test(std::move(name), link, location) - , Func(func) + TestFunction(std::string_view name, TestSuite& link, FuncType func_, const fmt::detail::FileLocation& location) + : Test(name, link, location) + , func(func_) { - Link.tests.insert({name, this}); + link.tests.insert({std::string{name}, this}); } ~TestFunction() override = default; protected: - TestStatus RunImpl() override + TestStatus run_impl() override { - Func(*this); - return TestStatus::Ok; + func(*this); + return TestStatus::ok; } public: - void TestAssert(bool assert, const std::string_view assertView, int line); + void test_assert(bool assert, const std::string_view assertView, int line); template - void TestEq(T result, std::convertible_to auto expected, std::string_view testView, int line); + void test_eq(T result, std::convertible_to auto expected, std::string_view testView, int line); template - void TestNotEq(T result, std::convertible_to auto notExpected, std::string_view testView, int line); + void test_not_eq(T result, std::convertible_to auto notExpected, std::string_view testView, int line); template - void TestEq(std::expected result, std::convertible_to auto expected, std::string_view testView, int line); + void test_eq(std::expected result, std::convertible_to auto expected, std::string_view testView, int line); template - void TestNotEq(std::expected result, std::convertible_to auto notExpected, std::string_view testView, int line); + void test_not_eq(std::expected result, std::convertible_to auto notExpected, std::string_view testView, int line); template - void AssertExpected(std::expected result, std::string_view testView, int line); + void assert_expected(std::expected result, std::string_view testView, int line); template - void AssertOptional(std::optional result, std::string_view testView, int line); + void assert_optional(std::optional result, std::string_view testView, int line); public: - FuncType Func; + FuncType func; }; template - void TestFunction::TestEq(T result, std::convertible_to auto expected, std::string_view testView, [[maybe_unused]] int line) + void TestFunction::test_eq(T result, std::convertible_to auto expected, std::string_view testView, [[maybe_unused]] int line) { T expected_as_T = static_cast(expected); if (result != expected_as_T) { - Link.test_logger.error("{C:red}{} return {} instead of {}", testView, result, expected, FORMAT_SV("test_name", name)).value(); + link.test_logger.error("{C:red}{} return {} instead of {}", testView, result, expected, FORMAT_SV("test_name", name)).value(); throw TestFailure{}; } - Link.test_logger.trace("{C:green}{} return {}", testView, result, FORMAT_SV("test_name", name)).value(); + link.test_logger.trace("{C:green}{} return {}", testView, result, FORMAT_SV("test_name", name)).value(); } template - void TestFunction::TestNotEq(T result, std::convertible_to auto notExpected, std::string_view testView, [[maybe_unused]] int line) + void TestFunction::test_not_eq(T result, std::convertible_to auto notExpected, std::string_view testView, [[maybe_unused]] int line) { if (result == static_cast(notExpected)) { - Link.test_logger.error("{C:red}{} return {} but that result was prohibited", testView, result, FORMAT_SV("test_name", name)).value(); + link.test_logger.error("{C:red}{} return {} but that result was prohibited", testView, result, FORMAT_SV("test_name", name)).value(); throw TestFailure{}; } - Link.test_logger.trace("{C:green}{} return {}", testView, result, FORMAT_SV("test_name", name)).value(); + link.test_logger.trace("{C:green}{} return {}", testView, result, FORMAT_SV("test_name", name)).value(); } - inline void TestFunction::TestAssert(bool assert, std::string_view assertView, [[maybe_unused]] int line) + inline void TestFunction::test_assert(bool assert, std::string_view assertView, [[maybe_unused]] int line) { if (assert == false) { - Link.test_logger.error("{C:red}ASSERT FAILED : {}", assertView, FORMAT_SV("test_name", name)).value(); + link.test_logger.error("{C:red}ASSERT FAILED : {}", assertView, FORMAT_SV("test_name", name)).value(); throw TestFailure{}; } - Link.test_logger.trace("{C:green}ASSERT SUCCED : {}", assertView, FORMAT_SV("test_name", name)).value(); + link.test_logger.trace("{C:green}ASSERT SUCCED : {}", assertView, FORMAT_SV("test_name", name)).value(); } template - void TestFunction::TestEq(std::expected result, std::convertible_to auto expected, std::string_view testView, [[maybe_unused]] int line) + void TestFunction::test_eq(std::expected result, std::convertible_to auto expected, std::string_view testView, [[maybe_unused]] int line) { if (result.has_value()) - TestEq(result.value(), expected, testView, line); + test_eq(result.value(), expected, testView, line); else - AssertExpected(result, testView, line); + assert_expected(result, testView, line); } template - void TestFunction::TestNotEq(std::expected result, std::convertible_to auto notExpected, std::string_view testView, [[maybe_unused]] int line) + void TestFunction::test_not_eq(std::expected result, std::convertible_to auto notExpected, std::string_view testView, [[maybe_unused]] int line) { if (result.has_value()) - TestEq(result.value(), notExpected, testView, line); + test_eq(result.value(), notExpected, testView, line); else - AssertExpected(result, testView, line); + assert_expected(result, testView, line); } template - void TestFunction::AssertExpected(std::expected result, std::string_view testView, int line) + void TestFunction::assert_expected(std::expected result, std::string_view testView, int line) { if (result.has_value() == false) { - Link.test_logger.error("{C:red}{} return an error: {}", testView, result.error(), FORMAT_SV("test_name", name)).value(); + link.test_logger.error("{C:red}{} return an error: {}", testView, result.error(), FORMAT_SV("test_name", name)).value(); throw TestFailure{}; } } template - void TestFunction::AssertOptional(std::optional result, std::string_view testView, int line) + void TestFunction::assert_optional(std::optional result, std::string_view testView, int line) { if (result.has_value() == false) { - Link.test_logger.error("{C:red}{} didn't return any value", testView, FORMAT_SV("test_name", name)).value(); + link.test_logger.error("{C:red}{} didn't return any value", testView, FORMAT_SV("test_name", name)).value(); throw TestFailure{}; } } @@ -130,8 +130,8 @@ namespace stream::tester::detail STREAMFORMAT_TESTINTERNAL_FUNC_CREATE(TestSuiteName, TestName); \ void STREAMFORMAT_TESTINTERNAL_FUNC_EXEC_NAME(TestSuiteName, TestName)(stream::tester::detail::TestFunction & link) -#define SFT_ASSERT(Test) link.TestAssert(Test, #Test, __LINE__) -#define SFT_EQ(Test, Expected) link.TestEq(Test, Expected, #Test, __LINE__) -#define SFT_NEQ(Test, NotExpected) link.TestNotEq(Test, NotExpected, #Test, __LINE__) +#define SFT_ASSERT(Test) link.test_assert(Test, #Test, __LINE__) +#define SFT_EQ(Test, Expected) link.test_eq(Test, Expected, #Test, __LINE__) +#define SFT_NEQ(Test, NotExpected) link.test_not_eq(Test, NotExpected, #Test, __LINE__) -#define SFT_EXPECTED_VALUE(Test) link.AssertExpected(Test, #Test, __LINE__) +#define SFT_EXPECTED_VALUE(Test) link.assert_expected(Test, #Test, __LINE__) diff --git a/src/stream/tester/test_suite/test_suite.cpp b/src/stream/tester/test_suite/test_suite.cpp index 13137f79..5f94bede 100644 --- a/src/stream/tester/test_suite/test_suite.cpp +++ b/src/stream/tester/test_suite/test_suite.cpp @@ -17,7 +17,7 @@ namespace stream::tester else logger.error("{C:white}RESULT => {C:+black}{}", status); - return status.ErrorStatus(); + return status.error_status(); } } @@ -42,7 +42,7 @@ namespace stream::tester::detail { first_test_suite = false; profiler::DurationEvent current_test_duration(test->name, "Profile"); - TestStatus test_status = TestStatus::Fail; + TestStatus test_status = TestStatus::fail; current_test_duration.start(); if (TestSuitesManager::performance_test.enable == false) test_status = test->run(); @@ -51,13 +51,13 @@ namespace stream::tester::detail for (std::uint32_t i = 0; i < TestSuitesManager::performance_test.nb_samples; ++i) { test_status = test->run(); - if (test_status != TestStatus::Ok) break; + if (test_status != TestStatus::ok) break; } } current_test_duration.stop(); - if (test_status != TestStatus::Ok) + if (test_status != TestStatus::ok) {} - test_suite_status.AddTestStatus(test_status); + test_suite_status.add_test_status(test_status); logger.debug("{} -> {}", test_status, name); profiler->add_event(current_test_duration); } diff --git a/src/stream/tester/test_suite/test_suite.h b/src/stream/tester/test_suite/test_suite.h index 06586b3b..580fed55 100644 --- a/src/stream/tester/test_suite/test_suite.h +++ b/src/stream/tester/test_suite/test_suite.h @@ -18,8 +18,8 @@ namespace stream::tester enum class TestStatus : int { - Ok, - Fail, + ok, + fail, Crash }; } @@ -30,65 +30,65 @@ namespace stream::tester::detail class Test { public: - Test(std::string&& name, TestSuite& link, const fmt::detail::FileLocation& location) - : name(std::move(name)) - , Link(link) + Test(std::string_view name_, TestSuite& link, const fmt::detail::FileLocation& location) + : name(name_) + , link(link) , location(location) - , LastStatus(TestStatus::Ok) + , last_status(TestStatus::ok) {} virtual ~Test() = default; protected: - virtual TestStatus RunImpl() = 0; + virtual TestStatus run_impl() = 0; public: TestStatus run() { try { - return LastStatus = RunImpl(); + return last_status = run_impl(); } catch (const TestFailure&) { - return LastStatus = TestStatus::Fail; + return last_status = TestStatus::fail; } catch (...) { - return LastStatus = TestStatus::Crash; + return last_status = TestStatus::Crash; } } public: std::string name; - TestSuite& Link; + TestSuite& link; fmt::detail::FileLocation location; - TestStatus LastStatus; + TestStatus last_status; }; struct TestStatusBank { - void Reset() + void reset() { tests_done = 0; tests_ok = 0; tests_failed = 0; - testsCrash = 0; + tests_crash = 0; } - void AddTestStatus(TestStatus status) + void add_test_status(TestStatus status) { tests_done++; switch (status) { - case TestStatus::Ok: + case TestStatus::ok: tests_ok++; break; - case TestStatus::Fail: + case TestStatus::fail: tests_failed++; break; case TestStatus::Crash: - testsCrash++; + tests_crash++; break; } } @@ -98,17 +98,17 @@ namespace stream::tester::detail tests_done += status.tests_done; tests_ok += status.tests_ok; tests_failed += status.tests_failed; - testsCrash += status.testsCrash; + tests_crash += status.tests_crash; } - bool is_all_ok() { return tests_done == tests_ok && testsCrash == 0 && tests_failed == 0; } + bool is_all_ok() { return tests_done == tests_ok && tests_crash == 0 && tests_failed == 0; } - std::uint32_t ErrorStatus() { return tests_done - tests_ok; } + std::uint32_t error_status() { return tests_done - tests_ok; } std::uint32_t tests_done = 0; std::uint32_t tests_ok = 0; std::uint32_t tests_failed = 0; - std::uint32_t testsCrash = 0; + std::uint32_t tests_crash = 0; }; class TestSuite; @@ -151,14 +151,14 @@ namespace stream::tester::detail class TestSuite { public: - TestSuite(std::string&& name, TestSuiteData extra = TestSuiteData{}, TestSuite* parent = nullptr) - : name(std::move(name)) + TestSuite(std::string_view name_, TestSuiteData extra_ = TestSuiteData{}, TestSuite* parent_ = nullptr) + : name(name_) , tests() - , extra(extra) + , extra(extra_) , logger() , test_logger() , profiler(nullptr) - , parent(parent) + , parent(parent_) { if (parent == nullptr) TestSuitesManager::test_suites.insert({name, this}); @@ -166,9 +166,9 @@ namespace stream::tester::detail parent->test_suites_linked.insert({name, this}); } - std::string name; - std::unordered_map tests; - std::unordered_map test_suites_linked; + std::string name; + std::unordered_map tests; + std::unordered_map test_suites_linked; TestSuiteData extra; flog::BasicLogger logger; @@ -204,7 +204,7 @@ namespace stream::fmt { [[nodiscard]] static std::expected format(const stream::tester::detail::Test& t, FormatterExecutor& executor) { - SF_TRY(buf::WriteManip(executor.ostream).fast_write_string(t.Link.name)); + SF_TRY(buf::WriteManip(executor.ostream).fast_write_string(t.link.name)); SF_TRY(buf::WriteManip(executor.ostream).fast_write_string_literal("::")); SF_TRY(buf::WriteManip(executor.ostream).fast_write_string(t.name)); return {}; @@ -218,9 +218,9 @@ namespace stream::fmt { switch (status) { - case stream::tester::TestStatus::Ok: + case stream::tester::TestStatus::ok: return executor.run("[ {C:green}OK{C} ]"); - case stream::tester::TestStatus::Fail: + case stream::tester::TestStatus::fail: return executor.run("[ {C:red}FAIL{C} ]"); case stream::tester::TestStatus::Crash: return executor.run("[{C:magenta}Crash{C} ]"); @@ -250,10 +250,10 @@ namespace stream::fmt { SF_TRY(executor.run("{:C:red}", status_bank.tests_failed)); } SF_TRY(buf::WriteManip(executor.ostream).fast_write_string_literal(" | TestCrash ")); - if (status_bank.testsCrash == 0) - { SF_TRY(executor.run("{:C:green}", status_bank.testsCrash)); } + if (status_bank.tests_crash == 0) + { SF_TRY(executor.run("{:C:green}", status_bank.tests_crash)); } else - { SF_TRY(executor.run("{:C:magenta}", status_bank.testsCrash)); } + { SF_TRY(executor.run("{:C:magenta}", status_bank.tests_crash)); } return {}; } diff --git a/src/stream/tester/tests_macros.h b/src/stream/tester/tests_macros.h index ec52cc34..3c004dcc 100644 --- a/src/stream/tester/tests_macros.h +++ b/src/stream/tester/tests_macros.h @@ -7,9 +7,9 @@ #define STREAMFORMAT_TEST_WARN(...) stream::Test::TestCore::get_logger().warn(__VA_ARGS__) #define STREAMFORMAT_TEST_ERROR(...) stream::Test::TestCore::get_logger().error(__VA_ARGS__) #define STREAMFORMAT_TEST_FATAL(...) stream::Test::TestCore::get_logger().fatal(__VA_ARGS__) -#define STREAMFORMAT_TEST_OK(...) stream::Test::TestCore::get_logger().Ok(__VA_ARGS__) -#define STREAMFORMAT_TEST_FAIL(...) stream::Test::TestCore::get_logger().Fail(__VA_ARGS__) -#define STREAMFORMAT_TEST_BASIC(...) stream::Test::TestCore::get_logger().Basic(__VA_ARGS__) +#define STREAMFORMAT_TEST_OK(...) stream::Test::TestCore::get_logger().ok(__VA_ARGS__) +#define STREAMFORMAT_TEST_FAIL(...) stream::Test::TestCore::get_logger().fail(__VA_ARGS__) +#define STREAMFORMAT_TEST_BASIC(...) stream::Test::TestCore::get_logger().basic(__VA_ARGS__) namespace stream::Test { diff --git a/tests/BUILD.bazel b/tests/BUILD.bazel index 14210557..cf938353 100644 --- a/tests/BUILD.bazel +++ b/tests/BUILD.bazel @@ -4,7 +4,7 @@ load("@rules_cc//cc:defs.bzl", "cc_test") cc_test( name = "units", - srcs = glob([ "**/*.h", "**/*.cpp" ]), + srcs = [ "tests.cpp" ] + glob([ "fmt/*.h", "fmt/*.cpp" ]), copts = select({ "@rules_cc//cc/compiler:msvc-cl": ["/std:latest"], "//conditions:default": [ From c2b048b0ba6f213d97196fd928acff58426f0ff1 Mon Sep 17 00:00:00 2001 From: Sacha Bellier Date: Sun, 23 Mar 2025 18:54:41 +0100 Subject: [PATCH 21/42] wip: CI --- .buildbuddy/workspace_status.ps1 | 2 +- conf | 2 +- scripts/clang-tidy.sh | 2 +- src/stream/core/prelude.h | 26 +- src/stream/default_logger.h | 38 +- src/stream/flog/backends/basic_logger.h | 101 ++--- src/stream/flog/backends/logger_multi_sink.h | 36 +- .../flog/backends/logger_multi_sink_fast.h | 45 +-- .../flog/backends/logger_multi_sink_safe.h | 55 ++- src/stream/flog/detail/detail.h | 50 +-- src/stream/flog/frontends/xlogger.cpp | 10 +- src/stream/flog/frontends/xlogger.h | 130 +++---- src/stream/flog/logger_factory.h | 9 +- src/stream/flog/sinks/file_sink.h | 47 +-- src/stream/flog/sinks/logger_sink.h | 74 ++-- src/stream/fmt/buf/fmt_manip_io.h | 80 ++-- src/stream/fmt/buf/fmt_read_manip.h | 132 +++---- src/stream/fmt/buf/fmt_write_manip.h | 155 ++++---- src/stream/fmt/buf/manip.h | 111 +++--- src/stream/fmt/buf/manip_io.h | 47 ++- src/stream/fmt/buf/read_manip.h | 90 +++-- src/stream/fmt/buf/stream.h | 63 ++-- src/stream/fmt/buf/streamio.h | 32 +- .../streamio_manager/basic_streamio_manager.h | 53 ++- .../dynamic_streamio_manager.h | 78 ++-- .../streamio_manager/given_streamio_manager.h | 35 +- .../static_streamio_manager.h | 27 +- src/stream/fmt/buf/test_manip.h | 147 ++++---- .../fmt/buf/utils/buffer_globber_manip.h | 80 ++-- src/stream/fmt/buf/utils/buffer_shift_manip.h | 64 ++-- src/stream/fmt/buf/utils/buffer_utils.h | 56 ++- src/stream/fmt/buf/write_manip.h | 129 +++---- .../basic_context/basic_args_interface.h | 66 ++-- .../fmt/context/basic_context/basic_context.h | 87 ++--- .../basic_context/basic_context_parse_impl.h | 243 +++++------- .../basic_context/text_properties_executor.h | 8 +- .../basic_context/text_properties_manager.cpp | 104 ++---- .../basic_context/text_properties_manager.h | 186 +++++----- .../text_properties_manager_impl.h | 241 +++++++----- .../basic_formatter_executor.h | 58 ++- .../formatter_executor/format_basics_impl.h | 187 +++++----- .../format_text_properties_impl.h | 53 +-- .../formatter_executor/formatter_args.h | 106 +++--- .../formatter_text_properties_executor.h | 21 +- .../formatter_text_properties_executor_ansi.h | 86 ++--- .../formatter_executor/formatter_type.h | 35 +- .../context/formatter_executor/index_args.h | 27 +- .../context/formatter_executor/named_args.h | 85 ++--- .../formatter_executor/std_enumerable.h | 77 ++-- .../formatter_executor/utility_functions.h | 128 +++---- .../parser_executor/basic_parser_executor.h | 42 +-- .../parser_executor/parse_basics_impl.h | 76 ++-- .../parse_text_properties_impl.h | 53 +-- .../fmt/context/parser_executor/parser_args.h | 97 ++--- .../parser_text_properties_executor.h | 115 ++++-- .../parser_text_properties_executor_ansi.h | 84 ++--- .../fmt/context/parser_executor/parser_type.h | 22 +- .../parser_executor/utility_functions.h | 10 +- .../fmt/context/utils/context_functions.h | 19 +- src/stream/fmt/detail/convert_traits.h | 47 ++- src/stream/fmt/detail/fmt_result.h | 28 +- src/stream/fmt/detail/indent_handlers.h | 19 +- src/stream/fmt/detail/prelude.h | 5 +- src/stream/fmt/detail/specifiers.h | 234 +++++------- src/stream/fmt/detail/types_traits.h | 8 +- src/stream/fmt/serializers/compilation_data.h | 51 +-- src/stream/fmt/serializers/format_chrono.h | 127 +++---- src/stream/fmt/serializers/format_stdlib.h | 49 ++- src/stream/fmt/serializers/parse_chrono.h | 10 +- src/stream/fmt/serializers/parse_stdlib.h | 3 +- .../fmt/serializers/std_container/FMT_deque.h | 14 - .../fmt/serializers/std_container/FMT_list.h | 14 - .../fmt/serializers/std_container/FMT_queue.h | 16 - .../fmt/serializers/std_container/FMT_set.h | 21 -- .../serializers/std_container/FMT_vector.h | 14 - .../std_container/{FMT_array.h => array.h} | 15 +- .../fmt/serializers/std_container/deque.h | 15 + .../{FMT_forward_list.h => forward_list.h} | 15 +- .../fmt/serializers/std_container/list.h | 15 + .../std_container/{FMT_map.h => map.h} | 20 +- .../fmt/serializers/std_container/queue.h | 13 + .../fmt/serializers/std_container/set.h | 22 ++ .../std_container/{FMT_stack.h => stack.h} | 3 +- .../std_container/{FMT_tuple.h => tuple.h} | 48 +-- .../{FMT_unordered_map.h => unordered_map.h} | 20 +- .../{FMT_unordered_set.h => unordered_set.h} | 21 +- .../fmt/serializers/std_container/vector.h | 15 + .../text_properties/base_text_properties.h | 12 +- .../fmt/text_properties/text_properties.h | 11 +- .../text_properties/text_properties_color.h | 346 +++++++----------- .../text_properties/text_properties_front.h | 78 ++-- .../text_properties/text_properties_style.h | 225 ++++++------ src/stream/json/detail.h | 69 ++-- src/stream/json/json_factory.h | 40 +- src/stream/json/json_formatter.h | 66 ++-- src/stream/json/json_formatter_impl.h | 27 +- src/stream/json/json_objects.cpp | 41 +-- src/stream/json/json_objects.h | 171 +++++---- src/stream/json/json_parser.cpp | 75 ++-- src/stream/json/json_parser.h | 69 ++-- src/stream/json/json_serializer.h | 179 ++++----- .../json/serializers/base_serializers.h | 67 ++-- .../serializers/json_objects_serializer.h | 89 +++-- .../std_serializers/basic_std_serializers.h | 26 +- .../serializers/std_serializers/json_map.h | 35 +- .../std_serializers/json_unordered_map.h | 30 +- .../serializers/std_serializers/json_vector.h | 19 +- src/stream/profiler/all_events.h | 35 +- src/stream/profiler/detail.h | 10 +- src/stream/profiler/event.h | 112 +++--- src/stream/profiler/event_data.h | 21 +- src/stream/profiler/get_pid.cpp | 8 +- src/stream/profiler/profiler.h | 29 +- .../profiler/profiler_event_creator.cpp | 54 ++- src/stream/profiler/profiler_event_creator.h | 37 +- src/stream/profiler/profiler_factory.cpp | 12 +- src/stream/profiler/profiler_factory.h | 8 +- .../profiler/profiler_json_serializers.h | 79 ++-- src/stream/profiler/profiler_macros.h | 5 +- src/stream/tester/copy_move_check.h | 44 +-- src/stream/tester/test_suite/basic_test.h | 62 ++-- src/stream/tester/test_suite/test_suite.cpp | 95 ++--- src/stream/tester/test_suite/test_suite.h | 210 +++++------ src/stream/tester/tests_macros.h | 45 ++- tests/fmt/complex_pattern.cpp | 7 +- tests/fmt/globber.cpp | 107 +++--- tests/fmt/index.cpp | 4 + tests/fmt/limits.cpp | 130 +++---- tests/fmt/shift.cpp | 79 ++-- tests/fmt/specifier.cpp | 7 +- tests/fmt/text_properties.cpp | 37 +- tests/tests.cpp | 5 +- 132 files changed, 3558 insertions(+), 4563 deletions(-) delete mode 100644 src/stream/fmt/serializers/std_container/FMT_deque.h delete mode 100644 src/stream/fmt/serializers/std_container/FMT_list.h delete mode 100644 src/stream/fmt/serializers/std_container/FMT_queue.h delete mode 100644 src/stream/fmt/serializers/std_container/FMT_set.h delete mode 100644 src/stream/fmt/serializers/std_container/FMT_vector.h rename src/stream/fmt/serializers/std_container/{FMT_array.h => array.h} (59%) create mode 100644 src/stream/fmt/serializers/std_container/deque.h rename src/stream/fmt/serializers/std_container/{FMT_forward_list.h => forward_list.h} (58%) create mode 100644 src/stream/fmt/serializers/std_container/list.h rename src/stream/fmt/serializers/std_container/{FMT_map.h => map.h} (55%) create mode 100644 src/stream/fmt/serializers/std_container/queue.h create mode 100644 src/stream/fmt/serializers/std_container/set.h rename src/stream/fmt/serializers/std_container/{FMT_stack.h => stack.h} (94%) rename src/stream/fmt/serializers/std_container/{FMT_tuple.h => tuple.h} (61%) rename src/stream/fmt/serializers/std_container/{FMT_unordered_map.h => unordered_map.h} (82%) rename src/stream/fmt/serializers/std_container/{FMT_unordered_set.h => unordered_set.h} (61%) create mode 100644 src/stream/fmt/serializers/std_container/vector.h diff --git a/.buildbuddy/workspace_status.ps1 b/.buildbuddy/workspace_status.ps1 index e6726f2b..a2c1a204 100755 --- a/.buildbuddy/workspace_status.ps1 +++ b/.buildbuddy/workspace_status.ps1 @@ -8,7 +8,7 @@ # If the script exits with a non-zero code, it's considered as a failure # and the output will be discarded. -$ErrorActionPreference = "stop" +$ErrorActionPreference = "Stop" # Get the repository URL without credentials $repo_url = (git config --get remote.origin.url) -replace '//.*?:.*?@', '//' diff --git a/conf b/conf index 6cc31a2b..ba69cca0 160000 --- a/conf +++ b/conf @@ -1 +1 @@ -Subproject commit 6cc31a2b5c9afbeef30af8bcc391e846fa12fe1f +Subproject commit ba69cca07f908ff389da36bc07140ffe14643665 diff --git a/scripts/clang-tidy.sh b/scripts/clang-tidy.sh index 699a7fc5..128a0613 100755 --- a/scripts/clang-tidy.sh +++ b/scripts/clang-tidy.sh @@ -1,3 +1,3 @@ #!/bin/bash -./conf/linter/clang-tidy.sh //custom:compile_commands_tests --enable-headers +./conf/linter/clang-tidy.sh //custom:compile_commands_tests --enable-headers $* diff --git a/src/stream/core/prelude.h b/src/stream/core/prelude.h index 28579737..646e1f43 100644 --- a/src/stream/core/prelude.h +++ b/src/stream/core/prelude.h @@ -19,11 +19,10 @@ #define STREAMFORMAT_DEBUGBREAK() std::raise(SIGINT) #endif #include -#define STREAMFORMAT_ASSERT(x) \ - if (!(x)) \ - { \ +#define STREAMFORMAT_ASSERT(x) \ + if (!(x)) { \ std::cerr << "ASSERT FAILED! : " << #x << std::endl; \ - STREAMFORMAT_DEBUGBREAK(); \ + STREAMFORMAT_DEBUGBREAK(); \ } #else #define STREAMFORMAT_ASSERT(x) @@ -35,20 +34,19 @@ #include #include -namespace stream::detail -{ - template - T forward_error(T t) - { +namespace stream::detail { + template + T forward_error(T t) { return std::forward(t); } -} +} // namespace stream::detail -#define SF_TRY(exp) ({ \ - auto __expected = exp; \ - if (not __expected) [[unlikely]] \ +#define SF_TRY(exp) \ + ({ \ + auto __expected = exp; \ + if (not __expected) [[unlikely]] \ return std::unexpected(stream::detail::forward_error(__expected.error())); \ - __expected.value(); \ + __expected.value(); \ }); #define SF_FORWARD(exp) SF_TRY(exp) diff --git a/src/stream/default_logger.h b/src/stream/default_logger.h index 9070d3e2..61f11afb 100644 --- a/src/stream/default_logger.h +++ b/src/stream/default_logger.h @@ -7,36 +7,32 @@ #define STREAMFORMAT_BASE_LOGGER_NAME "APP" #endif -namespace stream::flog -{ - class DefaultLogger - { +namespace stream::flog { + class DefaultLogger { public: - [[maybe_unused]] static BasicLogger& core() - { + [[maybe_unused]] static BasicLogger& core() { static BasicLogger instance(STREAMFORMAT_BASE_LOGGER_NAME "-core", LogSeverity::Trace); return instance; } - [[maybe_unused]] static BasicLogger& client() - { + [[maybe_unused]] static BasicLogger& client() { static BasicLogger instance(STREAMFORMAT_BASE_LOGGER_NAME "-client", LogSeverity::Trace); return instance; } }; -} +} // namespace stream::flog #ifdef STREAMFORMAT_LOGGER_ENABLE - #define CORE_TRACE(...) stream::flog::BasicLogger::core().trace(__VA_ARGS__) - #define CORE_DEBUG(...) stream::flog::BasicLogger::core().debug(__VA_ARGS__) - #define CORE_INFO(...) stream::flog::BasicLogger::core().info(__VA_ARGS__) - #define CORE_WARN(...) stream::flog::BasicLogger::core().warn(__VA_ARGS__) - #define CORE_ERROR(...) stream::flog::BasicLogger::core().error(__VA_ARGS__) - #define CORE_FATAL(...) stream::flog::BasicLogger::core().fatal(__VA_ARGS__) +#define CORE_TRACE(...) stream::flog::BasicLogger::core().trace(__VA_ARGS__) +#define CORE_DEBUG(...) stream::flog::BasicLogger::core().debug(__VA_ARGS__) +#define CORE_INFO(...) stream::flog::BasicLogger::core().info(__VA_ARGS__) +#define CORE_WARN(...) stream::flog::BasicLogger::core().warn(__VA_ARGS__) +#define CORE_ERROR(...) stream::flog::BasicLogger::core().error(__VA_ARGS__) +#define CORE_FATAL(...) stream::flog::BasicLogger::core().fatal(__VA_ARGS__) #else - #define CORE_TRACE(...) - #define CORE_DEBUG(...) - #define CORE_INFO(...) - #define CORE_WARN(...) - #define CORE_ERROR(...) - #define CORE_FATAL(...) +#define CORE_TRACE(...) +#define CORE_DEBUG(...) +#define CORE_INFO(...) +#define CORE_WARN(...) +#define CORE_ERROR(...) +#define CORE_FATAL(...) #endif diff --git a/src/stream/flog/backends/basic_logger.h b/src/stream/flog/backends/basic_logger.h index f1a48e41..758b6d1a 100644 --- a/src/stream/flog/backends/basic_logger.h +++ b/src/stream/flog/backends/basic_logger.h @@ -6,87 +6,90 @@ #include #include -namespace stream::flog::detail -{ +namespace stream::flog::detail { template - class BasicLoggerImpl - { + class BasicLoggerImpl { public: using SeverityValueType = typename Severity::Value; public: - BasicLoggerImpl() - : name_("logger_") - , m_Severity(Severity::Value::DefaultSeverity) - , m_Stream(std::cout) - , start_time_(std::chrono::high_resolution_clock::now()) - { + BasicLoggerImpl() : name_("logger_"), m_Severity(Severity::Value::DefaultSeverity), m_Stream(std::cout), start_time_(std::chrono::high_resolution_clock::now()) { ResetPattern(); } - + explicit BasicLoggerImpl(const std::string_view& name, typename Severity::Value severity = Severity::Value::DefaultSeverity, std::ostream& stream = std::cout) - : name_(name) - , m_Severity(severity) - , m_Stream(stream) - , preFormatStreamIOManager(64) - , fullFormatStreamIOManager(64) - , start_time_(std::chrono::high_resolution_clock::now()) - { + : name_(name), + m_Severity(severity), + m_Stream(stream), + preFormatStreamIOManager(64), + fullFormatStreamIOManager(64), + start_time_(std::chrono::high_resolution_clock::now()) { ResetPattern(); } explicit BasicLoggerImpl(const std::string_view& name, const std::string_view& format, typename Severity::Value severity = Severity::Value::DefaultSeverity, std::ostream& stream = std::cout) - : name_(name) - , m_Severity(severity) - , m_Stream(stream) - , preFormatStreamIOManager(64) - , fullFormatStreamIOManager(64) - , start_time_(std::chrono::high_resolution_clock::now()) - { + : name_(name), + m_Severity(severity), + m_Stream(stream), + preFormatStreamIOManager(64), + fullFormatStreamIOManager(64), + start_time_(std::chrono::high_resolution_clock::now()) { SetPattern(format); } virtual ~BasicLoggerImpl() = default; public: - void set_severity(const SeverityValueType& severity) { m_Severity = severity; } - void set_name(const std::string& name) { name_ = name; } - void set_name(std::string&& name) { name_ = std::move(name); } - void SetRealPattern(std::string_view pattern) { m_Pattern = pattern; } - void set_real_pattern_strmv(std::string&& pattern) { m_Pattern = std::move(pattern); } - void SetPattern(std::string_view pattern) - { + void set_severity(const SeverityValueType& severity) { + m_Severity = severity; + } + void set_name(const std::string& name) { + name_ = name; + } + void set_name(std::string&& name) { + name_ = std::move(name); + } + void SetRealPattern(std::string_view pattern) { + m_Pattern = pattern; + } + void set_real_pattern_strmv(std::string&& pattern) { + m_Pattern = std::move(pattern); + } + void SetPattern(std::string_view pattern) { m_Pattern = "{color}"; m_Pattern += pattern; } - void ResetPattern() { SetPattern("[{time:pattern='%h:%m:%s:%ms'}] {name} >> {data}"); } + void ResetPattern() { + SetPattern("[{time:pattern='%h:%m:%s:%ms'}] {name} >> {data}"); + } private: - std::string name_; - SeverityValueType m_Severity; - std::ostream& m_Stream; - std::string m_Pattern; + std::string name_; + SeverityValueType m_Severity; + std::ostream& m_Stream; + std::string m_Pattern; fmt::buf::DynamicStreamIOManager preFormatStreamIOManager; fmt::buf::DynamicStreamIOManager fullFormatStreamIOManager; std::chrono::time_point start_time_; public: - void NewLine() { m_Stream.write("\n", 1); } + void NewLine() { + m_Stream.write("\n", 1); + } template - requires fmt::buf::convertible_to_buffer_info_view - [[nodiscard]] std::expected log(const SeverityValueType& severity, Format&& format, Args&&... args) - { - if (severity < m_Severity) - return {}; + requires fmt::buf::convertible_to_buffer_info_view + [[nodiscard]] std::expected log(const SeverityValueType& severity, Format&& format, Args&&... args) { + if (severity < m_Severity) return {}; std::chrono::nanoseconds logTime = std::chrono::high_resolution_clock::now() - start_time_; SF_TRY(fmt::detail::format_in_manager(preFormatStreamIOManager, false, fmt::buf::StreamView(m_Pattern), FORMAT_SV("time", logTime), FORMAT_SV("name", name_), FORMAT_SV("data", flog::AddIndentInFormat(format)))); - - SF_TRY(fmt::detail::format_in_manager(fullFormatStreamIOManager, true, preFormatStreamIOManager.get_last_generated_buffer_info_view(), std::forward(args)..., FORMAT_SV("color", severity))); + + SF_TRY(fmt::detail::format_in_manager(fullFormatStreamIOManager, true, preFormatStreamIOManager.get_last_generated_buffer_info_view(), std::forward(args)..., + FORMAT_SV("color", severity))); m_Stream.write(fullFormatStreamIOManager.get_buffer(), static_cast(fullFormatStreamIOManager.get_last_generated_data_size())); m_Stream.flush(); @@ -94,10 +97,8 @@ namespace stream::flog::detail } template - [[nodiscard]] std::expected log(const SeverityValueType& severity, T&& t) - { - if (severity < m_Severity) - return {}; + [[nodiscard]] std::expected log(const SeverityValueType& severity, T&& t) { + if (severity < m_Severity) return {}; std::chrono::nanoseconds logTime = std::chrono::high_resolution_clock::now() - start_time_; @@ -109,4 +110,4 @@ namespace stream::flog::detail return {}; } }; -} +} // namespace stream::flog::detail diff --git a/src/stream/flog/backends/logger_multi_sink.h b/src/stream/flog/backends/logger_multi_sink.h index 31ab3b8a..fdf6c4c9 100644 --- a/src/stream/flog/backends/logger_multi_sink.h +++ b/src/stream/flog/backends/logger_multi_sink.h @@ -3,33 +3,32 @@ #include "stream/flog/detail/detail.h" #include "stream/flog/sinks/logger_sink.h" -namespace stream::flog::detail -{ +namespace stream::flog::detail { template - class BasicLoggerMultiSinkImpl - { + class BasicLoggerMultiSinkImpl { public: using SinkType = BasicLoggerSink; using SeverityValueType = typename Severity::Value; public: - BasicLoggerMultiSinkImpl() - : name_("logger_:{sink}") - , start_time_(std::chrono::high_resolution_clock::now()) - {} + BasicLoggerMultiSinkImpl() : name_("logger_:{sink}"), start_time_(std::chrono::high_resolution_clock::now()) {} BasicLoggerMultiSinkImpl(std::basic_string&& name) - : name_(std::forward>(name)) - , start_time_(std::chrono::high_resolution_clock::now()) - {} + : name_(std::forward>(name)), start_time_(std::chrono::high_resolution_clock::now()) {} virtual ~BasicLoggerMultiSinkImpl() = default; public: - void set_name(std::basic_string&& name) { name_ = std::forward>(name); } + void set_name(std::basic_string&& name) { + name_ = std::forward>(name); + } - std::basic_string& get_name() { return name_; } - std::vector>& get_sinks() { return sinks_; } + std::basic_string& get_name() { + return name_; + } + std::vector>& get_sinks() { + return sinks_; + } protected: std::basic_string name_; @@ -38,13 +37,14 @@ namespace stream::flog::detail std::chrono::time_point start_time_; public: - void add_sink(std::shared_ptr sink) { sinks_.pushback(sink); } + void add_sink(std::shared_ptr sink) { + sinks_.pushback(sink); + } template - void EmplaceSink(Args&&... args) - { + void EmplaceSink(Args&&... args) { std::shared_ptr sink = std::make_shared(std::forward(args)...); add_sink(sink); } }; -} +} // namespace stream::flog::detail diff --git a/src/stream/flog/backends/logger_multi_sink_fast.h b/src/stream/flog/backends/logger_multi_sink_fast.h index 682f71de..d1ea360a 100644 --- a/src/stream/flog/backends/logger_multi_sink_fast.h +++ b/src/stream/flog/backends/logger_multi_sink_fast.h @@ -2,18 +2,16 @@ #include "logger_multi_sink.h" -namespace stream::flog::detail -{ +namespace stream::flog::detail { template - class BasicLoggerMultiSinkFastImpl : public BasicLoggerMultiSinkImpl - { + class BasicLoggerMultiSinkFastImpl : public BasicLoggerMultiSinkImpl { public: using Base = BasicLoggerMultiSinkImpl; - using Base::set_name; + using Base::add_sink; using Base::get_name; using Base::get_sinks; - using Base::add_sink; using Base::name_; + using Base::set_name; using Base::sinks_; using Base::start_time_; @@ -21,54 +19,49 @@ namespace stream::flog::detail using typename Base::SeverityValueType; public: - BasicLoggerMultiSinkFastImpl() - : Base() - {} + BasicLoggerMultiSinkFastImpl() : Base() {} - BasicLoggerMultiSinkFastImpl(std::basic_string&& name) - : Base(std::forward>(name)) - {} + BasicLoggerMultiSinkFastImpl(std::basic_string&& name) : Base(std::forward>(name)) {} ~BasicLoggerMultiSinkFastImpl() override = default; public: - void await(const SeverityValueType& severity) - { + void await(const SeverityValueType& severity) { for (auto& sink : sinks_) if (sink->need_to_log(severity)) sink->wait_until_finished_to_write(); } public: template - requires fmt::buf::convertible_to_buffer_info_view - [[nodiscard]] std::expected log(const SeverityValueType& severity, const Format& format, Args&&... args) - { + requires fmt::buf::convertible_to_buffer_info_view + [[nodiscard]] std::expected log(const SeverityValueType& severity, const Format& format, Args&&... args) { std::chrono::nanoseconds logTime = std::chrono::high_resolution_clock::now() - start_time_; fmt::buf::DynamicStreamIOManager manager(256); - auto formatBuffer = SF_TRY(fmt::detail::format_in_manager(manager, false, format, std::forward(args)...)); + auto formatBuffer = SF_TRY(fmt::detail::format_in_manager(manager, false, format, std::forward(args)...)); for (auto& sink : sinks_) - if (sink->need_to_log(severity)) - { SF_TRY(sink->format_and_write_to_sink(sink->get_pattern(severity), logTime, name_, static_cast>(*formatBuffer))); } + if (sink->need_to_log(severity)) { + SF_TRY(sink->format_and_write_to_sink(sink->get_pattern(severity), logTime, name_, static_cast>(*formatBuffer))); + } await(severity); return {}; } template - [[nodiscard]] std::expected log(const SeverityValueType& severity, T&& t) - { + [[nodiscard]] std::expected log(const SeverityValueType& severity, T&& t) { std::chrono::nanoseconds logTime = std::chrono::high_resolution_clock::now() - start_time_; fmt::buf::DynamicStreamIOManager manager(256); - auto formatBuffer = SF_TRY(fmt::detail::format_in_manager(manager, false, std::forward(t))); + auto formatBuffer = SF_TRY(fmt::detail::format_in_manager(manager, false, std::forward(t))); for (auto& sink : sinks_) - if (sink->need_to_log(severity)) - { SF_TRY(sink->format_and_write_to_sink(sink->get_pattern(severity), logTime, name_, static_cast>(*formatBuffer))); } + if (sink->need_to_log(severity)) { + SF_TRY(sink->format_and_write_to_sink(sink->get_pattern(severity), logTime, name_, static_cast>(*formatBuffer))); + } await(severity); return {}; } }; -} +} // namespace stream::flog::detail diff --git a/src/stream/flog/backends/logger_multi_sink_safe.h b/src/stream/flog/backends/logger_multi_sink_safe.h index 72bdd0cc..955f6b4c 100644 --- a/src/stream/flog/backends/logger_multi_sink_safe.h +++ b/src/stream/flog/backends/logger_multi_sink_safe.h @@ -2,81 +2,68 @@ #include "logger_multi_sink.h" -namespace stream::flog::detail -{ +namespace stream::flog::detail { template - class BasicLoggerMultiSinkSafeImpl : public BasicLoggerMultiSinkImpl - { + class BasicLoggerMultiSinkSafeImpl : public BasicLoggerMultiSinkImpl { public: using Base = BasicLoggerMultiSinkImpl; - using Base::set_name; + using Base::add_sink; using Base::get_name; using Base::get_sinks; using Base::name_; + using Base::set_name; using Base::sinks_; - using Base::add_sink; using Base::start_time_; using typename Base::SeverityValueType; public: - BasicLoggerMultiSinkSafeImpl() - : Base() - {} + BasicLoggerMultiSinkSafeImpl() : Base() {} - BasicLoggerMultiSinkSafeImpl(std::basic_string&& name) - : Base(std::forward>(name)) - {} + BasicLoggerMultiSinkSafeImpl(std::basic_string&& name) : Base(std::forward>(name)) {} ~BasicLoggerMultiSinkSafeImpl() override = default; public: - void await(const SeverityValueType& severity) - { + void await(const SeverityValueType& severity) { for (auto& sink : sinks_) if (sink->need_to_log(severity)) sink->wait_until_finished_to_write(); } public: template - requires fmt::buf::convertible_to_buffer_info_view - [[nodiscard]] std::expected log(const SeverityValueType& severity, const Format& format, Args&&... args) - { + requires fmt::buf::convertible_to_buffer_info_view + [[nodiscard]] std::expected log(const SeverityValueType& severity, const Format& format, Args&&... args) { std::chrono::nanoseconds logTime = std::chrono::high_resolution_clock::now() - start_time_; // FIXME maybe add : name ; indent ??? - for (auto& sink : sinks_) - { - if (sink->need_to_log(severity)) - { + for (auto& sink : sinks_) { + if (sink->need_to_log(severity)) { fmt::buf::DynamicStreamIOManager manager_pattern(256); fmt::buf::DynamicStreamIOManager manager_format(256); - auto format_pattern_str = + auto format_pattern_str = SF_TRY(fmt::detail::format_in_manager(manager_pattern, false, std::string_view(sink->get_pattern(severity)), FORMAT_SV("time", logTime), - FORMAT_SV("name", FutureConcatNameAndSinkName(name_)), FORMAT_SV("data", flog::AddIndentInFormat(format)))); - auto format_format_str = SF_TRY(fmt::detail::format_in_manager(manager_format, false, static_cast(*format_pattern_str), std::forward(args)..., - FORMAT_SV("sink", sink->get_name()), FORMAT_SV("color", severity))); + FORMAT_SV("name", FutureConcatNameAndSinkName(name_)), FORMAT_SV("data", flog::AddIndentInFormat(format)))); + auto format_format_str = SF_TRY(fmt::detail::format_in_manager(manager_format, false, static_cast(*format_pattern_str), + std::forward(args)..., FORMAT_SV("sink", sink->get_name()), FORMAT_SV("color", severity))); SF_TRY(sink->WriteToSink(static_cast>(*format_format_str))); } } - + await(severity); return {}; } template - [[nodiscard]] std::expected log(const SeverityValueType& severity, T&& t) - { + [[nodiscard]] std::expected log(const SeverityValueType& severity, T&& t) { std::chrono::nanoseconds logTime = std::chrono::high_resolution_clock::now() - start_time_; - for (auto& sink : sinks_) - { - if (sink->need_to_log(severity)) - { + for (auto& sink : sinks_) { + if (sink->need_to_log(severity)) { fmt::buf::DynamicStreamIOManager manager(256); auto formatBuffer = SF_TRY(fmt::detail::format_in_manager(manager, false, std::string_view(sink->get_pattern(severity)), FORMAT_SV("time", logTime), - FORMAT_SV("name", ConcatNameAndSinkName(name_, sink->get_name())), FORMAT_SV("data", t))); + FORMAT_SV("name", ConcatNameAndSinkName(name_, sink->get_name())), FORMAT_SV("data", t))); SF_TRY(sink->WriteToSink(static_cast>(*formatBuffer))); } } @@ -85,4 +72,4 @@ namespace stream::flog::detail return {}; } }; -} +} // namespace stream::flog::detail diff --git a/src/stream/flog/detail/detail.h b/src/stream/flog/detail/detail.h index b3696691..d428da5b 100644 --- a/src/stream/flog/detail/detail.h +++ b/src/stream/flog/detail/detail.h @@ -5,65 +5,47 @@ #include "stream/fmt/buf/manip.h" #include "stream/fmt/buf/write_manip.h" -namespace stream::flog -{ +namespace stream::flog { template - struct AddIndentInFormat - { - AddIndentInFormat(const FormatStr& format) - : format(format) - {} + struct AddIndentInFormat { + AddIndentInFormat(const FormatStr& format) : format(format) {} const FormatStr& format; }; template - struct ConcatNameAndSinkName - { - ConcatNameAndSinkName(const std::basic_string& loggerName, const std::basic_string& sinkName) - : LoggerName(loggerName) - , SinkName(sinkName) - {} + struct ConcatNameAndSinkName { + ConcatNameAndSinkName(const std::basic_string& loggerName, const std::basic_string& sinkName) : LoggerName(loggerName), SinkName(sinkName) {} const std::basic_string& LoggerName; const std::basic_string& SinkName; }; template - struct FutureConcatNameAndSinkName - { - FutureConcatNameAndSinkName(const std::basic_string& loggerName) - : LoggerName(loggerName) - {} + struct FutureConcatNameAndSinkName { + FutureConcatNameAndSinkName(const std::basic_string& loggerName) : LoggerName(loggerName) {} const std::basic_string& LoggerName; }; -} +} // namespace stream::flog -namespace stream::fmt -{ +namespace stream::fmt { template - struct FormatterType, FormatterExecutor> - { - [[nodiscard]] static std::expected format(const stream::flog::AddIndentInFormat& format, FormatterExecutor& executor) - { + struct FormatterType, FormatterExecutor> { + [[nodiscard]] static std::expected format(const stream::flog::AddIndentInFormat& format, FormatterExecutor& executor) { SF_TRY(buf::WriteManip(executor.ostream).fast_write_string_literal("{K:indent}")); return executor.write_type(format.format); } }; template - struct FormatterType, FormatterExecutor> - { - [[nodiscard]] static std::expected format(const stream::flog::ConcatNameAndSinkName& names, FormatterExecutor& executor) - { + struct FormatterType, FormatterExecutor> { + [[nodiscard]] static std::expected format(const stream::flog::ConcatNameAndSinkName& names, FormatterExecutor& executor) { return executor.run(names.LoggerName, FORMAT_SV("sink", names.SinkName)); } }; template - struct FormatterType, FormatterExecutor> - { - [[nodiscard]] static std::expected format(const stream::flog::FutureConcatNameAndSinkName& names, FormatterExecutor& executor) - { + struct FormatterType, FormatterExecutor> { + [[nodiscard]] static std::expected format(const stream::flog::FutureConcatNameAndSinkName& names, FormatterExecutor& executor) { return executor.run(names.LoggerName, "sink"); } }; -} +} // namespace stream::fmt diff --git a/src/stream/flog/frontends/xlogger.cpp b/src/stream/flog/frontends/xlogger.cpp index 2b737982..ac7591ba 100644 --- a/src/stream/flog/frontends/xlogger.cpp +++ b/src/stream/flog/frontends/xlogger.cpp @@ -1,14 +1,12 @@ #include "xlogger.h" -namespace stream::flog -{ +namespace stream::flog { template class detail::XLogger>; template class detail::XLogger>; template class detail::XLogger>; -} +} // namespace stream::flog -namespace stream::flog::Sinks -{ +namespace stream::flog::Sinks { template class BasicConsoleSink; template class BasicFileSink; -} +} // namespace stream::flog::Sinks diff --git a/src/stream/flog/frontends/xlogger.h b/src/stream/flog/frontends/xlogger.h index 2616afdc..8b66b381 100644 --- a/src/stream/flog/frontends/xlogger.h +++ b/src/stream/flog/frontends/xlogger.h @@ -6,13 +6,10 @@ #include "stream/flog/backends/logger_multi_sink_safe.h" #include "stream/flog/sinks/file_sink.h" -namespace stream::flog -{ - struct LogSeverity - { +namespace stream::flog { + struct LogSeverity { public: - enum class Value : int - { + enum class Value : int { Trace, Debug, Info, @@ -32,8 +29,7 @@ namespace stream::flog static constexpr Value DefaultSeverity = Trace; public: - class PatternOverride - { + class PatternOverride { public: std::basic_string trace_pattern = ""; std::basic_string debug_pattern = ""; @@ -42,10 +38,8 @@ namespace stream::flog std::basic_string error_pattern = ""; std::basic_string fatal_pattern = ""; - std::basic_string_view get_pattern(const Value& severity) const - { - switch (severity) - { + std::basic_string_view get_pattern(const Value& severity) const { + switch (severity) { case Value::Trace: if (trace_pattern.empty() == false) return trace_pattern; break; @@ -69,138 +63,121 @@ namespace stream::flog } }; }; -} +} // namespace stream::flog -namespace stream::flog::detail -{ +namespace stream::flog::detail { template - class XLogger : public Master - { + class XLogger : public Master { public: template - XLogger(Args&&... args) - : Master(std::forward(args)...) - {} + XLogger(Args&&... args) : Master(std::forward(args)...) {} ~XLogger() override = default; public: template - requires fmt::buf::convertible_to_buffer_info_view - [[nodiscard]] std::expected log(Severity status, Format&& format, Args&&... args) - { + requires fmt::buf::convertible_to_buffer_info_view + [[nodiscard]] std::expected log(Severity status, Format&& format, Args&&... args) { return Master::template log(status, format, std::forward(args)...); } template - [[nodiscard]] std::expected log(Severity status, T&& t) - { + [[nodiscard]] std::expected log(Severity status, T&& t) { return Master::template log(status, std::forward(t)); } public: /////---------- logger Severity with array as format ----------///// template - requires fmt::buf::convertible_to_buffer_info_view - inline std::expected trace(Format&& format, Args&&... args) - { + requires fmt::buf::convertible_to_buffer_info_view + inline std::expected trace(Format&& format, Args&&... args) { return log(LogSeverity::Trace, format, std::forward(args)...); } template - requires fmt::buf::convertible_to_buffer_info_view - inline std::expected debug(Format&& format, Args&&... args) - { + requires fmt::buf::convertible_to_buffer_info_view + inline std::expected debug(Format&& format, Args&&... args) { return log(LogSeverity::Debug, format, std::forward(args)...); } template - requires fmt::buf::convertible_to_buffer_info_view - inline std::expected info(Format&& format, Args&&... args) - { + requires fmt::buf::convertible_to_buffer_info_view + inline std::expected info(Format&& format, Args&&... args) { return log(LogSeverity::Info, format, std::forward(args)...); } template - requires fmt::buf::convertible_to_buffer_info_view - inline std::expected warn(Format&& format, Args&&... args) - { + requires fmt::buf::convertible_to_buffer_info_view + inline std::expected warn(Format&& format, Args&&... args) { return log(LogSeverity::Warn, format, std::forward(args)...); } template - requires fmt::buf::convertible_to_buffer_info_view - inline std::expected error(Format&& format, Args&&... args) - { + requires fmt::buf::convertible_to_buffer_info_view + inline std::expected error(Format&& format, Args&&... args) { return log(LogSeverity::Error, format, std::forward(args)...); } template - requires fmt::buf::convertible_to_buffer_info_view - inline std::expected fatal(Format&& format, Args&&... args) - { + requires fmt::buf::convertible_to_buffer_info_view + inline std::expected fatal(Format&& format, Args&&... args) { return log(LogSeverity::Fatal, format, std::forward(args)...); } /////---------- NO-FORMAT logger Severity ----------///// template - inline std::expected trace(T&& t) - { + inline std::expected trace(T&& t) { return log(LogSeverity::Trace, std::forward(t)); } template - inline std::expected debug(T&& t) - { + inline std::expected debug(T&& t) { return log(LogSeverity::Debug, std::forward(t)); } template - inline std::expected info(T&& t) - { + inline std::expected info(T&& t) { return log(LogSeverity::Info, std::forward(t)); } template - inline std::expected warn(T&& t) - { + inline std::expected warn(T&& t) { return log(LogSeverity::Warn, std::forward(t)); } template - inline std::expected error(T&& t) - { + inline std::expected error(T&& t) { return log(LogSeverity::Error, std::forward(t)); } template - inline std::expected fatal(T&& t) - { + inline std::expected fatal(T&& t) { return log(LogSeverity::Fatal, std::forward(t)); } }; -} +} // namespace stream::flog::detail -namespace stream::fmt -{ +namespace stream::fmt { template - struct FormatterType - { - [[nodiscard]] static std::expected format(const stream::flog::LogSeverity::Value t, FormatterExecutor& executor) - { + struct FormatterType { + [[nodiscard]] static std::expected format(const stream::flog::LogSeverity::Value t, FormatterExecutor& executor) { executor.data.keep_new_style = true; - switch (t) - { + switch (t) { case stream::flog::LogSeverity::Trace: - return FormatterType::format(detail::TextProperties::TextColor::BasicColorFG::BrightBlack, executor); + return FormatterType::format(detail::TextProperties::TextColor::BasicColorFG::BrightBlack, + executor); case stream::flog::LogSeverity::Debug: - return FormatterType::format(detail::TextProperties::TextColor::BasicColorFG::Blue, executor); + return FormatterType::format(detail::TextProperties::TextColor::BasicColorFG::Blue, + executor); case stream::flog::LogSeverity::Info: - return FormatterType::format(detail::TextProperties::TextColor::BasicColorFG::Green, executor); + return FormatterType::format(detail::TextProperties::TextColor::BasicColorFG::Green, + executor); case stream::flog::LogSeverity::Warn: - return FormatterType::format(detail::TextProperties::TextColor::BasicColorFG::Yellow, executor); + return FormatterType::format(detail::TextProperties::TextColor::BasicColorFG::Yellow, + executor); case stream::flog::LogSeverity::Error: - return FormatterType::format(detail::TextProperties::TextColor::BasicColorFG::Red, executor); + return FormatterType::format(detail::TextProperties::TextColor::BasicColorFG::Red, + executor); case stream::flog::LogSeverity::Fatal: - return FormatterType::format(detail::TextProperties::TextColor::BasicColorFG::BrightMagenta, executor); + return FormatterType::format(detail::TextProperties::TextColor::BasicColorFG::BrightMagenta, + executor); } return {}; } }; -} +} // namespace stream::fmt -namespace stream::flog -{ +namespace stream::flog { using BasicLogger = detail::XLogger>; using LoggerMultiSinkFast = detail::XLogger>; using LoggerMultiSinkSafe = detail::XLogger>; @@ -208,13 +185,12 @@ namespace stream::flog extern template class detail::XLogger>; extern template class detail::XLogger>; extern template class detail::XLogger>; -} +} // namespace stream::flog -namespace stream::flog::Sinks -{ +namespace stream::flog::Sinks { using ConsoleSink = BasicConsoleSink; using FileSink = BasicFileSink; extern template class BasicConsoleSink; extern template class BasicFileSink; -} +} // namespace stream::flog::Sinks diff --git a/src/stream/flog/logger_factory.h b/src/stream/flog/logger_factory.h index 6fc7ed9f..8f3bbce6 100644 --- a/src/stream/flog/logger_factory.h +++ b/src/stream/flog/logger_factory.h @@ -5,9 +5,6 @@ #include "backends/logger_multi_sink_safe.h" // TODO: -namespace stream::flog -{ - class LoggerFactory - { - }; -} +namespace stream::flog { + class LoggerFactory {}; +} // namespace stream::flog diff --git a/src/stream/flog/sinks/file_sink.h b/src/stream/flog/sinks/file_sink.h index a3d14144..d459ee65 100644 --- a/src/stream/flog/sinks/file_sink.h +++ b/src/stream/flog/sinks/file_sink.h @@ -6,36 +6,29 @@ #include #include -namespace stream::flog::Sinks -{ +namespace stream::flog::Sinks { template - class BasicConsoleSink : public detail::BasicLoggerSink - { + class BasicConsoleSink : public detail::BasicLoggerSink { public: using Base = detail::BasicLoggerSink; - using typename Base::PatternType; - using typename Base::NameType; using typename Base::BufferType; + using typename Base::NameType; + using typename Base::PatternType; public: - BasicConsoleSink(std::basic_ostream& stream, NameType&& name) - : Base(std::forward(name)) - , m_Stream(stream) - {} + BasicConsoleSink(std::basic_ostream& stream, NameType&& name) : Base(std::forward(name)), m_Stream(stream) {} - BasicConsoleSink(std::basic_ostream& stream, NameType&& name, detail::AsyncSink isAsync) - : Base(std::forward(name), isAsync) - , m_Stream(stream) - {} + BasicConsoleSink(std::basic_ostream& stream, NameType&& name, detail::AsyncSink isAsync) : Base(std::forward(name), isAsync), m_Stream(stream) {} ~BasicConsoleSink() override = default; public: - std::basic_ostream& GetStream() { return m_Stream; } + std::basic_ostream& GetStream() { + return m_Stream; + } protected: - void WriteImpl(const BufferType& bufferToPrint) override - { + void WriteImpl(const BufferType& bufferToPrint) override { m_Stream.write(bufferToPrint.data(), bufferToPrint.size()); m_Stream.write("\n", 1); m_Stream.flush(); @@ -46,28 +39,26 @@ namespace stream::flog::Sinks }; template - class BasicFileSink : public detail::BasicLoggerSink - { + class BasicFileSink : public detail::BasicLoggerSink { public: using Base = detail::BasicLoggerSink; - using typename Base::PatternType; - using typename Base::NameType; using typename Base::BufferType; + using typename Base::NameType; + using typename Base::PatternType; public: BasicFileSink(const std::filesystem::path& filePath, NameType&& name, detail::AsyncSink isAsync) - : Base(std::forward(name), isAsync) - , m_Stream(filePath, std::ios::out) - {} + : Base(std::forward(name), isAsync), m_Stream(filePath, std::ios::out) {} ~BasicFileSink() override = default; public: - std::basic_ostream& GetStream() { return m_Stream; } + std::basic_ostream& GetStream() { + return m_Stream; + } protected: - void WriteImpl(const BufferType& bufferToPrint) override - { + void WriteImpl(const BufferType& bufferToPrint) override { m_Stream.write(bufferToPrint.data(), bufferToPrint.size()); m_Stream.write("\n", 1); m_Stream.flush(); @@ -76,4 +67,4 @@ namespace stream::flog::Sinks private: std::basic_ofstream m_Stream; }; -} +} // namespace stream::flog::Sinks diff --git a/src/stream/flog/sinks/logger_sink.h b/src/stream/flog/sinks/logger_sink.h index 342f592c..49ed328e 100644 --- a/src/stream/flog/sinks/logger_sink.h +++ b/src/stream/flog/sinks/logger_sink.h @@ -4,35 +4,26 @@ #include -namespace stream::flog::detail -{ - enum class AsyncSink - { +namespace stream::flog::detail { + enum class AsyncSink { Sync, Async }; template - class BasicLoggerSink - { + class BasicLoggerSink { public: - using PatternType = std::basic_string; + using PatternType = std::basic_string; using PatternTransferType = std::basic_string_view; - using NameType = std::basic_string; - using BufferType = std::basic_string_view; + using NameType = std::basic_string; + using BufferType = std::basic_string_view; using SeverityValueType = typename Severity::Value; public: - BasicLoggerSink(NameType&& name) - : name(std::forward(name)) - , IsAsync(AsyncSink::Sync) - {} + BasicLoggerSink(NameType&& name) : name(std::forward(name)), IsAsync(AsyncSink::Sync) {} - BasicLoggerSink(NameType&& name, AsyncSink isAsync) - : name(std::forward(name)) - , IsAsync(isAsync) - {} + BasicLoggerSink(NameType&& name, AsyncSink isAsync) : name(std::forward(name)), IsAsync(isAsync) {} virtual ~BasicLoggerSink() = default; @@ -47,16 +38,15 @@ namespace stream::flog::detail std::future m_AsyncWaiter; public: - bool need_to_log(const SeverityValueType& severity) { return severity >= SinkSeverity; } - void WriteToSink(const SeverityValueType& severity, const BufferType& bufferToPrint) - { - if (need_to_log(severity)) - WriteToSink(bufferToPrint); + bool need_to_log(const SeverityValueType& severity) { + return severity >= SinkSeverity; + } + void WriteToSink(const SeverityValueType& severity, const BufferType& bufferToPrint) { + if (need_to_log(severity)) WriteToSink(bufferToPrint); } public: - PatternTransferType get_pattern(const typename Severity::Value& severity) const - { + PatternTransferType get_pattern(const typename Severity::Value& severity) const { PatternTransferType customPattern = SeverityPatternOverride.get_pattern(severity); if (customPattern.data() == nullptr || customPattern.size() == 0) return Pattern; return customPattern; @@ -66,14 +56,14 @@ namespace stream::flog::detail virtual void WriteImpl(const BufferType& bufferToPrint) = 0; public: - void WriteToSinkSync(const BufferType& bufferToPrint) { WriteImpl(bufferToPrint); } - void WriteToSinkAsync(const BufferType& bufferToPrint) - { + void WriteToSinkSync(const BufferType& bufferToPrint) { + WriteImpl(bufferToPrint); + } + void WriteToSinkAsync(const BufferType& bufferToPrint) { m_AsyncWaiter = std::async(std::launch::async, &BasicLoggerSink::WriteToSinkSync, this, bufferToPrint); } - void WriteToSink(const BufferType& bufferToPrint) - { + void WriteToSink(const BufferType& bufferToPrint) { if (IsAsync == AsyncSink::Sync) WriteToSinkSync(bufferToPrint); else @@ -81,33 +71,31 @@ namespace stream::flog::detail } public: - void wait_until_finished_to_write() - { + void wait_until_finished_to_write() { if (IsAsync == AsyncSink::Async) return m_AsyncWaiter.get(); } - [[nodiscard]] std::expected FormatAndWriteToSinkSync(PatternTransferType pattern, const std::chrono::nanoseconds& logTime, const NameType& loggerName, const BufferType& formatBuffer) - { + [[nodiscard]] std::expected FormatAndWriteToSinkSync(PatternTransferType pattern, const std::chrono::nanoseconds& logTime, const NameType& loggerName, + const BufferType& formatBuffer) { fmt::buf::DynamicStreamIOManager manager(256); - auto format_pattern_str = SF_TRY(fmt::detail::format_in_manager(manager, false, pattern, FORMAT_SV("time", logTime), FORMAT_SV("name", ConcatNameAndSinkName(loggerName, name)), - FORMAT_SV("data", formatBuffer))); - BufferType buffer(*format_pattern_str); + auto format_pattern_str = SF_TRY(fmt::detail::format_in_manager(manager, false, pattern, FORMAT_SV("time", logTime), + FORMAT_SV("name", ConcatNameAndSinkName(loggerName, name)), FORMAT_SV("data", formatBuffer))); + BufferType buffer(*format_pattern_str); WriteToSinkSync(buffer); return {}; } - [[nodiscard]] std::expected FormatAndWriteToSinkAsync(PatternTransferType pattern, const std::chrono::nanoseconds& logTime, const NameType& loggerName, const BufferType& formatBuffer) - { + [[nodiscard]] std::expected FormatAndWriteToSinkAsync(PatternTransferType pattern, const std::chrono::nanoseconds& logTime, + const NameType& loggerName, const BufferType& formatBuffer) { // TODO m_AsyncWaiter = std::async(std::launch::async, &BasicLoggerSink::FormatAndWriteToSinkSync, this, pattern, logTime, loggerName, formatBuffer); return {}; } - [[nodiscard]] std::expected format_and_write_to_sink(PatternTransferType pattern, const std::chrono::nanoseconds& logTime, const NameType& loggerName, const BufferType& formatBuffer) - { - if (IsAsync == AsyncSink::Sync) - return FormatAndWriteToSinkSync(pattern, logTime, loggerName, formatBuffer); + [[nodiscard]] std::expected format_and_write_to_sink(PatternTransferType pattern, const std::chrono::nanoseconds& logTime, const NameType& loggerName, + const BufferType& formatBuffer) { + if (IsAsync == AsyncSink::Sync) return FormatAndWriteToSinkSync(pattern, logTime, loggerName, formatBuffer); return FormatAndWriteToSinkAsync(pattern, logTime, loggerName, formatBuffer); } }; -} +} // namespace stream::flog::detail diff --git a/src/stream/fmt/buf/fmt_manip_io.h b/src/stream/fmt/buf/fmt_manip_io.h index d67f4b70..6ae7f848 100644 --- a/src/stream/fmt/buf/fmt_manip_io.h +++ b/src/stream/fmt/buf/fmt_manip_io.h @@ -4,11 +4,9 @@ #include "manip_io.h" #include "test_manip.h" -namespace stream::fmt::buf -{ +namespace stream::fmt::buf { template - class FMTStreamIO : public StreamIO - { + class FMTStreamIO : public StreamIO { public: using typename StreamIO::TChar; @@ -19,15 +17,12 @@ namespace stream::fmt::buf using StreamIO::get; using StreamIO::Manager; - + protected: - FMTStreamIO(BasicStreamIOManager& ostream_manager) noexcept - : StreamIO(ostream_manager) - {} + FMTStreamIO(BasicStreamIOManager& ostream_manager) noexcept : StreamIO(ostream_manager) {} public: - [[nodiscard]] static std::expected, FMTResult> create(BasicStreamIOManager& ostream_manager) - { + [[nodiscard]] static std::expected, FMTResult> create(BasicStreamIOManager& ostream_manager) { FMTStreamIO res(ostream_manager); SF_TRY(StreamIO::init(res)); return res; @@ -35,84 +30,85 @@ namespace stream::fmt::buf public: std::size_t NoStride = 0; - std::size_t indent = 0; + std::size_t indent = 0; }; template - class FMTManipIO - { + class FMTManipIO { public: FMTManipIO(FMTStreamIO& buffer) : buffer(buffer) {} + public: FMTStreamIO& buffer; public: - constexpr inline void add_no_stride(const std::size_t no_stride) noexcept { buffer.NoStride += no_stride; } + constexpr inline void add_no_stride(const std::size_t no_stride) noexcept { + buffer.NoStride += no_stride; + } + + constexpr inline void add_indent(const std::size_t indent) noexcept { + buffer.indent += indent; + } + constexpr inline void remove_indent(const std::size_t indent) noexcept { + buffer.indent -= indent; + } + constexpr inline void set_indent() noexcept { + buffer.indent = Manip(buffer).get_buffer_current_size() - buffer.NoStride; + } - constexpr inline void add_indent(const std::size_t indent) noexcept { buffer.indent += indent; } - constexpr inline void remove_indent(const std::size_t indent) noexcept { buffer.indent -= indent; } - constexpr inline void set_indent() noexcept { buffer.indent = Manip(buffer).get_buffer_current_size() - buffer.NoStride; } - public: - [[nodiscard]] constexpr inline std::expected new_line_indent() - { + [[nodiscard]] constexpr inline std::expected new_line_indent() { SF_TRY(ManipIO(buffer).pushback('\n')); return ManipIO(buffer).pushback(' ', buffer.indent); } - [[nodiscard]] constexpr inline std::expected pushback_check_indent(const TChar c) - { + [[nodiscard]] constexpr inline std::expected pushback_check_indent(const TChar c) { SF_TRY(ManipIO(buffer).pushback(c)); - if (c == '\n') - { return ManipIO(buffer).pushback(' ', buffer.indent); } + if (c == '\n') { + return ManipIO(buffer).pushback(' ', buffer.indent); + } return {}; } }; template - class FMTParamsManip - { + class FMTParamsManip { public: FMTParamsManip(Stream& buffer) : buffer(buffer) {} + public: Stream& buffer; public: template - inline void param_go_to(const CharToTest... ele) - { + inline void param_go_to(const CharToTest... ele) { TestManip(buffer).GoTo(ele..., '}'); } template - [[nodiscard]] inline std::expected param_go_to_forward(const CharToTest... ele) - { + [[nodiscard]] inline std::expected param_go_to_forward(const CharToTest... ele) { return TestManip(buffer).go_to_forward(ele..., '}'); } - inline bool is_begin_of_parameter() - { + inline bool is_begin_of_parameter() { return TestAccess(buffer).is_equal_to('{'); } - inline bool is_end_of_parameter() - { + inline bool is_end_of_parameter() { return TestAccess(buffer).is_equal_to('}'); } public: template - [[nodiscard]] std::expected next_is_named_args(const std::basic_string_view& sv) - { + [[nodiscard]] std::expected next_is_named_args(const std::basic_string_view& sv) { TestAccess access(buffer); - TestManip manip(buffer); + TestManip manip(buffer); - TChar* const oldpos = buffer.current_pos; - auto is_same = SF_TRY(manip.is_same_forward(sv)); - if (is_same && (access.is_equal_to(':') || access.is_equal_to('}'))) - { + TChar* const oldpos = buffer.current_pos; + auto is_same = SF_TRY(manip.is_same_forward(sv)); + if (is_same && (access.is_equal_to(':') || access.is_equal_to('}'))) { return true; } buffer.current_pos = oldpos; return false; } }; -} +} // namespace stream::fmt::buf diff --git a/src/stream/fmt/buf/fmt_read_manip.h b/src/stream/fmt/buf/fmt_read_manip.h index 2a89cd8c..1b97c2b8 100644 --- a/src/stream/fmt/buf/fmt_read_manip.h +++ b/src/stream/fmt/buf/fmt_read_manip.h @@ -6,28 +6,25 @@ #include "stream/fmt/buf/test_manip.h" #include "stream/fmt/buf/read_manip.h" -namespace stream::fmt::buf -{ +namespace stream::fmt::buf { template - class FMTReadManip - { + class FMTReadManip { public: FMTReadManip(Stream& buffer) : buffer(buffer) {} + public: Stream& buffer; public: template - [[nodiscard]] std::expected read_integer(T& i, detail::ShiftInfo shift = detail::ShiftInfo{}) - { + [[nodiscard]] std::expected read_integer(T& i, detail::ShiftInfo shift = detail::ShiftInfo{}) { ShiftReadManip shift_manip(buffer); buf::TestManip manip(buffer); SF_TRY(shift_manip.ignore_shift_begin_space(shift)); bool sign = false; - if constexpr (std::is_signed_v) - { + if constexpr (std::is_signed_v) { sign = SF_TRY(manip.is_equal_to_forward('-')); if (sign) --shift.size; } @@ -35,10 +32,9 @@ namespace stream::fmt::buf TestAccess(buffer).is_a_digit(); T res = (T)0; - while (TestAccess(buffer).is_a_digit()) - { + while (TestAccess(buffer).is_a_digit()) { char c = SF_TRY(Manip(buffer).get_and_forward()); - res = res * 10 + (c - '0'); + res = res * 10 + (c - '0'); --shift.size; } @@ -47,44 +43,39 @@ namespace stream::fmt::buf i = sign ? -res : res; return {}; } + public: template - [[nodiscard]] std::expected read_float(T& t, std::int32_t float_precision = -1, detail::ShiftInfo shift = detail::ShiftInfo{}) - { - ShiftReadManip shift_manip(buffer); + [[nodiscard]] std::expected read_float(T& t, std::int32_t float_precision = -1, detail::ShiftInfo shift = detail::ShiftInfo{}) { + ShiftReadManip shift_manip(buffer); buf::TestAccess access(buffer); - buf::TestManip manip(buffer); - + buf::TestManip manip(buffer); + SF_TRY(shift_manip.ignore_shift_begin_space(shift)); bool sign = SF_TRY(manip.is_equal_to_forward('-')); if (sign) --shift.size; T intpart = static_cast(0); - if (access.is_a_digit()) - { - while (access.is_a_digit()) - { - char c = SF_TRY(Manip(buffer).get_and_forward()); + if (access.is_a_digit()) { + while (access.is_a_digit()) { + char c = SF_TRY(Manip(buffer).get_and_forward()); intpart = intpart * 10 + (c - '0'); --shift.size; } + } else if (access.is_equal_to('.')) { + SF_TRY(buf::Manip(buffer).forward()); + } else { + return std::unexpected(FMTResult::Parse_NonValidDigit); } - else if (access.is_equal_to('.')) - { SF_TRY(buf::Manip(buffer).forward()); } - else - { return std::unexpected(FMTResult::Parse_NonValidDigit); } if (float_precision <= 0) - while (access.is_a_digit() && access.is_end_of_string() == false) - { + while (access.is_a_digit() && access.is_end_of_string() == false) { Manip(buffer).forward_force(); --shift.size; } - else - { - while (Access(buffer).is_a_digit() && float_precision > 0 && Access(buffer).is_end_of_string() == false) - { + else { + while (Access(buffer).is_a_digit() && float_precision > 0 && Access(buffer).is_end_of_string() == false) { Manip(buffer).forward_force(); float_precision--; --shift.size; @@ -93,8 +84,7 @@ namespace stream::fmt::buf Manip(buffer).backward_force(); T dec = (T)0; - while (access.is_a_digit()) - { + while (access.is_a_digit()) { dec += static_cast(buffer.get() - '0'); Manip(buffer).backward_force(); dec /= 10; @@ -102,32 +92,30 @@ namespace stream::fmt::buf SF_TRY(shift_manip.ignore_shift_end(shift)); - t = sign ? - intpart - dec : intpart + dec; + t = sign ? -intpart - dec : intpart + dec; return {}; } public: template - [[nodiscard]] std::expected read_integer_h(T& i, std::uint8_t digitSize, std::uint8_t (&digit_lut)(TChar), TChar base_prefix = '\0', detail::ShiftInfo shift = detail::ShiftInfo{}) - { - ShiftReadManip shift_manip(buffer); + [[nodiscard]] std::expected read_integer_h(T& i, std::uint8_t digitSize, std::uint8_t (&digit_lut)(TChar), TChar base_prefix = '\0', + detail::ShiftInfo shift = detail::ShiftInfo{}) { + ShiftReadManip shift_manip(buffer); buf::TestAccess access(buffer); - buf::TestManip manip(buffer); + buf::TestManip manip(buffer); shift.size -= sizeof(T) * 8; if (base_prefix != '\0') shift.size -= 2; SF_TRY(shift_manip.ignore_shift_begin_space(shift)); - if (base_prefix != '\0') - { + if (base_prefix != '\0') { SF_TRY(manip.skip_one_of('0')); SF_TRY(manip.skip_one_of(base_prefix)); } T res = (T)0; - while (digit_lut(buffer.get()) != std::numeric_limits::max()) - { + while (digit_lut(buffer.get()) != std::numeric_limits::max()) { res = res << digitSize; res += digit_lut(buffer.get()); Manip(buffer).forward_force(); @@ -140,49 +128,35 @@ namespace stream::fmt::buf } protected: - static constexpr std::uint8_t digit_lut_bin(TChar in) - { + static constexpr std::uint8_t digit_lut_bin(TChar in) { if (in == '0') return 0; if (in == '1') return 1; return std::numeric_limits::max(); } - static constexpr std::uint8_t digit_lut_oct(TChar in) - { - if (in >= '0' && in <= '7') - return in - '0'; + static constexpr std::uint8_t digit_lut_oct(TChar in) { + if (in >= '0' && in <= '7') return in - '0'; return std::numeric_limits::max(); } - static constexpr std::uint8_t digit_lut_dec(TChar in) - { - if (in >= '0' && in <= '9') - return in - '0'; + static constexpr std::uint8_t digit_lut_dec(TChar in) { + if (in >= '0' && in <= '9') return in - '0'; return std::numeric_limits::max(); } - static constexpr std::uint8_t digit_lut_hexupper(TChar in) - { - if (in >= '0' && in <= '9') - return in - '0'; - if (in >= 'A' && in <= 'F') - return in - 'A'; + static constexpr std::uint8_t digit_lut_hexupper(TChar in) { + if (in >= '0' && in <= '9') return in - '0'; + if (in >= 'A' && in <= 'F') return in - 'A'; return std::numeric_limits::max(); } - static constexpr std::uint8_t digit_lut_hexlower(TChar in) - { - if (in >= '0' && in <= '9') - return in - '0'; - if (in >= 'a' && in <= 'f') - return in - 'a'; + static constexpr std::uint8_t digit_lut_hexlower(TChar in) { + if (in >= '0' && in <= '9') return in - '0'; + if (in >= 'a' && in <= 'f') return in - 'a'; return std::numeric_limits::max(); } public: template - [[nodiscard]] std::expected read_integer_format_data(T& i, const detail::FormatData& formatdata) - { - if (formatdata.has_spec) - { - switch (formatdata.integer_print) - { + [[nodiscard]] std::expected read_integer_format_data(T& i, const detail::FormatData& formatdata) { + if (formatdata.has_spec) { + switch (formatdata.integer_print) { case detail::IntegerPrintBase::Dec: if (formatdata.shift.type == detail::ShiftInfo::ShiftType::Nothing) return ReadManip(buffer).fast_read_integer(i); @@ -203,10 +177,8 @@ namespace stream::fmt::buf return ReadManip(buffer).fast_read_integer(i); } template - [[nodiscard]] std::expected read_float_format_data(T& i, const detail::FormatData& formatdata) - { - if (formatdata.has_spec) - { + [[nodiscard]] std::expected read_float_format_data(T& i, const detail::FormatData& formatdata) { + if (formatdata.has_spec) { if (formatdata.ShiftType == detail::ShiftInfo::ShiftType::Nothing) return ReadManip(buffer).fast_read_float(i, formatdata.float_precision); else @@ -217,22 +189,20 @@ namespace stream::fmt::buf public: template - [[nodiscard]] std::expected read_char_ptr(const CharStr* str, std::size_t sizeContainer, std::size_t sizeToWrite, detail::ShiftInfo shift = detail::ShiftInfo{}) - { + [[nodiscard]] std::expected read_char_ptr(const CharStr* str, std::size_t sizeContainer, std::size_t sizeToWrite, + detail::ShiftInfo shift = detail::ShiftInfo{}) { // FIXME // TODO return std::unexpected(FMTResult::FunctionNotImpl); } template - [[nodiscard]] inline std::expected read_char_array(const CharStr (&str)[SIZE], detail::ShiftInfo shift = detail::ShiftInfo{}) - { + [[nodiscard]] inline std::expected read_char_array(const CharStr (&str)[SIZE], detail::ShiftInfo shift = detail::ShiftInfo{}) { return read_char_ptr(str, SIZE, 0, shift); } template - [[nodiscard]] inline std::expected read_char_bound(const CharStr* begin, const CharStr* end, detail::ShiftInfo shift = detail::ShiftInfo{}) - { + [[nodiscard]] inline std::expected read_char_bound(const CharStr* begin, const CharStr* end, detail::ShiftInfo shift = detail::ShiftInfo{}) { return read_char_ptr(begin, end - begin, 0, shift); } }; -} +} // namespace stream::fmt::buf diff --git a/src/stream/fmt/buf/fmt_write_manip.h b/src/stream/fmt/buf/fmt_write_manip.h index 3948011e..38705ba3 100644 --- a/src/stream/fmt/buf/fmt_write_manip.h +++ b/src/stream/fmt/buf/fmt_write_manip.h @@ -8,50 +8,47 @@ #include -namespace stream::fmt::buf -{ +namespace stream::fmt::buf { template - class FMTWriteManip - { + class FMTWriteManip { public: FMTWriteManip(FMTStreamIO& buffer) : buffer(buffer) {} + public: FMTStreamIO& buffer; public: template - [[nodiscard]] std::expected write_integer(T i, detail::ShiftInfo shift = detail::ShiftInfo{}) - { + [[nodiscard]] std::expected write_integer(T i, detail::ShiftInfo shift = detail::ShiftInfo{}) { char old_after = shift.print.after; - if (shift.print.after >= '0' && shift.print.after <= '9') - shift.print.after = ' '; + if (shift.print.after >= '0' && shift.print.after <= '9') shift.print.after = ' '; std::int32_t nb_digit = WriteUtils::get_number_of_digit_dec(i); shift.size -= nb_digit; if (i < 0) --shift.size; - if (shift.size <= 0) - { return WriteManip(buffer).fast_write_integer(i); } + if (shift.size <= 0) { + return WriteManip(buffer).fast_write_integer(i); + } - if (!shift.print.before_is_a_digit()) - { SF_TRY(ShiftWriteManip(buffer).write_shift_begin(shift)); } - if (i < 0) - { + if (!shift.print.before_is_a_digit()) { + SF_TRY(ShiftWriteManip(buffer).write_shift_begin(shift)); + } + if (i < 0) { SF_TRY(ManipIO(buffer).pushback('-')); i = -i; } - if (shift.print.before_is_a_digit()) - { SF_TRY(ShiftWriteManip(buffer).write_shift_right_all(shift)); } + if (shift.print.before_is_a_digit()) { + SF_TRY(ShiftWriteManip(buffer).write_shift_right_all(shift)); + } - if (i == 0) - { SF_TRY(ManipIO(buffer).pushback('0')); } - else - { + if (i == 0) { + SF_TRY(ManipIO(buffer).pushback('0')); + } else { SF_TRY(ManipIO(buffer).forward(nb_digit)); std::int32_t nb_digit_ = nb_digit; - while (nb_digit_ > 0) - { + while (nb_digit_ > 0) { Manip(buffer).backward_force(); buffer.set(i % 10 + '0'); i /= 10; @@ -68,39 +65,37 @@ namespace stream::fmt::buf public: template - [[nodiscard]] std::expected write_float(T i, std::int32_t float_precision = 2, detail::ShiftInfo shift = detail::ShiftInfo{}) - { + [[nodiscard]] std::expected write_float(T i, std::int32_t float_precision = 2, detail::ShiftInfo shift = detail::ShiftInfo{}) { char old_before = shift.print.before; - if (shift.print.before >= '0' && shift.print.before <= '9') - shift.print.before = ' '; + if (shift.print.before >= '0' && shift.print.before <= '9') shift.print.before = ' '; std::int32_t nb_digit = WriteUtils::get_number_of_digit_dec(std::trunc(i)); shift.size -= nb_digit + float_precision + 1; if (i < 0) --shift.size; - if (shift.size <= 0) - { return WriteManip(buffer).fast_write_float(i, float_precision); } + if (shift.size <= 0) { + return WriteManip(buffer).fast_write_float(i, float_precision); + } - if (!shift.print.before_is_a_digit()) - { SF_TRY(ShiftWriteManip(buffer).write_shift_begin(shift)); } - if (i < 0) - { + if (!shift.print.before_is_a_digit()) { + SF_TRY(ShiftWriteManip(buffer).write_shift_begin(shift)); + } + if (i < 0) { SF_TRY(ManipIO(buffer).pushback('-')); i = -i; } - if (shift.print.before_is_a_digit()) - { SF_TRY(ShiftWriteManip(buffer).write_shift_right_all(shift)); } + if (shift.print.before_is_a_digit()) { + SF_TRY(ShiftWriteManip(buffer).write_shift_right_all(shift)); + } T k = std::trunc(i); - if (k == 0) - { SF_TRY(ManipIO(buffer).pushback('0')); } - else - { + if (k == 0) { + SF_TRY(ManipIO(buffer).pushback('0')); + } else { SF_TRY(ManipIO(buffer).forward(nb_digit)); std::int32_t nb_digit_ = nb_digit; - while (nb_digit_ > 0) - { + while (nb_digit_ > 0) { Manip(buffer).backward_force(); buffer.set(char(std::fmod(i, 10)) + '0'); k /= 10; @@ -111,8 +106,7 @@ namespace stream::fmt::buf SF_TRY(ManipIO(buffer).pushback('.')); i -= k; - while (float_precision-- != 0) - { + while (float_precision-- != 0) { T decimal = std::trunc(i *= 10); SF_TRY(ManipIO(buffer).pushback((char)decimal + '0')); i -= decimal; @@ -126,34 +120,31 @@ namespace stream::fmt::buf public: template - [[nodiscard]] std::expected write_integer_h(T i, std::uint8_t digitSize, const TChar* const lut, TChar base_prefix = '\0', detail::ShiftInfo shift = detail::ShiftInfo{}) - { + [[nodiscard]] std::expected write_integer_h(T i, std::uint8_t digitSize, const TChar* const lut, TChar base_prefix = '\0', + detail::ShiftInfo shift = detail::ShiftInfo{}) { ManipIO manip(buffer); std::int32_t digit_count = sizeof(T) * 8; { // Remove leading 0 std::int32_t last_pos_with_data = 0; - std::int32_t k = digit_count + 1; - T cpyI = i; - while (--k != 0) - { + std::int32_t k = digit_count + 1; + T cpyI = i; + while (--k != 0) { if ((cpyI & (0b1 << digitSize)) != 0) last_pos_with_data = k; cpyI = cpyI >> digitSize; } digit_count -= last_pos_with_data; } - if (base_prefix != '\0') - { + if (base_prefix != '\0') { SF_TRY(ManipIO(buffer).pushback('0')); SF_TRY(ManipIO(buffer).pushback(base_prefix)); } SF_TRY(manip.forward(digit_count)); std::int32_t k = digit_count + 1; - while (--k != 0) - { + while (--k != 0) { Manip(buffer).backward_force(); buffer.set(lut[i & (0b1 << digitSize)]); i = i >> digitSize; @@ -164,12 +155,9 @@ namespace stream::fmt::buf public: template - [[nodiscard]] std::expected write_integer_format_data(T i, const detail::FormatData& formatdata) - { - if (formatdata.has_spec) - { - switch (formatdata.integer_print) - { + [[nodiscard]] std::expected write_integer_format_data(T i, const detail::FormatData& formatdata) { + if (formatdata.has_spec) { + switch (formatdata.integer_print) { case detail::IntegerPrintBase::Dec: if (formatdata.shift.type == detail::ShiftInfo::ShiftType::Nothing) return WriteManip(buffer).fast_write_integer(i); @@ -185,18 +173,14 @@ namespace stream::fmt::buf return write_integer_h(i, 4, WriteManip::LOWER_HEX, formatdata.prefix_suffix ? (char)formatdata.integer_print : '\0', formatdata.shift); case detail::IntegerPrintBase::HexUpper: return write_integer_h(i, 4, WriteManip::UPPER_HEX, formatdata.prefix_suffix ? (char)formatdata.integer_print : '\0', formatdata.shift); - } } return WriteManip(buffer).fast_write_integer(i); } template - [[nodiscard]] std::expected write_float_formatdata(T i, const detail::FormatData& formatdata) - { - if (formatdata.has_spec) - { - if (formatdata.shift.type != detail::ShiftInfo::ShiftType::Nothing) - return write_float(i, formatdata.float_precision, formatdata.shift); + [[nodiscard]] std::expected write_float_formatdata(T i, const detail::FormatData& formatdata) { + if (formatdata.has_spec) { + if (formatdata.shift.type != detail::ShiftInfo::ShiftType::Nothing) return write_float(i, formatdata.float_precision, formatdata.shift); } return WriteManip(buffer).fast_write_float(i, formatdata.float_precision); @@ -204,21 +188,17 @@ namespace stream::fmt::buf public: template - [[nodiscard]] inline std::expected write_indent_char_ptr(const CharStr* str, std::size_t size) - { - while (size > 0) - { + [[nodiscard]] inline std::expected write_indent_char_ptr(const CharStr* str, std::size_t size) { + while (size > 0) { const CharStr* const begin = str; - while (size > 0 && *str != '\n') - { + while (size > 0 && *str != '\n') { ++str, --size; } const CharStr* const end = str; SF_TRY(WriteManip(buffer).fast_write_char_array(begin, end - begin)); - if (size > 0 && *str == '\n') - { + if (size > 0 && *str == '\n') { SF_TRY(FMTManipIO(buffer).new_line_indent()); ++str; --size; @@ -227,26 +207,21 @@ namespace stream::fmt::buf return {}; } template - [[nodiscard]] inline std::expected write_indent_char_bound(const CharStr* begin, const CharStr* end) - { + [[nodiscard]] inline std::expected write_indent_char_bound(const CharStr* begin, const CharStr* end) { return write_indent_char_ptr(begin, end - begin); } template - [[nodiscard]] inline std::expected write_indent_string(std::basic_string_view str) - { + [[nodiscard]] inline std::expected write_indent_string(std::basic_string_view str) { return write_indent_char_ptr(str.data(), str.size()); } template - [[nodiscard]] inline std::expected write_char_ptr(const CharStr* str, std::size_t size, detail::ShiftInfo& shift) - { - if (shift.size <= 0) - return WriteManip(buffer).fast_write_char_array(str, size); - + [[nodiscard]] inline std::expected write_char_ptr(const CharStr* str, std::size_t size, detail::ShiftInfo& shift) { + if (shift.size <= 0) return WriteManip(buffer).fast_write_char_array(str, size); + SF_TRY(ManipIO(buffer).reserve(std::max(static_cast(shift.size), size))); - if (static_cast(shift.size) > size) - { + if (static_cast(shift.size) > size) { shift.size -= static_cast(size); SF_TRY(ShiftWriteManip(buffer).write_shift_begin(shift)); @@ -254,22 +229,18 @@ namespace stream::fmt::buf SF_TRY(WriteManip(buffer).fast_write_char_array(str, size)); SF_TRY(ShiftWriteManip(buffer).write_shift_end(shift)); - } - else - { + } else { SF_TRY(WriteManip(buffer).fast_write_char_array(str, size)); } return {}; } template - [[nodiscard]] inline std::expected write_char_bound(const CharStr* begin, const CharStr* end, detail::ShiftInfo& shift) - { + [[nodiscard]] inline std::expected write_char_bound(const CharStr* begin, const CharStr* end, detail::ShiftInfo& shift) { return write_char_ptr(begin, end - begin, shift); } template - [[nodiscard]] inline std::expected write_string(std::basic_string_view str, detail::ShiftInfo& shift) - { + [[nodiscard]] inline std::expected write_string(std::basic_string_view str, detail::ShiftInfo& shift) { return write_char_ptr(str.data(), str.size(), shift); } }; -} +} // namespace stream::fmt::buf diff --git a/src/stream/fmt/buf/manip.h b/src/stream/fmt/buf/manip.h index 250ffab8..25046ebc 100644 --- a/src/stream/fmt/buf/manip.h +++ b/src/stream/fmt/buf/manip.h @@ -2,100 +2,111 @@ #include "stream.h" -namespace stream::fmt::buf -{ +namespace stream::fmt::buf { template - class Access - { + class Access { public: constexpr inline Access(const Stream& buffer) noexcept : buffer(buffer) {} + public: const Stream& buffer; - + public: - constexpr inline std::size_t get_buffer_total_size() const noexcept { return static_cast(buffer.buffer_end - buffer.buffer); } - constexpr inline std::size_t get_buffer_current_size() const noexcept { return static_cast(buffer.current_pos - buffer.buffer); } - constexpr inline std::size_t get_buffer_remaining_size() const noexcept { return static_cast(buffer.buffer_end - buffer.current_pos); } + constexpr inline std::size_t get_buffer_total_size() const noexcept { + return static_cast(buffer.buffer_end - buffer.buffer); + } + constexpr inline std::size_t get_buffer_current_size() const noexcept { + return static_cast(buffer.current_pos - buffer.buffer); + } + constexpr inline std::size_t get_buffer_remaining_size() const noexcept { + return static_cast(buffer.buffer_end - buffer.current_pos); + } public: - constexpr inline bool can_move_forward(const std::size_t count = 1) const noexcept { return buffer.current_pos + count <= buffer.buffer_end; } - constexpr inline bool can_move_backward(const std::size_t count = 1) const noexcept { return buffer.current_pos - count >= buffer.buffer; } + constexpr inline bool can_move_forward(const std::size_t count = 1) const noexcept { + return buffer.current_pos + count <= buffer.buffer_end; + } + constexpr inline bool can_move_backward(const std::size_t count = 1) const noexcept { + return buffer.current_pos - count >= buffer.buffer; + } - constexpr inline bool is_out_of_bound() const noexcept { return buffer.current_pos < buffer.buffer || buffer.current_pos >= buffer.buffer_end; } - constexpr inline bool is_empty() const noexcept { return buffer.current_pos >= buffer.buffer_end; } - constexpr inline bool is_end_of_string() const noexcept { return is_empty() || buffer.get() == 0; } + constexpr inline bool is_out_of_bound() const noexcept { + return buffer.current_pos < buffer.buffer || buffer.current_pos >= buffer.buffer_end; + } + constexpr inline bool is_empty() const noexcept { + return buffer.current_pos >= buffer.buffer_end; + } + constexpr inline bool is_end_of_string() const noexcept { + return is_empty() || buffer.get() == 0; + } - [[nodiscard]] constexpr inline std::expected, FMTResult> get_next(const std::size_t count = 1) const - { - if (Access(buffer).can_move_forward(count) == false) - return std::unexpected(FMTResult::Buffer_OutOfBoundAccess); + [[nodiscard]] constexpr inline std::expected, FMTResult> get_next(const std::size_t count = 1) const { + if (Access(buffer).can_move_forward(count) == false) return std::unexpected(FMTResult::Buffer_OutOfBoundAccess); return Manip(buffer).get_next_force(count); } - [[nodiscard]] constexpr inline std::expected, FMTResult> get_prev(const std::size_t count = 1) const - { - if (Access(buffer).can_move_backward(count) == false) - return std::unexpected(FMTResult::Buffer_OutOfBoundAccess); + [[nodiscard]] constexpr inline std::expected, FMTResult> get_prev(const std::size_t count = 1) const { + if (Access(buffer).can_move_backward(count) == false) return std::unexpected(FMTResult::Buffer_OutOfBoundAccess); return Manip(buffer).get_prev_force(count); } - constexpr inline TChar get_next_force(const std::size_t count = 1) const noexcept { return *(buffer.current_pos + count); } - constexpr inline TChar get_prev_force(const std::size_t count = 1) const noexcept { return *(buffer.current_pos - count); } + constexpr inline TChar get_next_force(const std::size_t count = 1) const noexcept { + return *(buffer.current_pos + count); + } + constexpr inline TChar get_prev_force(const std::size_t count = 1) const noexcept { + return *(buffer.current_pos - count); + } }; template - class Manip - { + class Manip { public: constexpr inline Manip(Stream& buffer) noexcept : buffer(buffer) {} + public: Stream& buffer; - + public: - constexpr inline void reload(TChar* const buffer_, const std::size_t size_) noexcept - { + constexpr inline void reload(TChar* const buffer_, const std::size_t size_) noexcept { buffer.buffer = buffer_; buffer.current_pos = buffer_; buffer.buffer_end = buffer_ + size_; } - constexpr inline void reload(Stream& buffer_) noexcept - { + constexpr inline void reload(Stream& buffer_) noexcept { buffer.buffer = buffer_.buffer; buffer.current_pos = buffer_.current_pos; buffer.buffer_end = buffer_.buffer_end; } - Access access() { return Access(buffer); } + Access access() { + return Access(buffer); + } public: - constexpr inline void forward_force(const std::size_t count = 1) noexcept { buffer.current_pos += count; } - [[nodiscard]] constexpr inline std::expected forward(const std::size_t count = 1) noexcept - { - if (!access().can_move_forward(count)) - return std::unexpected(FMTResult::Buffer_OutOfBoundAccess); + constexpr inline void forward_force(const std::size_t count = 1) noexcept { + buffer.current_pos += count; + } + [[nodiscard]] constexpr inline std::expected forward(const std::size_t count = 1) noexcept { + if (!access().can_move_forward(count)) return std::unexpected(FMTResult::Buffer_OutOfBoundAccess); buffer.current_pos += count; return {}; } - constexpr inline void backward_force(const std::size_t count = 1) noexcept { buffer.current_pos -= count; } - [[nodiscard]] constexpr inline std::expected backward(const std::size_t count = 1) noexcept - { - if (!access().can_move_backward(count)) - return std::unexpected(FMTResult::Buffer_OutOfBoundAccess); + constexpr inline void backward_force(const std::size_t count = 1) noexcept { + buffer.current_pos -= count; + } + [[nodiscard]] constexpr inline std::expected backward(const std::size_t count = 1) noexcept { + if (!access().can_move_backward(count)) return std::unexpected(FMTResult::Buffer_OutOfBoundAccess); buffer.current_pos -= count; return {}; } - [[nodiscard]] constexpr inline std::expected, FMTResult> get_and_forward() - { - if (Access(buffer).can_move_forward(1) == false) - return std::unexpected(FMTResult::Buffer_OutOfBoundAccess); + [[nodiscard]] constexpr inline std::expected, FMTResult> get_and_forward() { + if (Access(buffer).can_move_forward(1) == false) return std::unexpected(FMTResult::Buffer_OutOfBoundAccess); return *buffer.current_pos++; } - [[nodiscard]] constexpr inline std::expected, FMTResult> get_and_backward() - { - if (Access(buffer).can_move_backward(1) == false) - return std::unexpected(FMTResult::Buffer_OutOfBoundAccess); + [[nodiscard]] constexpr inline std::expected, FMTResult> get_and_backward() { + if (Access(buffer).can_move_backward(1) == false) return std::unexpected(FMTResult::Buffer_OutOfBoundAccess); return *buffer.current_pos--; } }; -} +} // namespace stream::fmt::buf diff --git a/src/stream/fmt/buf/manip_io.h b/src/stream/fmt/buf/manip_io.h index 5da3b25c..616308e9 100644 --- a/src/stream/fmt/buf/manip_io.h +++ b/src/stream/fmt/buf/manip_io.h @@ -6,22 +6,22 @@ #include "streamio_manager/basic_streamio_manager.h" -namespace stream::fmt::buf -{ +namespace stream::fmt::buf { template - class ManipIO - { + class ManipIO { public: constexpr inline ManipIO(StreamIO& buffer) noexcept : buffer(buffer) {} + public: StreamIO& buffer; public: - void compute_generated_size() noexcept { buffer.Manager.compute_generated_size(Access(buffer).get_buffer_current_size()); } + void compute_generated_size() noexcept { + buffer.Manager.compute_generated_size(Access(buffer).get_buffer_current_size()); + } public: - [[nodiscard]] std::expected add_size(const std::size_t count) noexcept - { + [[nodiscard]] std::expected add_size(const std::size_t count) noexcept { std::size_t currentSize = Access(buffer).get_buffer_current_size(); SF_TRY(buffer.Manager.add_size(count)) Manip(buffer).reload(buffer.Manager.get_buffer(), buffer.Manager.get_buffer_size()); @@ -29,34 +29,33 @@ namespace stream::fmt::buf return {}; } - [[nodiscard]] inline std::expected reserve(const std::size_t count = 1) noexcept - { - if (buffer.current_pos + count <= buffer.buffer_end) - return {}; + [[nodiscard]] inline std::expected reserve(const std::size_t count = 1) noexcept { + if (buffer.current_pos + count <= buffer.buffer_end) return {}; return add_size(static_cast(count)); } - [[nodiscard]] inline std::expected forward(const std::size_t count = 1) noexcept - { + [[nodiscard]] inline std::expected forward(const std::size_t count = 1) noexcept { SF_TRY(reserve(count)); buffer.current_pos += count; return {}; } public: - inline void set(const TChar c) noexcept { *buffer.current_pos = c; } - - [[nodiscard]] inline std::expected pushback(const TChar c) noexcept - { + inline void set(const TChar c) noexcept { + *buffer.current_pos = c; + } + + [[nodiscard]] inline std::expected pushback(const TChar c) noexcept { SF_TRY(reserve(1)); *buffer.current_pos++ = c; return {}; } - inline void pushback_force(const TChar c) noexcept { *buffer.current_pos++ = c; } + inline void pushback_force(const TChar c) noexcept { + *buffer.current_pos++ = c; + } public: - [[nodiscard]] inline std::expected pushback(const TChar c, auto count) noexcept - { + [[nodiscard]] inline std::expected pushback(const TChar c, auto count) noexcept { SF_TRY(reserve(count)) while (count-- > 0) pushback_force(c); @@ -65,19 +64,17 @@ namespace stream::fmt::buf private: template - inline void pushback_seq_impl(const TChar c, const Rest... rest) noexcept - { + inline void pushback_seq_impl(const TChar c, const Rest... rest) noexcept { force_pushback(c); if constexpr (sizeof...(rest) > 0) pushback_seq_impl(rest...); } public: template - [[nodiscard]] inline std::expected pushback_seq(const CharToPush... ele) noexcept - { + [[nodiscard]] inline std::expected pushback_seq(const CharToPush... ele) noexcept { SF_TRY(reserve(sizeof...(ele))) pushback_seq_impl(ele...); return {}; } }; -} +} // namespace stream::fmt::buf diff --git a/src/stream/fmt/buf/read_manip.h b/src/stream/fmt/buf/read_manip.h index b6ed2cdf..f8883131 100644 --- a/src/stream/fmt/buf/read_manip.h +++ b/src/stream/fmt/buf/read_manip.h @@ -3,32 +3,31 @@ #include "stream/fmt/buf/stream.h" #include "stream/fmt/buf/manip.h" -namespace stream::fmt::buf -{ +namespace stream::fmt::buf { template - class ReadManip - { + class ReadManip { public: constexpr inline ReadManip(Stream& buffer_) noexcept : buffer(buffer_) {} + public: Stream& buffer; - + public: template - [[nodiscard]] constexpr std::expected fast_read_integer(T& t) noexcept - { + [[nodiscard]] constexpr std::expected fast_read_integer(T& t) noexcept { bool sign = false; - if constexpr (std::is_signed_v) - { sign = SF_TRY(TestManip(buffer).is_equal_to_forward('-')); } + if constexpr (std::is_signed_v) { + sign = SF_TRY(TestManip(buffer).is_equal_to_forward('-')); + } + + if (!TestAccess(buffer).is_a_digit()) { + return std::unexpected(FMTResult::Parse_NonValidDigit); + } - if (!TestAccess(buffer).is_a_digit()) - { return std::unexpected(FMTResult::Parse_NonValidDigit); } - T value = static_cast(0); - while (TestAccess(buffer).is_a_digit()) - { + while (TestAccess(buffer).is_a_digit()) { char c = SF_TRY(Manip(buffer).get_and_forward()); - value = value * static_cast(10) + static_cast(c - static_cast('0')); + value = value * static_cast(10) + static_cast(c - static_cast('0')); } t = sign ? -value : value; @@ -37,31 +36,28 @@ namespace stream::fmt::buf public: template - [[nodiscard]] constexpr inline std::expected fast_read_float(T& t, std::int32_t float_precision = -1) noexcept - { + [[nodiscard]] constexpr inline std::expected fast_read_float(T& t, std::int32_t float_precision = -1) noexcept { T intpart = static_cast(0); TestAccess access(buffer); - TestManip manip(buffer); + TestManip manip(buffer); bool sign = SF_TRY(manip.is_equal_to_forward('-')); - if (access.is_a_digit()) - { SF_TRY(fast_read_integer(intpart)); } - else if (access.is_equal_to('.')) - { SF_TRY(buf::Manip(buffer).forward()); } - else - { return std::unexpected(FMTResult::Parse_NonValidDigit); } - - if (float_precision < 0) - { - while (access.is_a_digit() && Access(buffer).is_end_of_string() == false) - { Manip(buffer).forward_force(); } + if (access.is_a_digit()) { + SF_TRY(fast_read_integer(intpart)); + } else if (access.is_equal_to('.')) { + SF_TRY(buf::Manip(buffer).forward()); + } else { + return std::unexpected(FMTResult::Parse_NonValidDigit); } - else - { - while (access.is_a_digit() && float_precision > 0 && Access(buffer).is_end_of_string() == false) - { + + if (float_precision < 0) { + while (access.is_a_digit() && Access(buffer).is_end_of_string() == false) { + Manip(buffer).forward_force(); + } + } else { + while (access.is_a_digit() && float_precision > 0 && Access(buffer).is_end_of_string() == false) { Manip(buffer).forward_force(); float_precision--; } @@ -69,42 +65,40 @@ namespace stream::fmt::buf Manip(buffer).backward_force(); T dec = static_cast(0); - while (access.is_a_digit()) - { + while (access.is_a_digit()) { dec += static_cast(buffer.get() - '0'); Manip(buffer).backward_force(); dec /= 10; } - t = sign ? - intpart - dec : intpart + dec; + t = sign ? -intpart - dec : intpart + dec; return {}; } public: template - [[nodiscard]] std::expected FastReadCharPtr(const CharPtr* str, std::size_t sizeToCopy, bool isZeroEnded = true) - { - if (Access(buffer).can_move_forward(sizeToCopy) == false) - { + [[nodiscard]] std::expected FastReadCharPtr(const CharPtr* str, std::size_t sizeToCopy, bool isZeroEnded = true) { + if (Access(buffer).can_move_forward(sizeToCopy) == false) { return ReadManip(buffer).FastReadCharPtr(str, Access(buffer).get_buffer_remaining_size(), isZeroEnded); } // TODO : Opti with bigger types - while (sizeToCopy-- != 0) - { *str++ = SF_TRY(Manip(buffer).get_and_forward()); } - if (isZeroEnded) { *str = 0; } + while (sizeToCopy-- != 0) { + *str++ = SF_TRY(Manip(buffer).get_and_forward()); + } + if (isZeroEnded) { + *str = 0; + } return {}; } template - [[nodiscard]] inline std::expected FastReadCharArray(const CharStr (&str)[SIZE], bool isZeroEnded = true) - { + [[nodiscard]] inline std::expected FastReadCharArray(const CharStr (&str)[SIZE], bool isZeroEnded = true) { return FastReadCharPtr(str, SIZE); } template - [[nodiscard]] inline std::expected FastReadCharBound(const CharStr* begin, const CharStr* end, bool isZeroEnded = true) - { + [[nodiscard]] inline std::expected FastReadCharBound(const CharStr* begin, const CharStr* end, bool isZeroEnded = true) { return FastReadCharPtr(begin, end - begin - (isZeroEnded ? 1 : 0), isZeroEnded); } }; -} +} // namespace stream::fmt::buf diff --git a/src/stream/fmt/buf/stream.h b/src/stream/fmt/buf/stream.h index 842e2ca6..f6fa247c 100644 --- a/src/stream/fmt/buf/stream.h +++ b/src/stream/fmt/buf/stream.h @@ -2,11 +2,9 @@ #include "stream/fmt/detail/prelude.h" -namespace stream::fmt::buf -{ +namespace stream::fmt::buf { template - class Stream - { + class Stream { public: using TChar = CharType; @@ -16,28 +14,21 @@ namespace stream::fmt::buf TChar* buffer_end; // Not included public: - constexpr inline TChar get() const { return *current_pos; } + constexpr inline TChar get() const { + return *current_pos; + } public: - Stream() noexcept - : buffer(nullptr) - , current_pos(nullptr) - , buffer_end(nullptr) - {} - - Stream(TChar* const buffer_, const std::size_t size_) noexcept - : buffer(buffer_) - , current_pos(buffer_) - , buffer_end(buffer_ + size_) - {} + Stream() noexcept : buffer(nullptr), current_pos(nullptr), buffer_end(nullptr) {} + + Stream(TChar* const buffer_, const std::size_t size_) noexcept : buffer(buffer_), current_pos(buffer_), buffer_end(buffer_ + size_) {} }; template - class StreamView : public Stream - { + class StreamView : public Stream { public: using typename Stream::TChar; - + using Stream::buffer; using Stream::current_pos; using Stream::buffer_end; @@ -45,39 +36,27 @@ namespace stream::fmt::buf using Stream::get; public: - StreamView() noexcept - : Stream() - {} + StreamView() noexcept : Stream() {} template - StreamView(const CharType (&data)[SIZE]) noexcept - : Stream(data, SIZE) - { - while (buffer_end - 1 > buffer && *(buffer_end - 1) == 0) + StreamView(const CharType (&data)[SIZE]) noexcept : Stream(data, SIZE) { + while (buffer_end - 1 > buffer && *(buffer_end - 1) == 0) --buffer_end; } - StreamView(std::basic_string_view sv) noexcept - : Stream(sv.data(), sv.size()) - {} + StreamView(std::basic_string_view sv) noexcept : Stream(sv.data(), sv.size()) {} - StreamView(const CharType* const buffer, const std::size_t size) noexcept - : Stream(buffer, size) - {} + StreamView(const CharType* const buffer, const std::size_t size) noexcept : Stream(buffer, size) {} public: - operator Stream() const { return Stream {.buffer = buffer, .current_pos = current_pos, .buffer_end = buffer_end}; } + operator Stream() const { + return Stream{.buffer = buffer, .current_pos = current_pos, .buffer_end = buffer_end}; + } }; template - concept convertible_to_buffer_info = requires(T&& t) - { - Stream(std::forward(t)); - }; + concept convertible_to_buffer_info = requires(T&& t) { Stream(std::forward(t)); }; template - concept convertible_to_buffer_info_view = requires(T&& t) - { - StreamView(std::forward(t)); - }; -} + concept convertible_to_buffer_info_view = requires(T&& t) { StreamView(std::forward(t)); }; +} // namespace stream::fmt::buf diff --git a/src/stream/fmt/buf/streamio.h b/src/stream/fmt/buf/streamio.h index fa1e8535..f9a5704c 100644 --- a/src/stream/fmt/buf/streamio.h +++ b/src/stream/fmt/buf/streamio.h @@ -5,11 +5,9 @@ #include "streamio_manager/basic_streamio_manager.h" -namespace stream::fmt::buf -{ +namespace stream::fmt::buf { template - class StreamIO : public Stream - { + class StreamIO : public Stream { public: using typename Stream::TChar; @@ -18,39 +16,33 @@ namespace stream::fmt::buf using Stream::buffer_end; using Stream::get; - + protected: - StreamIO(BasicStreamIOManager& ostream_manager) noexcept - : Stream() - , Manager(ostream_manager) - {} + StreamIO(BasicStreamIOManager& ostream_manager) noexcept : Stream(), Manager(ostream_manager) {} protected: - [[nodiscard]] static std::expected init(StreamIO& in) - { + [[nodiscard]] static std::expected init(StreamIO& in) { SF_TRY(in.Manager.BeginContext()); Manip(in).reload(in.Manager.get_buffer(), in.Manager.get_buffer_size()); return {}; } public: - [[nodiscard]] static std::expected, FMTResult> create(BasicStreamIOManager& ostream_manager) - { + [[nodiscard]] static std::expected, FMTResult> create(BasicStreamIOManager& ostream_manager) { StreamIO res(ostream_manager); SF_TRY(init(res)); return res; } - + public: - inline void set(const TChar c) noexcept { *current_pos = c; } + inline void set(const TChar c) noexcept { + *current_pos = c; + } public: BasicStreamIOManager& Manager; }; template - concept convertible_to_streamio_info = requires(T&& t) - { - StreamIO(std::forward(t)); - }; -} + concept convertible_to_streamio_info = requires(T&& t) { StreamIO(std::forward(t)); }; +} // namespace stream::fmt::buf diff --git a/src/stream/fmt/buf/streamio_manager/basic_streamio_manager.h b/src/stream/fmt/buf/streamio_manager/basic_streamio_manager.h index 9b13068e..b65d1e14 100644 --- a/src/stream/fmt/buf/streamio_manager/basic_streamio_manager.h +++ b/src/stream/fmt/buf/streamio_manager/basic_streamio_manager.h @@ -3,50 +3,63 @@ #include "stream/fmt/detail/prelude.h" #include "stream/fmt/buf/stream.h" -namespace stream::fmt::buf -{ +namespace stream::fmt::buf { template - class BasicStreamIOManager - { + class BasicStreamIOManager { public: - BasicStreamIOManager() = default; - virtual ~BasicStreamIOManager() = default; - BasicStreamIOManager(BasicStreamIOManager&) = delete; + BasicStreamIOManager() = default; + virtual ~BasicStreamIOManager() = default; + BasicStreamIOManager(BasicStreamIOManager&) = delete; BasicStreamIOManager& operator=(BasicStreamIOManager&) = delete; protected: - [[nodiscard]] virtual std::expected begin_context_impl() { return {}; } + [[nodiscard]] virtual std::expected begin_context_impl() { + return {}; + } virtual void compute_generated_size_impl(const std::size_t /* totalGeneratedLength */) {} public: - [[nodiscard]] std::expected BeginContext() { return begin_context_impl(); } - void compute_generated_size(std::size_t totalGeneratedLength) - { + [[nodiscard]] std::expected BeginContext() { + return begin_context_impl(); + } + void compute_generated_size(std::size_t totalGeneratedLength) { compute_generated_size_impl(totalGeneratedLength); set_last_generated_data_size(totalGeneratedLength); } public: - virtual CharType* get_buffer() = 0; - virtual const CharType* get_buffer() const = 0; + virtual CharType* get_buffer() = 0; + virtual const CharType* get_buffer() const = 0; virtual std::size_t get_buffer_size() const = 0; public: [[nodiscard]] virtual std::expected add_size(const std::size_t count) = 0; public: - StreamView get_last_generated_buffer_info_view() const { return StreamView(get_buffer(), m_LastGeneratedDataSize); } - operator StreamView() const { return get_last_generated_buffer_info_view(); } - std::basic_string_view get_last_generated_string_view() const { return std::basic_string_view(get_buffer(), m_LastGeneratedDataSize); } - operator std::basic_string_view() const { return get_last_generated_string_view(); } + StreamView get_last_generated_buffer_info_view() const { + return StreamView(get_buffer(), m_LastGeneratedDataSize); + } + operator StreamView() const { + return get_last_generated_buffer_info_view(); + } + std::basic_string_view get_last_generated_string_view() const { + return std::basic_string_view(get_buffer(), m_LastGeneratedDataSize); + } + operator std::basic_string_view() const { + return get_last_generated_string_view(); + } public: - std::size_t get_last_generated_data_size() const { return m_LastGeneratedDataSize; } + std::size_t get_last_generated_data_size() const { + return m_LastGeneratedDataSize; + } private: - void set_last_generated_data_size(const std::size_t size) { m_LastGeneratedDataSize = size; } + void set_last_generated_data_size(const std::size_t size) { + m_LastGeneratedDataSize = size; + } protected: std::size_t m_LastGeneratedDataSize{0}; }; -} +} // namespace stream::fmt::buf diff --git a/src/stream/fmt/buf/streamio_manager/dynamic_streamio_manager.h b/src/stream/fmt/buf/streamio_manager/dynamic_streamio_manager.h index c9d30df9..fbfdc552 100644 --- a/src/stream/fmt/buf/streamio_manager/dynamic_streamio_manager.h +++ b/src/stream/fmt/buf/streamio_manager/dynamic_streamio_manager.h @@ -6,59 +6,60 @@ #include #include -namespace stream::fmt::buf -{ +namespace stream::fmt::buf { template - class DynamicStreamIOManager : public BasicStreamIOManager - { + class DynamicStreamIOManager : public BasicStreamIOManager { public: - DynamicStreamIOManager(std::size_t beginSize = DEFAULT_BEGIN_SIZE) - : buffer_size_(beginSize) - {} + DynamicStreamIOManager(std::size_t beginSize = DEFAULT_BEGIN_SIZE) : buffer_size_(beginSize) {} - ~DynamicStreamIOManager() override = default; - DynamicStreamIOManager(DynamicStreamIOManager&) = delete; + ~DynamicStreamIOManager() override = default; + DynamicStreamIOManager(DynamicStreamIOManager&) = delete; DynamicStreamIOManager& operator=(DynamicStreamIOManager&) = delete; - + public: static constexpr std::size_t DEFAULT_BEGIN_SIZE = 128; static constexpr std::size_t GROW_UP_BUFFER_SIZE = 2; static constexpr bool DEBUG_RESIZE = false; public: - CharType* get_buffer() override { return buffer_.get(); } - const CharType* get_buffer() const override { return buffer_.get(); } - std::size_t get_buffer_size() const override { if (buffer_ == nullptr) return 0; return buffer_size_; } + CharType* get_buffer() override { + return buffer_.get(); + } + const CharType* get_buffer() const override { + return buffer_.get(); + } + std::size_t get_buffer_size() const override { + if (buffer_ == nullptr) return 0; + return buffer_size_; + } public: - [[nodiscard]] std::expected begin_context_impl() final - { - if (buffer_ != nullptr) - return {}; + [[nodiscard]] std::expected begin_context_impl() final { + if (buffer_ != nullptr) return {}; CharType* alloc = new CharType[buffer_size_]; - if (alloc == nullptr) - return std::unexpected(FMTResult::Manager_AllocationFailed); + if (alloc == nullptr) return std::unexpected(FMTResult::Manager_AllocationFailed); buffer_.reset(alloc); return {}; } - [[nodiscard]] std::expected add_size(const std::size_t count) override { return resize(count + buffer_size_); } + [[nodiscard]] std::expected add_size(const std::size_t count) override { + return resize(count + buffer_size_); + } [[nodiscard]] std::expected resize(const std::size_t target_buffer_size); protected: - std::unique_ptr buffer_ = nullptr; + std::unique_ptr buffer_ = nullptr; std::size_t buffer_size_ = 0; }; template - class ShrinkDynamicStreamIOManager : public DynamicStreamIOManager - { + class ShrinkDynamicStreamIOManager : public DynamicStreamIOManager { public: using Base = DynamicStreamIOManager; + using Base::DEBUG_RESIZE; using Base::DEFAULT_BEGIN_SIZE; using Base::GROW_UP_BUFFER_SIZE; - using Base::DEBUG_RESIZE; using Base::get_buffer; using Base::get_buffer_size; @@ -73,26 +74,20 @@ namespace stream::fmt::buf static constexpr float MEAN_CALCFACT_LAST = 1; public: - ShrinkDynamicStreamIOManager(std::size_t beginSize = DEFAULT_BEGIN_SIZE) - : Base(beginSize) - , m_MeanGeneratedSize(beginSize) - {} - ~ShrinkDynamicStreamIOManager() override = default; - ShrinkDynamicStreamIOManager(ShrinkDynamicStreamIOManager&) = delete; + ShrinkDynamicStreamIOManager(std::size_t beginSize = DEFAULT_BEGIN_SIZE) : Base(beginSize), m_MeanGeneratedSize(beginSize) {} + ~ShrinkDynamicStreamIOManager() override = default; + ShrinkDynamicStreamIOManager(ShrinkDynamicStreamIOManager&) = delete; ShrinkDynamicStreamIOManager& operator=(ShrinkDynamicStreamIOManager&) = delete; protected: - void compute_generated_size_impl(std::size_t totalGeneratedLength) override - { + void compute_generated_size_impl(std::size_t totalGeneratedLength) override { // WTF m_MeanGeneratedSize = (m_MeanGeneratedSize * MEAN_CALCFACT_OLD + totalGeneratedLength * MEAN_CALCFACT_LAST) / (MEAN_CALCFACT_OLD + MEAN_CALCFACT_LAST); } public: - [[nodiscard]] std::expected shrink_if_needed() - { - if (buffer_size_ > static_cast(m_MeanGeneratedSize * MEAN_SIZE_OVERFLOW)) - return resize(static_cast(m_MeanGeneratedSize * MEAN_SIZE_RESIZE)); + [[nodiscard]] std::expected shrink_if_needed() { + if (buffer_size_ > static_cast(m_MeanGeneratedSize * MEAN_SIZE_OVERFLOW)) return resize(static_cast(m_MeanGeneratedSize * MEAN_SIZE_RESIZE)); return {}; } @@ -101,20 +96,17 @@ namespace stream::fmt::buf }; template - [[nodiscard]] std::expected DynamicStreamIOManager::resize(const std::size_t target_buffer_size) - { + [[nodiscard]] std::expected DynamicStreamIOManager::resize(const std::size_t target_buffer_size) { std::size_t new_buffer_size = target_buffer_size; - if (buffer_size_ < target_buffer_size) - { + if (buffer_size_ < target_buffer_size) { new_buffer_size = buffer_size_; while (new_buffer_size < target_buffer_size) new_buffer_size *= GROW_UP_BUFFER_SIZE; } CharType* newBuffer = new CharType[new_buffer_size]; - if (newBuffer == nullptr) - return std::unexpected(FMTResult::Manager_AllocationFailed); + if (newBuffer == nullptr) return std::unexpected(FMTResult::Manager_AllocationFailed); std::memcpy(newBuffer, buffer_.get(), std::min(new_buffer_size, buffer_size_)); @@ -125,4 +117,4 @@ namespace stream::fmt::buf return {}; } -} +} // namespace stream::fmt::buf diff --git a/src/stream/fmt/buf/streamio_manager/given_streamio_manager.h b/src/stream/fmt/buf/streamio_manager/given_streamio_manager.h index 4387289b..12eb06e9 100644 --- a/src/stream/fmt/buf/streamio_manager/given_streamio_manager.h +++ b/src/stream/fmt/buf/streamio_manager/given_streamio_manager.h @@ -2,36 +2,33 @@ #include "basic_streamio_manager.h" -namespace stream::fmt::buf -{ +namespace stream::fmt::buf { template - class GivenStreamIOManager : public BasicStreamIOManager - { + class GivenStreamIOManager : public BasicStreamIOManager { public: template - GivenStreamIOManager(CharType (&buffer)[SIZE]) - : buffer_(buffer) - , buffer_size_(SIZE) - {} + GivenStreamIOManager(CharType (&buffer)[SIZE]) : buffer_(buffer), buffer_size_(SIZE) {} - GivenStreamIOManager(CharType* buffer, std::size_t buffer_size) - : buffer_(buffer) - , buffer_size_(buffer_size) - {} + GivenStreamIOManager(CharType* buffer, std::size_t buffer_size) : buffer_(buffer), buffer_size_(buffer_size) {} ~GivenStreamIOManager() override = default; - GivenStreamIOManager(GivenStreamIOManager&) = delete; + GivenStreamIOManager(GivenStreamIOManager&) = delete; GivenStreamIOManager& operator=(GivenStreamIOManager&) = delete; public: - CharType* get_buffer() override { return buffer_; } - const CharType* get_buffer() const override { return buffer_; } - std::size_t get_buffer_size() const override { return buffer_size_; } + CharType* get_buffer() override { + return buffer_; + } + const CharType* get_buffer() const override { + return buffer_; + } + std::size_t get_buffer_size() const override { + return buffer_size_; + } public: - [[nodiscard]] std::expected add_size(const std::size_t /* count */) override - { + [[nodiscard]] std::expected add_size(const std::size_t /* count */) override { return std::unexpected(FMTResult::Manager_StaticMemory); } @@ -39,4 +36,4 @@ namespace stream::fmt::buf CharType* buffer_; std::size_t buffer_size_; }; -} +} // namespace stream::fmt::buf diff --git a/src/stream/fmt/buf/streamio_manager/static_streamio_manager.h b/src/stream/fmt/buf/streamio_manager/static_streamio_manager.h index e97ead51..0b2cc15f 100644 --- a/src/stream/fmt/buf/streamio_manager/static_streamio_manager.h +++ b/src/stream/fmt/buf/streamio_manager/static_streamio_manager.h @@ -2,28 +2,31 @@ #include "basic_streamio_manager.h" -namespace stream::fmt::buf -{ +namespace stream::fmt::buf { template - class StaticStreamIOManager : public BasicStreamIOManager - { + class StaticStreamIOManager : public BasicStreamIOManager { public: - ~StaticStreamIOManager() override = default; - StaticStreamIOManager(StaticStreamIOManager&) = delete; + ~StaticStreamIOManager() override = default; + StaticStreamIOManager(StaticStreamIOManager&) = delete; StaticStreamIOManager& operator=(StaticStreamIOManager&) = delete; public: - CharType* get_buffer() override { return buffer_; } - const CharType* get_buffer() const override { return buffer_; } - std::size_t get_buffer_size() const override { return Count; } + CharType* get_buffer() override { + return buffer_; + } + const CharType* get_buffer() const override { + return buffer_; + } + std::size_t get_buffer_size() const override { + return Count; + } public: - [[nodiscard]] std::expected add_size(const std::size_t) override - { + [[nodiscard]] std::expected add_size(const std::size_t) override { return std::unexpected(FMTResult::Manager_StaticMemory); } private: CharType buffer_[Count]; }; -} +} // namespace stream::fmt::buf diff --git a/src/stream/fmt/buf/test_manip.h b/src/stream/fmt/buf/test_manip.h index 95df97a6..dd561a58 100644 --- a/src/stream/fmt/buf/test_manip.h +++ b/src/stream/fmt/buf/test_manip.h @@ -3,89 +3,93 @@ #include "stream/fmt/buf/stream.h" #include "stream/fmt/buf/manip.h" -namespace stream::fmt::buf -{ +namespace stream::fmt::buf { template - class TestAccess - { + class TestAccess { public: constexpr inline TestAccess(const Stream& buffer) noexcept : buffer(buffer) {} + public: const Stream& buffer; - + public: - constexpr inline bool is_equal_to(const TChar c) const noexcept { return buffer.get() == c; } - constexpr inline bool is_not_equal_to(const TChar c) const noexcept { return buffer.get() != c; } + constexpr inline bool is_equal_to(const TChar c) const noexcept { + return buffer.get() == c; + } + constexpr inline bool is_not_equal_to(const TChar c) const noexcept { + return buffer.get() != c; + } template - constexpr inline bool is_equal_to(const TChar c, const CharToTest... ele) const noexcept - { + constexpr inline bool is_equal_to(const TChar c, const CharToTest... ele) const noexcept { return is_equal_to(c) || is_equal_to(ele...); } template - constexpr inline bool is_not_equal_to(const TChar c, const CharToTest... ele) const noexcept - { + constexpr inline bool is_not_equal_to(const TChar c, const CharToTest... ele) const noexcept { return is_not_equal_to(c) && is_not_equal_to(ele...); } public: - constexpr inline bool IsLowerCase() const noexcept { return buffer.get() >= 'a' && buffer.get() <= 'z'; } - constexpr inline bool IsUpperCase() const noexcept { return buffer.get() >= 'A' && buffer.get() <= 'Z'; } - constexpr inline bool is_a_digit() const noexcept { return buffer.get() >= '0' && buffer.get() <= '9'; } + constexpr inline bool IsLowerCase() const noexcept { + return buffer.get() >= 'a' && buffer.get() <= 'z'; + } + constexpr inline bool IsUpperCase() const noexcept { + return buffer.get() >= 'A' && buffer.get() <= 'Z'; + } + constexpr inline bool is_a_digit() const noexcept { + return buffer.get() >= '0' && buffer.get() <= '9'; + } public: template - constexpr bool is_same(const CharToTest* str, std::size_t size) const noexcept - { - if (size > Access(buffer).get_buffer_remaining_size()) - { return false; } + constexpr bool is_same(const CharToTest* str, std::size_t size) const noexcept { + if (size > Access(buffer).get_buffer_remaining_size()) { + return false; + } const TChar* bufferStr = buffer.current_pos; - bool is_same = true; - while (is_same && size != 0 && *str != 0) - { + bool is_same = true; + while (is_same && size != 0 && *str != 0) { is_same = *bufferStr++ == *str++; --size; } - if (size != 0) - { return false; } + if (size != 0) { + return false; + } return is_same; } template - constexpr inline bool is_same(std::basic_string_view sv) const noexcept - { + constexpr inline bool is_same(std::basic_string_view sv) const noexcept { return is_same(sv.data(), sv.size()); } }; template - class TestManip - { + class TestManip { public: constexpr inline TestManip(Stream& buffer) noexcept : buffer(buffer) {} + public: Stream& buffer; using TConstChar = std::remove_const_t; public: - TestAccess access() const noexcept { return TestAccess(buffer); } + TestAccess access() const noexcept { + return TestAccess(buffer); + } public: template - [[nodiscard]] constexpr inline std::expected is_equal_to_forward(const CharToTest... ele) noexcept - { - if (access().is_equal_to(ele...)) - { + [[nodiscard]] constexpr inline std::expected is_equal_to_forward(const CharToTest... ele) noexcept { + if (access().is_equal_to(ele...)) { SF_TRY(Manip(buffer).forward()); return true; } return false; } template - [[nodiscard]] constexpr inline std::expected is_not_equal_forward(const CharToTest... ele) noexcept - { - if (access().is_not_equal_to(ele...)) - { + [[nodiscard]] constexpr inline std::expected is_not_equal_forward(const CharToTest... ele) noexcept { + if (access().is_not_equal_to(ele...)) { SF_TRY(Manip(buffer).forward()); return true; } @@ -94,20 +98,16 @@ namespace stream::fmt::buf public: template - [[nodiscard]] constexpr std::expected is_same_forward(const CharToTest* str, std::size_t size) noexcept - { - if (access().is_same(str, size)) - { + [[nodiscard]] constexpr std::expected is_same_forward(const CharToTest* str, std::size_t size) noexcept { + if (access().is_same(str, size)) { SF_TRY(Manip(buffer).forward(size)); return true; } return false; } template - [[nodiscard]] constexpr inline std::expected is_same_forward(std::basic_string_view sv) noexcept - { - if (access().is_same(sv)) - { + [[nodiscard]] constexpr inline std::expected is_same_forward(std::basic_string_view sv) noexcept { + if (access().is_same(sv)) { SF_TRY(Manip(buffer).forward(sv.size())); return true; } @@ -116,10 +116,8 @@ namespace stream::fmt::buf public: template - [[nodiscard]] inline std::expected skip_one_of(const CharToTest... ele) noexcept - { - if (access().is_equal_to(ele...)) - { + [[nodiscard]] inline std::expected skip_one_of(const CharToTest... ele) noexcept { + if (access().is_equal_to(ele...)) { SF_TRY(Manip(buffer).forward()); return {}; } @@ -127,44 +125,49 @@ namespace stream::fmt::buf } template - inline void ignore_one_of(const CharToTest... ele) noexcept - { - if (access().is_equal_to(ele...) && Access(buffer).can_move_forward()) - { Manip(buffer).forward_force(); } + inline void ignore_one_of(const CharToTest... ele) noexcept { + if (access().is_equal_to(ele...) && Access(buffer).can_move_forward()) { + Manip(buffer).forward_force(); + } } template - inline void ignore_every(const CharToTest... ele) noexcept - { - while (access().is_equal_to(ele...) && Access(buffer).can_move_forward()) - { Manip(buffer).forward_force(); } + inline void ignore_every(const CharToTest... ele) noexcept { + while (access().is_equal_to(ele...) && Access(buffer).can_move_forward()) { + Manip(buffer).forward_force(); + } } - + public: - [[nodiscard]] inline void IgnoreOneSpace() noexcept { return ignore_one_of(' ', '\t'); } - [[nodiscard]] inline void IgnoreOneBlank() noexcept { return ignore_one_of(' ', '\t', '\n', '\r', '\v'); } + [[nodiscard]] inline void IgnoreOneSpace() noexcept { + return ignore_one_of(' ', '\t'); + } + [[nodiscard]] inline void IgnoreOneBlank() noexcept { + return ignore_one_of(' ', '\t', '\n', '\r', '\v'); + } - inline void ignore_every_spaces() noexcept { ignore_every(' ', '\t'); } - inline void IgnoreEveryBlanks() noexcept { ignore_every(' ', '\t', '\n', '\r', '\v'); } + inline void ignore_every_spaces() noexcept { + ignore_every(' ', '\t'); + } + inline void IgnoreEveryBlanks() noexcept { + ignore_every(' ', '\t', '\n', '\r', '\v'); + } public: template - inline void GoTo(const CharToTest... ele) noexcept - { + inline void GoTo(const CharToTest... ele) noexcept { while (access().is_not_equal_to(ele...) && Access(buffer).can_move_forward()) Manip(buffer).forward_force(); } template - [[nodiscard]] inline std::expected go_to_forward(const CharToTest... ele) noexcept - { + [[nodiscard]] inline std::expected go_to_forward(const CharToTest... ele) noexcept { GoTo(ele...); return Manip(buffer).forward(); } public: template - [[nodiscard]] std::expected, FMTResult> ViewExec(Func&& func) - { + [[nodiscard]] std::expected, FMTResult> ViewExec(Func&& func) { TChar* begin = buffer.current_pos; SF_TRY(func()); TChar* end = buffer.current_pos; @@ -172,9 +175,11 @@ namespace stream::fmt::buf } template - [[nodiscard]] inline std::expected, FMTResult> view_until(CharToTest&&... c) - { - return ViewExec([&] -> std::expected { TestManip(buffer).GoTo(std::forward(c)...); return {}; }); + [[nodiscard]] inline std::expected, FMTResult> view_until(CharToTest&&... c) { + return ViewExec([&] -> std::expected { + TestManip(buffer).GoTo(std::forward(c)...); + return {}; + }); } }; -} +} // namespace stream::fmt::buf diff --git a/src/stream/fmt/buf/utils/buffer_globber_manip.h b/src/stream/fmt/buf/utils/buffer_globber_manip.h index 906c761e..cd1f2704 100644 --- a/src/stream/fmt/buf/utils/buffer_globber_manip.h +++ b/src/stream/fmt/buf/utils/buffer_globber_manip.h @@ -3,45 +3,39 @@ #include "stream/fmt/buf/stream.h" #include "stream/fmt/buf/manip.h" -namespace stream::fmt::buf -{ +namespace stream::fmt::buf { template - class Globber - { + class Globber { public: - enum class PatternMatchType - { + enum class PatternMatchType { MatchBiggest, MatchSmallest }; private: - [[nodiscard]] static std::expected buffer_exec_glob_(Stream& istream, Stream& glob) - { - if (Access(glob).is_end_of_string()) { return istream.current_pos; } + [[nodiscard]] static std::expected buffer_exec_glob_(Stream& istream, Stream& glob) { + if (Access(glob).is_end_of_string()) { + return istream.current_pos; + } - if (Access(istream).is_end_of_string()) { return nullptr; } + if (Access(istream).is_end_of_string()) { + return nullptr; + } - if (TestAccess(glob).is_equal_to('?')) - { + if (TestAccess(glob).is_equal_to('?')) { SF_TRY(Manip(glob).forward()); SF_TRY(Manip(istream).forward()); return buffer_exec_glob_(istream, glob); - } - else if (TestAccess(glob).is_equal_to('*')) - { + } else if (TestAccess(glob).is_equal_to('*')) { SF_TRY(Manip(glob).forward()); const TChar* further = SF_TRY(buffer_exec_glob_(istream, glob)); - while (Access(istream).can_move_forward()) - { + while (Access(istream).can_move_forward()) { SF_TRY(Manip(istream).forward()); const TChar* last = SF_TRY(buffer_exec_glob_(istream, glob)); if (last > further || further == nullptr) further = last; } return further; - } - else if (TestAccess(glob).is_equal_to('[')) - { + } else if (TestAccess(glob).is_equal_to('[')) { SF_TRY(Manip(istream).forward()); const TChar* begin = glob.current_pos; SF_TRY(TestManip(glob).go_to_forward(']')); @@ -49,24 +43,20 @@ namespace stream::fmt::buf StreamView charSet(begin, end - begin); - bool is_inverted = SF_TRY(TestManip(glob).is_equal_to_forward('!')); - TChar toMatch = SF_TRY(Manip(istream).get_and_forward()); - bool found = false; + bool is_inverted = SF_TRY(TestManip(glob).is_equal_to_forward('!')); + TChar toMatch = SF_TRY(Manip(istream).get_and_forward()); + bool found = false; - while (found == false && Access(charSet).can_move_forward()) - { - if (TestAccess(charSet).is_equal_to(toMatch)) - { + while (found == false && Access(charSet).can_move_forward()) { + if (TestAccess(charSet).is_equal_to(toMatch)) { found = true; break; } - if (TestAccess(charSet).is_equal_to('-')) - { + if (TestAccess(charSet).is_equal_to('-')) { TChar beginSubSet = Access(charSet).get_prev_force(); - TChar endSubSet = Access(charSet).get_next_force(); - if (toMatch >= beginSubSet && toMatch <= endSubSet) - { + TChar endSubSet = Access(charSet).get_next_force(); + if (toMatch >= beginSubSet && toMatch <= endSubSet) { found = true; break; } @@ -82,8 +72,7 @@ namespace stream::fmt::buf return nullptr; } - if (istream.get() == glob.get()) - { + if (istream.get() == glob.get()) { SF_TRY(Manip(glob).forward()); SF_TRY(Manip(istream).forward()); return buffer_exec_glob_(istream, glob); @@ -92,28 +81,26 @@ namespace stream::fmt::buf } public: - [[nodiscard]] static std::expected buffer_exec_glob(Stream& istream, Stream& glob, [[maybe_unused]] PatternMatchType patternMatchtype = PatternMatchType::MatchBiggest) - { + [[nodiscard]] static std::expected buffer_exec_glob(Stream& istream, Stream& glob, + [[maybe_unused]] PatternMatchType patternMatchtype = PatternMatchType::MatchBiggest) { const TChar* furtherPointMatched = SF_TRY(buffer_exec_glob_(istream, glob)); - if (furtherPointMatched != nullptr) - istream.current_pos = furtherPointMatched; + if (furtherPointMatched != nullptr) istream.current_pos = furtherPointMatched; return {}; } }; template - class BufferGlobberManip - { + class BufferGlobberManip { public: constexpr inline BufferGlobberManip(Stream& buffer) noexcept : buffer(buffer) {} + public: Stream& buffer; - + public: - [[nodiscard]] std::expected FastReadCharPtrGlobber(std::basic_string_view globPattern, TChar* str, std::size_t sizeToCopy) - { + [[nodiscard]] std::expected FastReadCharPtrGlobber(std::basic_string_view globPattern, TChar* str, std::size_t sizeToCopy) { Stream globber(globPattern); - const TChar* begin = buffer.current_pos; + const TChar* begin = buffer.current_pos; Globber::buffer_exec_glob(*this, globber); const TChar* end = buffer.current_pos; @@ -121,9 +108,8 @@ namespace stream::fmt::buf return ReadManip(subContext).FastReadCharPtr(str, sizeToCopy); } - [[nodiscard]] std::expected FastReadCharPtrRegex(std::basic_string_view regexPattern, TChar* str, std::size_t sizeToCopy) - { + [[nodiscard]] std::expected FastReadCharPtrRegex(std::basic_string_view regexPattern, TChar* str, std::size_t sizeToCopy) { return std::unexpected(FMTResult::FunctionNotImpl); } }; -} +} // namespace stream::fmt::buf diff --git a/src/stream/fmt/buf/utils/buffer_shift_manip.h b/src/stream/fmt/buf/utils/buffer_shift_manip.h index 64e9c3b0..4db0830b 100644 --- a/src/stream/fmt/buf/utils/buffer_shift_manip.h +++ b/src/stream/fmt/buf/utils/buffer_shift_manip.h @@ -3,21 +3,18 @@ #include "stream/fmt/buf/stream.h" #include "stream/fmt/buf/manip_io.h" -namespace stream::fmt::buf -{ +namespace stream::fmt::buf { template - class ShiftWriteManip - { + class ShiftWriteManip { public: ShiftWriteManip(StreamIO& buffer) : buffer(buffer) {} + public: StreamIO& buffer; public: - [[nodiscard]] inline std::expected WriteShiftCenterBegin(detail::ShiftInfo& shift) - { - if (shift.type == detail::ShiftInfo::ShiftType::CenterRight || shift.type == detail::ShiftInfo::ShiftType::CenterLeft) - { + [[nodiscard]] inline std::expected WriteShiftCenterBegin(detail::ShiftInfo& shift) { + if (shift.type == detail::ShiftInfo::ShiftType::CenterRight || shift.type == detail::ShiftInfo::ShiftType::CenterLeft) { std::int32_t shift_ = shift.size / 2; if (shift.type == detail::ShiftInfo::ShiftType::CenterLeft) shift_ = (shift.size + 1) / 2; SF_TRY(ManipIO(buffer).pushback(shift.print.before, shift.size - shift_)); @@ -27,58 +24,47 @@ namespace stream::fmt::buf return {}; } - [[nodiscard]] inline std::expected WriteShiftCenterEnd(detail::ShiftInfo& shift) - { + [[nodiscard]] inline std::expected WriteShiftCenterEnd(detail::ShiftInfo& shift) { if (shift.type == detail::ShiftInfo::ShiftType::CenterRight || shift.type == detail::ShiftInfo::ShiftType::CenterLeft) return ManipIO(buffer).pushback(shift.print.after, shift.size); return {}; } - [[nodiscard]] inline std::expected write_shift_right_all(detail::ShiftInfo& shift) - { - if (shift.type == detail::ShiftInfo::ShiftType::Right) - return ManipIO(buffer).pushback(shift.print.before, shift.size); + [[nodiscard]] inline std::expected write_shift_right_all(detail::ShiftInfo& shift) { + if (shift.type == detail::ShiftInfo::ShiftType::Right) return ManipIO(buffer).pushback(shift.print.before, shift.size); return {}; } - [[nodiscard]] inline std::expected WriteShiftLeftAll(detail::ShiftInfo& shift) - { - if (shift.type == detail::ShiftInfo::ShiftType::Left) - return ManipIO(buffer).pushback(shift.print.after, shift.size); + [[nodiscard]] inline std::expected WriteShiftLeftAll(detail::ShiftInfo& shift) { + if (shift.type == detail::ShiftInfo::ShiftType::Left) return ManipIO(buffer).pushback(shift.print.after, shift.size); return {}; } - [[nodiscard]] inline std::expected write_shift_begin(detail::ShiftInfo& shift) - { + [[nodiscard]] inline std::expected write_shift_begin(detail::ShiftInfo& shift) { SF_TRY(WriteShiftCenterBegin(shift)); return write_shift_right_all(shift); } - [[nodiscard]] inline std::expected write_shift_end(detail::ShiftInfo& shift) - { + [[nodiscard]] inline std::expected write_shift_end(detail::ShiftInfo& shift) { SF_TRY(WriteShiftLeftAll(shift)); return WriteShiftCenterEnd(shift); } }; template - class ShiftReadManip - { + class ShiftReadManip { public: ShiftReadManip(Stream& buffer) : buffer(buffer) {} + public: Stream& buffer; public: - [[nodiscard]] std::expected ignore_shift_begin_space(detail::ShiftInfo& shift) - { - if (shift.print.before_is_a_digit() == false) - return {}; - if (shift.type == detail::ShiftInfo::ShiftType::Right || shift.type == detail::ShiftInfo::ShiftType::CenterLeft || shift.type == detail::ShiftInfo::ShiftType::CenterRight) - { - - while (buffer.get() == ' ') - { + [[nodiscard]] std::expected ignore_shift_begin_space(detail::ShiftInfo& shift) { + if (shift.print.before_is_a_digit() == false) return {}; + if (shift.type == detail::ShiftInfo::ShiftType::Right || shift.type == detail::ShiftInfo::ShiftType::CenterLeft || + shift.type == detail::ShiftInfo::ShiftType::CenterRight) { + while (buffer.get() == ' ') { SF_TRY(Manip(buffer).forward()); --shift.size; } @@ -86,12 +72,10 @@ namespace stream::fmt::buf return {}; } - [[nodiscard]] std::expected ignore_shift_end(detail::ShiftInfo& shift) - { - if (shift.type == detail::ShiftInfo::ShiftType::Left || shift.type == detail::ShiftInfo::ShiftType::CenterLeft || shift.type == detail::ShiftInfo::ShiftType::CenterRight) - { - while (buffer.get() == ' ' && shift.size > 0) - { + [[nodiscard]] std::expected ignore_shift_end(detail::ShiftInfo& shift) { + if (shift.type == detail::ShiftInfo::ShiftType::Left || shift.type == detail::ShiftInfo::ShiftType::CenterLeft || + shift.type == detail::ShiftInfo::ShiftType::CenterRight) { + while (buffer.get() == ' ' && shift.size > 0) { SF_TRY(Manip(buffer).forward()); --shift.size; } @@ -99,4 +83,4 @@ namespace stream::fmt::buf return {}; } }; -} +} // namespace stream::fmt::buf diff --git a/src/stream/fmt/buf/utils/buffer_utils.h b/src/stream/fmt/buf/utils/buffer_utils.h index 41856d32..5887ae79 100644 --- a/src/stream/fmt/buf/utils/buffer_utils.h +++ b/src/stream/fmt/buf/utils/buffer_utils.h @@ -10,24 +10,21 @@ #include "stream/fmt/buf/streamio_manager/given_streamio_manager.h" #include "stream/fmt/buf/streamio_manager/static_streamio_manager.h" -namespace stream::fmt::buf -{ +namespace stream::fmt::buf { template - class UtilsManip - { + class UtilsManip { public: constexpr inline UtilsManip(Stream& buffer_) noexcept : buffer(buffer_) {} + public: Stream& buffer; using TConstChar = std::remove_const_t; - + public: template - [[nodiscard]] std::expected get_word_from_list(const std::basic_string_view (&data)[SIZE]) - { - for (std::size_t idx = 0; idx < SIZE; ++idx) - { + [[nodiscard]] std::expected get_word_from_list(const std::basic_string_view (&data)[SIZE]) { + for (std::size_t idx = 0; idx < SIZE; ++idx) { bool found = SF_TRY(TestManip(buffer).is_same_forward(data[idx])); if (found) return idx; } @@ -37,37 +34,31 @@ namespace stream::fmt::buf // TODO: use static map ? template using DictPairs = std::pair, T>; - + template - [[nodiscard]] std::expected get_word_from_dict_pairs(const DictPairs (&data)[SIZE]) - { - for (std::size_t idx = 0; idx < SIZE; ++idx) - { + [[nodiscard]] std::expected get_word_from_dict_pairs(const DictPairs (&data)[SIZE]) { + for (std::size_t idx = 0; idx < SIZE; ++idx) { bool found = SF_TRY(TestManip(buffer).is_same_forward(data[idx].first)); - if (found) - return data[idx].second; + if (found) return data[idx].second; } return std::unexpected(FMTResult::Specifiers_Invalid); } }; - namespace utils - { + namespace utils { template - [[nodiscard]] static std::expected parse_escaped_quoted_string(buf::Stream& buffer, buf::StreamIO& stringOut) - { + [[nodiscard]] static std::expected parse_escaped_quoted_string(buf::Stream& buffer, buf::StreamIO& stringOut) { SF_TRY(buf::TestManip(buffer).skip_one_of('"')); - while (buf::Access(buffer).is_end_of_string() == false) - { + while (buf::Access(buffer).is_end_of_string() == false) { auto view = SF_TRY(buf::TestManip(buffer).view_until('"', '\\')); SF_TRY(buf::WriteManip(stringOut).fast_write_string(view)); - if (buf::TestAccess(buffer).is_equal_to('"')) - { break; } + if (buf::TestAccess(buffer).is_equal_to('"')) { + break; + } SF_TRY(buf::TestManip(buffer).skip_one_of('\\')); - switch (buffer.get()) - { + switch (buffer.get()) { // TODO : Do all others escape char case '"': SF_TRY(buf::ManipIO(stringOut).pushback('"')); @@ -91,11 +82,9 @@ namespace stream::fmt::buf } template - [[nodiscard]] static std::expected format_escaped_quoted_string(buf::StreamIO& buffer, buf::Stream& string_in) - { + [[nodiscard]] static std::expected format_escaped_quoted_string(buf::StreamIO& buffer, buf::Stream& string_in) { SF_TRY(buf::ManipIO(buffer).pushback('"')); - while (buf::Access(string_in).is_end_of_string() == false) - { + while (buf::Access(string_in).is_end_of_string() == false) { auto view = SF_TRY(buf::TestManip(string_in).view_until('\\')); SF_TRY(buf::WriteManip(buffer).fast_write_string(view)); @@ -103,8 +92,7 @@ namespace stream::fmt::buf // TODO SF_TRY(buf::TestManip(string_in).skip_one_of('\\')); - switch (string_in.get()) - { + switch (string_in.get()) { // TODO : Do all others escape char case '"': SF_TRY(buf::ManipIO(buffer).pushback('"')); @@ -126,5 +114,5 @@ namespace stream::fmt::buf return {}; } - }; -} + }; // namespace utils +} // namespace stream::fmt::buf diff --git a/src/stream/fmt/buf/write_manip.h b/src/stream/fmt/buf/write_manip.h index 4eb23a3f..b6723411 100644 --- a/src/stream/fmt/buf/write_manip.h +++ b/src/stream/fmt/buf/write_manip.h @@ -8,21 +8,16 @@ #include #include -namespace stream::fmt::buf -{ - class WriteUtils - { +namespace stream::fmt::buf { + class WriteUtils { public: template - static std::int32_t get_number_of_digit_dec(T value) - { - if constexpr (std::numeric_limits::is_signed) - { + static std::int32_t get_number_of_digit_dec(T value) { + if constexpr (std::numeric_limits::is_signed) { if (value < 0) value = -value; } std::int32_t nb = 0; - while (true) - { + while (true) { if (value < 10) return nb + 1; else if (value < 100) @@ -31,8 +26,7 @@ namespace stream::fmt::buf return nb + 3; else if (value < 10000) return nb + 4; - else - { + else { value /= static_cast(10000); nb += 4; } @@ -41,37 +35,40 @@ namespace stream::fmt::buf }; template - class WriteManip - { + class WriteManip { public: constexpr inline WriteManip(StreamIO& buffer) noexcept : buffer(buffer) {} + public: StreamIO& buffer; - + public: - static constexpr TChar BIN[2] = {'0', '1'}; - static constexpr TChar OCT[8] = {'0', '1', '2', '3', '4', '5', '6', '7'}; + static constexpr TChar BIN[2] = {'0', '1'}; + static constexpr TChar OCT[8] = {'0', '1', '2', '3', '4', '5', '6', '7'}; static constexpr TChar UPPER_HEX[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'b', 'C', 'D', 'E', 'F'}; static constexpr TChar LOWER_HEX[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; public: template - requires std::is_integral_v - [[nodiscard]] constexpr std::expected fast_write_integer(T i) - { + requires std::is_integral_v + [[nodiscard]] constexpr std::expected fast_write_integer(T i) { ManipIO manip(buffer); - if (i == 0) { SF_TRY(manip.pushback('0')); return {}; } + if (i == 0) { + SF_TRY(manip.pushback('0')); + return {}; + } - if constexpr (std::is_signed_v) - { - if (i < 0) { SF_TRY(manip.pushback('-')); i = -i; } + if constexpr (std::is_signed_v) { + if (i < 0) { + SF_TRY(manip.pushback('-')); + i = -i; + } } std::int32_t nb_digit = WriteUtils::get_number_of_digit_dec(i); SF_TRY(manip.forward(nb_digit)); - while (i > 0) - { + while (i > 0) { Manip(buffer).backward_force(); ManipIO(buffer).set(i % 10 + '0'); i /= 10; @@ -83,23 +80,25 @@ namespace stream::fmt::buf public: template - requires std::is_floating_point_v - [[nodiscard]] constexpr std::expected fast_write_float(T i, std::int32_t float_precision = 2) - { + requires std::is_floating_point_v + [[nodiscard]] constexpr std::expected fast_write_float(T i, std::int32_t float_precision = 2) { ManipIO manip(buffer); - if (i == 0) - { SF_TRY(manip.pushback('0')); return {}; } - if (i < 0) - { SF_TRY(manip.pushback('-')); i = -i; } + if (i == 0) { + SF_TRY(manip.pushback('0')); + return {}; + } + if (i < 0) { + SF_TRY(manip.pushback('-')); + i = -i; + } - T k = std::trunc(i); - i = i - k; + T k = std::trunc(i); + i = i - k; std::int32_t nb_digit = WriteUtils::get_number_of_digit_dec(k); SF_TRY(manip.forward(nb_digit)); std::int32_t nb_digit_ = nb_digit; - while (nb_digit_ > 0) - { + while (nb_digit_ > 0) { Manip(buffer).backward_force(); buffer.set(char(std::fmod(k, 10)) + '0'); k /= 10; @@ -108,8 +107,7 @@ namespace stream::fmt::buf SF_TRY(manip.forward(nb_digit)); SF_TRY(manip.pushback('.')); - while (float_precision-- >= 0) - { + while (float_precision-- >= 0) { TChar intPart = static_cast(std::trunc(i *= 10)); SF_TRY(manip.pushback(intPart + '0')); i -= intPart; @@ -120,14 +118,11 @@ namespace stream::fmt::buf public: template - [[nodiscard]] constexpr std::expected fast_write_char_array(const CharInput* str, std::size_t size) - { - if (size == 0) - return {}; + [[nodiscard]] constexpr std::expected fast_write_char_array(const CharInput* str, std::size_t size) { + if (size == 0) return {}; auto reserve = ManipIO(buffer).reserve(size); - if (reserve.has_value() == false) - return fast_write_char_array(str, Access(buffer).get_buffer_remaining_size()); + if (reserve.has_value() == false) return fast_write_char_array(str, Access(buffer).get_buffer_remaining_size()); std::copy_n(str, size, buffer.current_pos); buffer.current_pos += size; @@ -135,40 +130,46 @@ namespace stream::fmt::buf return {}; } template - [[nodiscard]] inline constexpr std::expected fast_write_string(std::basic_string_view sv) - { + [[nodiscard]] inline constexpr std::expected fast_write_string(std::basic_string_view sv) { return fast_write_char_array(sv.data(), sv.size()); } - [[nodiscard]] inline std::expected fast_write_string(std::basic_string_view sv) - { + [[nodiscard]] inline std::expected fast_write_string(std::basic_string_view sv) { return fast_write_char_array(sv.data(), sv.size()); } template - [[nodiscard]] inline std::expected fast_write_string_literal(CharInput (&str)[SIZE]) - { + [[nodiscard]] inline std::expected fast_write_string_literal(CharInput (&str)[SIZE]) { std::size_t size = SIZE; - while (str[size - 1] == 0) - { --size; } + while (str[size - 1] == 0) { + --size; + } return fast_write_char_array(str, size); } public: template - [[nodiscard]] inline std::expected basic_write_type(std::basic_string_view str) { return fast_write_string(str); } + [[nodiscard]] inline std::expected basic_write_type(std::basic_string_view str) { + return fast_write_string(str); + } template - [[nodiscard]] inline std::expected basic_write_type(CharInput (&str)[SIZE]) { return fast_write_string_literal(str); } - template requires std::is_integral_v - [[nodiscard]] inline std::expected basic_write_type(T t) { return fast_write_integer(t); } - template requires std::is_floating_point_v - [[nodiscard]] inline std::expected basic_write_type(T t) { return fast_write_float(t); } + [[nodiscard]] inline std::expected basic_write_type(CharInput (&str)[SIZE]) { + return fast_write_string_literal(str); + } + template + requires std::is_integral_v + [[nodiscard]] inline std::expected basic_write_type(T t) { + return fast_write_integer(t); + } + template + requires std::is_floating_point_v + [[nodiscard]] inline std::expected basic_write_type(T t) { + return fast_write_float(t); + } template - [[nodiscard]] inline std::expected basic_write_type(Type&& type, Rest&&... rest) - { + [[nodiscard]] inline std::expected basic_write_type(Type&& type, Rest&&... rest) { SF_TRY(basic_write_type(type)); - if constexpr (sizeof...(rest) > 0) - SF_TRY(basic_write_type(std::forward(rest)...)); + if constexpr (sizeof...(rest) > 0) SF_TRY(basic_write_type(std::forward(rest)...)); return {}; } }; -} +} // namespace stream::fmt::buf diff --git a/src/stream/fmt/context/basic_context/basic_args_interface.h b/src/stream/fmt/context/basic_context/basic_args_interface.h index fca22751..9f3aec56 100644 --- a/src/stream/fmt/context/basic_context/basic_args_interface.h +++ b/src/stream/fmt/context/basic_context/basic_args_interface.h @@ -8,26 +8,22 @@ #include #include -namespace stream::fmt::context -{ +namespace stream::fmt::context { template class BasicContext; template class context_executor; -} +} // namespace stream::fmt::context -namespace stream::fmt::detail -{ - struct PointerID - { +namespace stream::fmt::detail { + struct PointerID { const std::type_info& type_info; - void* ptr = nullptr; + void* ptr = nullptr; }; template - class BasicArgsInterface - { + class BasicArgsInterface { public: BasicArgsInterface() {} virtual ~BasicArgsInterface() = default; @@ -36,25 +32,24 @@ namespace stream::fmt::detail virtual size_t size() = 0; public: - [[nodiscard]] virtual std::expected get_pointerid_at(std::int32_t idx) = 0; - [[nodiscard]] virtual std::expected run_type_at(std::int32_t idx) = 0; - [[nodiscard]] virtual std::expected get_index_of_current_named_arg(buf::StreamView& format) = 0; - [[nodiscard]] virtual std::expected, FMTResult> get_string_at(std::int32_t idx) = 0; - [[nodiscard]] virtual std::expected get_int_at(std::int32_t idx) = 0; + [[nodiscard]] virtual std::expected get_pointerid_at(std::int32_t idx) = 0; + [[nodiscard]] virtual std::expected run_type_at(std::int32_t idx) = 0; + [[nodiscard]] virtual std::expected get_index_of_current_named_arg(buf::StreamView& format) = 0; + [[nodiscard]] virtual std::expected, FMTResult> get_string_at(std::int32_t idx) = 0; + [[nodiscard]] virtual std::expected get_int_at(std::int32_t idx) = 0; public: template - [[nodiscard]] std::expected get_type_at(std::int32_t idx) - { + [[nodiscard]] std::expected get_type_at(std::int32_t idx) { PointerID ptr = SF_TRY(get_pointerid_at(idx)); - if (ptr.type_info != typeid(T)) - { return std::unexpected(FMTResult::ArgsInterface_InvalidTypeID); } + if (ptr.type_info != typeid(T)) { + return std::unexpected(FMTResult::ArgsInterface_InvalidTypeID); + } return reinterpret_cast(ptr.ptr); } template - [[nodiscard]] std::expected run_func_from_type_at(std::int32_t idx, std::function(const T&)> func) - { + [[nodiscard]] std::expected run_func_from_type_at(std::int32_t idx, std::function(const T&)> func) { const T* value = SF_TRY(get_type_at(idx)); SF_TRY(func(*value)); return {}; @@ -62,20 +57,31 @@ namespace stream::fmt::detail }; template - class EmptyContextArgsTupleInterface : public BasicArgsInterface - { + class EmptyContextArgsTupleInterface : public BasicArgsInterface { public: EmptyContextArgsTupleInterface() {} ~EmptyContextArgsTupleInterface() override = default; public: - size_t size() override { return 0; } + size_t size() override { + return 0; + } public: - [[nodiscard]] std::expected get_pointerid_at(std::int32_t) override { return std::unexpected(FMTResult::ArgsInterface_Unavaible); } - [[nodiscard]] std::expected run_type_at(std::int32_t) override { return std::unexpected(FMTResult::ArgsInterface_Unavaible); } - [[nodiscard]] std::expected get_index_of_current_named_arg(buf::StreamView&) override { return std::unexpected(FMTResult::ArgsInterface_Unavaible); } - [[nodiscard]] std::expected, FMTResult> get_string_at(std::int32_t) override { return std::unexpected(FMTResult::ArgsInterface_Unavaible); } - [[nodiscard]] std::expected get_int_at(std::int32_t) override { return std::unexpected(FMTResult::ArgsInterface_Unavaible); } + [[nodiscard]] std::expected get_pointerid_at(std::int32_t) override { + return std::unexpected(FMTResult::ArgsInterface_Unavaible); + } + [[nodiscard]] std::expected run_type_at(std::int32_t) override { + return std::unexpected(FMTResult::ArgsInterface_Unavaible); + } + [[nodiscard]] std::expected get_index_of_current_named_arg(buf::StreamView&) override { + return std::unexpected(FMTResult::ArgsInterface_Unavaible); + } + [[nodiscard]] std::expected, FMTResult> get_string_at(std::int32_t) override { + return std::unexpected(FMTResult::ArgsInterface_Unavaible); + } + [[nodiscard]] std::expected get_int_at(std::int32_t) override { + return std::unexpected(FMTResult::ArgsInterface_Unavaible); + } }; -} +} // namespace stream::fmt::detail diff --git a/src/stream/fmt/context/basic_context/basic_context.h b/src/stream/fmt/context/basic_context/basic_context.h index 52e7d448..a140887b 100644 --- a/src/stream/fmt/context/basic_context/basic_context.h +++ b/src/stream/fmt/context/basic_context/basic_context.h @@ -14,50 +14,40 @@ #include "text_properties_executor.h" #include "text_properties_manager.h" -namespace stream::fmt::context -{ +namespace stream::fmt::context { template class BasicContext; template - class context_executor - { + class context_executor { public: - context_executor(detail::ITextPropertiesExecutor& text_properties_executor) - : data{} - , text_manager{text_properties_executor} - {} + context_executor(detail::ITextPropertiesExecutor& text_properties_executor) : data{}, text_manager{text_properties_executor} {} virtual ~context_executor() = default; - + public: - [[nodiscard]] virtual std::expected exec_settings() = 0; + [[nodiscard]] virtual std::expected exec_settings() = 0; [[nodiscard]] virtual std::expected exec_raw_string(std::basic_string_view) = 0; public: - detail::FormatData data; + detail::FormatData data; detail::TextPropertiesManager text_manager; }; template - class BasicContext - { + class BasicContext { public: using TChar = CharType; public: - BasicContext( - context_executor& executor, - buf::StreamView fmtstream, - detail::BasicArgsInterface& args_interface - ); + BasicContext(context_executor& executor, buf::StreamView fmtstream, detail::BasicArgsInterface& args_interface); virtual ~BasicContext() = default; - + public: context_executor& executor; - buf::StreamView fmtstream; + buf::StreamView fmtstream; detail::BasicArgsInterface& args_interface; - std::int32_t values_index; + std::int32_t values_index; public: [[nodiscard]] std::expected run(); @@ -89,48 +79,33 @@ namespace stream::fmt::context public: template - inline void ExecNextFormatData(Func&& func, Args&&... args) - { - if (executor.data.next_override.size() == 0) - return func(std::forward(args)...); + inline void ExecNextFormatData(Func&& func, Args&&... args) { + if (executor.data.next_override.size() == 0) return func(std::forward(args)...); detail::FormatData format_data_copy = executor.data; formatdata_apply_next_override(); func(std::forward(args)...); executor.data = format_data_copy; } }; -} +} // namespace stream::fmt::context -namespace stream::fmt::context -{ +namespace stream::fmt::context { template - BasicContext::BasicContext( - context_executor& executor, - buf::StreamView format, - detail::BasicArgsInterface& args_interface - ) - : executor(executor) - , fmtstream{format} - , args_interface{args_interface} - , values_index{0} - {} + BasicContext::BasicContext(context_executor& executor, buf::StreamView format, detail::BasicArgsInterface& args_interface) + : executor(executor), fmtstream{format}, args_interface{args_interface}, values_index{0} {} template - [[nodiscard]] std::expected BasicContext::run() - { - while (!buf::Access(fmtstream).is_end_of_string()) - { + [[nodiscard]] std::expected BasicContext::run() { + while (!buf::Access(fmtstream).is_end_of_string()) { const TChar* begin_continuous_string = fmtstream.current_pos; - std::size_t size_continuous_string = 0; - while (buf::Access(fmtstream).is_end_of_string() == false && buf::TestAccess(fmtstream).is_equal_to('{') == false) - { + std::size_t size_continuous_string = 0; + while (buf::Access(fmtstream).is_end_of_string() == false && buf::TestAccess(fmtstream).is_equal_to('{') == false) { ++size_continuous_string; SF_TRY(buf::Manip(fmtstream).forward()); } SF_TRY(executor.exec_raw_string(std::basic_string_view(begin_continuous_string, size_continuous_string))); - if (buf::Access(fmtstream).is_end_of_string() == false && buf::TestAccess(fmtstream).is_equal_to('{')) - { + if (buf::Access(fmtstream).is_end_of_string() == false && buf::TestAccess(fmtstream).is_equal_to('{')) { SF_TRY(parse()); } } @@ -139,24 +114,22 @@ namespace stream::fmt::context } template - void BasicContext::formatdata_apply_next_override() - { - if (executor.data.next_override.size() == 0) - { return; } + void BasicContext::formatdata_apply_next_override() { + if (executor.data.next_override.size() == 0) { + return; + } buf::StreamView overridePos(executor.data.next_override); buf::StreamView format_pos = fmtstream; - fmtstream = overridePos; + fmtstream = overridePos; parse_format_data(); fmtstream = format_pos; } template template - [[nodiscard]] std::expected BasicContext::format_read_parameter(const T& default_value) - { - if (!buf::TestAccess(fmtstream).is_equal_to('{')) - { + [[nodiscard]] std::expected BasicContext::format_read_parameter(const T& default_value) { + if (!buf::TestAccess(fmtstream).is_equal_to('{')) { T t; SF_TRY(buf::ReadManip(fmtstream).fast_read_integer(t)); return t; @@ -172,6 +145,6 @@ namespace stream::fmt::context return std::unexpected(FMTResult::Context_ArgumentIndexExpected); } -} +} // namespace stream::fmt::context #include "basic_context_parse_impl.h" diff --git a/src/stream/fmt/context/basic_context/basic_context_parse_impl.h b/src/stream/fmt/context/basic_context/basic_context_parse_impl.h index f7e14cae..9b7fca25 100644 --- a/src/stream/fmt/context/basic_context/basic_context_parse_impl.h +++ b/src/stream/fmt/context/basic_context/basic_context_parse_impl.h @@ -9,14 +9,12 @@ #include "stream/fmt/buf/fmt_manip_io.h" #include "stream/fmt/buf/fmt_read_manip.h" -namespace stream::fmt::context -{ +namespace stream::fmt::context { template - [[nodiscard]] std::expected, FMTResult> BasicContext::parse_next_override_format_data() - { + [[nodiscard]] std::expected, FMTResult> BasicContext::parse_next_override_format_data() { // TODO: check that function buf::TestAccess access(fmtstream); - buf::TestManip manip(fmtstream); + buf::TestManip manip(fmtstream); manip.ignore_every_spaces(); buf::FMTParamsManip(fmtstream).param_go_to('{', '=', ':'); @@ -28,21 +26,15 @@ namespace stream::fmt::context const TChar* begin = fmtstream.current_pos; SF_TRY(manip.skip_one_of('{')); int scopes = 0; - while (buf::FMTParamsManip(fmtstream).is_end_of_parameter() == false || scopes > 0) - { + while (buf::FMTParamsManip(fmtstream).is_end_of_parameter() == false || scopes > 0) { manip.GoTo('\'', '}', '{'); - if (access.is_equal_to('\'')) - { + if (access.is_equal_to('\'')) { SF_TRY(buf::Manip(fmtstream).forward()); manip.go_to_forward('\''); - } - else if (access.is_equal_to('{')) - { + } else if (access.is_equal_to('{')) { SF_TRY(buf::Manip(fmtstream).forward()); scopes++; - } - else if (scopes > 0 && access.is_equal_to('}')) - { + } else if (scopes > 0 && access.is_equal_to('}')) { SF_TRY(buf::Manip(fmtstream).forward()); scopes--; } @@ -53,53 +45,42 @@ namespace stream::fmt::context } template - [[nodiscard]] std::expected BasicContext::parse_format_data_base() - { + [[nodiscard]] std::expected BasicContext::parse_format_data_base() { buf::TestAccess access(fmtstream); - if (access.is_equal_to('C')) - { + if (access.is_equal_to('C')) { SF_TRY(buf::Manip(fmtstream).forward()); SF_TRY(executor.text_manager.parse_color(*this)); - } - else if (access.is_equal_to('S')) - { + } else if (access.is_equal_to('S')) { SF_TRY(buf::Manip(fmtstream).forward()); SF_TRY(executor.text_manager.parse_style(*this)); - } - else if (access.is_equal_to('F')) - { + } else if (access.is_equal_to('F')) { SF_TRY(buf::Manip(fmtstream).forward()); SF_TRY(executor.text_manager.parse_front(*this)); } - else if (access.is_equal_to('K')) - { + else if (access.is_equal_to('K')) { SF_TRY(buf::Manip(fmtstream).forward()); executor.data.keep_new_style = true; } - else if (access.is_equal_to('N')) - { + else if (access.is_equal_to('N')) { SF_TRY(buf::Manip(fmtstream).forward()); executor.data.next_override = SF_TRY(parse_next_override_format_data()); } - + return {}; } template - [[nodiscard]] std::expected BasicContext::parse_format_dataSpecial_ShiftType(const detail::ShiftInfo::ShiftType type) - { + [[nodiscard]] std::expected BasicContext::parse_format_dataSpecial_ShiftType(const detail::ShiftInfo::ShiftType type) { executor.data.shift.type = type; executor.data.shift.size = SF_TRY(format_read_parameter(-1)); - if (buf::TestAccess(fmtstream).is_equal_to(':')) - { + if (buf::TestAccess(fmtstream).is_equal_to(':')) { SF_TRY(buf::Manip(fmtstream).forward()); executor.data.shift.print.before = SF_TRY(buf::Manip(fmtstream).get_and_forward()); executor.data.shift.print.after = executor.data.shift.print.before; - if (buf::TestAccess(fmtstream).is_equal_to('|')) - { + if (buf::TestAccess(fmtstream).is_equal_to('|')) { SF_TRY(buf::Manip(fmtstream).forward()); executor.data.shift.print.after = SF_TRY(buf::Manip(fmtstream).get_and_forward()); } @@ -108,17 +89,15 @@ namespace stream::fmt::context } template - [[nodiscard]] std::expected BasicContext::parse_format_dataSpecial() - { + [[nodiscard]] std::expected BasicContext::parse_format_dataSpecial() { buf::TestAccess access(fmtstream); - buf::TestManip manip(fmtstream); + buf::TestManip manip(fmtstream); - if (access.is_equal_to('{')) - { + if (access.is_equal_to('{')) { SF_TRY(buf::Manip(fmtstream).forward()); std::int32_t formatIndex = SF_TRY(GetFormatIndex()); - bool ableToapply = false; - + bool ableToapply = false; + auto applyFormatData = SF_TRY(args_interface.template get_type_at>(formatIndex)); ableToapply |= executor.data.testapply(applyFormatData); auto applyFormatSpecifier = SF_TRY(args_interface.template get_type_at>(formatIndex)); @@ -128,49 +107,39 @@ namespace stream::fmt::context auto applyShiftInfo = SF_TRY(args_interface.template get_type_at(formatIndex)); ableToapply |= executor.data.testapply(applyShiftInfo); - if (not ableToapply) - { return std::unexpected(FMTResult::Context_CannotapplyType); } + if (not ableToapply) { + return std::unexpected(FMTResult::Context_CannotapplyType); + } SF_TRY(manip.skip_one_of('}')); } - else if (access.is_equal_to('.')) - { + else if (access.is_equal_to('.')) { SF_TRY(buf::Manip(fmtstream).forward()); executor.data.float_precision = SF_TRY(format_read_parameter(-1)); } - else if (access.is_equal_to('d', 'b', 'b', 'o', 'O', 'x', 'X')) - { - auto get = SF_TRY(buf::Manip(fmtstream).get_and_forward()); + else if (access.is_equal_to('d', 'b', 'b', 'o', 'O', 'x', 'X')) { + auto get = SF_TRY(buf::Manip(fmtstream).get_and_forward()); executor.data.integer_print = static_cast(get); } - else if (access.is_equal_to('#')) - { + else if (access.is_equal_to('#')) { SF_TRY(buf::Manip(fmtstream).forward()); executor.data.prefix_suffix = true; } - else if (access.is_equal_to('>')) - { + else if (access.is_equal_to('>')) { SF_TRY(buf::Manip(fmtstream).forward()); SF_TRY(parse_format_dataSpecial_ShiftType(detail::ShiftInfo::ShiftType::Right)); - } - else if (access.is_equal_to('<')) - { + } else if (access.is_equal_to('<')) { SF_TRY(buf::Manip(fmtstream).forward()); SF_TRY(parse_format_dataSpecial_ShiftType(detail::ShiftInfo::ShiftType::Left)); - } - else if (access.is_equal_to('^')) - { + } else if (access.is_equal_to('^')) { SF_TRY(buf::Manip(fmtstream).forward()); - if (access.is_equal_to('<')) - { + if (access.is_equal_to('<')) { SF_TRY(buf::Manip(fmtstream).forward()); SF_TRY(parse_format_dataSpecial_ShiftType(detail::ShiftInfo::ShiftType::CenterLeft)); - } - else - { + } else { manip.ignore_one_of('>'); SF_TRY(parse_format_dataSpecial_ShiftType(detail::ShiftInfo::ShiftType::CenterRight)); } @@ -180,40 +149,33 @@ namespace stream::fmt::context } template - [[nodiscard]] std::expected BasicContext::parse_format_dataCustom() - { + [[nodiscard]] std::expected BasicContext::parse_format_dataCustom() { buf::TestAccess access(fmtstream); - buf::TestManip manip(fmtstream); + buf::TestManip manip(fmtstream); - std::basic_string_view name = SF_TRY(manip.ViewExec( - [&] -> std::expected { buf::FMTParamsManip(fmtstream).param_go_to(' ', '=', '\'', '{', ','); return {}; } - )); + std::basic_string_view name = SF_TRY(manip.ViewExec([&] -> std::expected { + buf::FMTParamsManip(fmtstream).param_go_to(' ', '=', '\'', '{', ','); + return {}; + })); buf::FMTParamsManip(fmtstream).param_go_to('=', '\'', '{', ','); manip.ignore_one_of('='); manip.ignore_every_spaces(); - if (access.is_equal_to('\'')) - { + if (access.is_equal_to('\'')) { SF_TRY(buf::Manip(fmtstream).forward()); std::basic_string_view value = SF_TRY(buf::TestManip(fmtstream).view_until('\'')); SF_TRY(executor.data.specifiers.concat(detail::FormatSpecifier{name, value})); - } - else if (access.is_a_digit()) - { + } else if (access.is_a_digit()) { std::int32_t value = 0; SF_TRY(buf::ReadManip(fmtstream).fast_read_integer(value)); SF_TRY(executor.data.specifiers.concat(detail::FormatSpecifier{name, value})); - } - else if (access.is_equal_to('{')) - { + } else if (access.is_equal_to('{')) { SF_TRY(buf::Manip(fmtstream).forward()); std::int32_t idx = SF_TRY(GetFormatIndex()); // TODO / FIXME // executor.data.specifiers.concat(detail::FormatSpecifier{name, GetTypeAtIndexAuto(idx)}); SF_TRY(manip.skip_one_of('}')); - } - else if (access.is_equal_to(',', '}')) - { + } else if (access.is_equal_to(',', '}')) { SF_TRY(executor.data.specifiers.concat(detail::FormatSpecifier{name})); } @@ -222,22 +184,21 @@ namespace stream::fmt::context /////---------- Impl ----------///// template - [[nodiscard]] std::expected BasicContext::parse_format_data() - { + [[nodiscard]] std::expected BasicContext::parse_format_data() { buf::TestAccess access(fmtstream); - buf::TestManip manip(fmtstream); + buf::TestManip manip(fmtstream); executor.data.has_spec = true; - while (buf::Access(fmtstream).is_end_of_string() == false && buf::FMTParamsManip(fmtstream).is_end_of_parameter() == false) - { + while (buf::Access(fmtstream).is_end_of_string() == false && buf::FMTParamsManip(fmtstream).is_end_of_parameter() == false) { manip.ignore_every_spaces(); - if (access.IsUpperCase()) - { SF_TRY(parse_format_data_base()); } - else if (!access.IsLowerCase()) - { SF_TRY(parse_format_dataSpecial()); } - else - { SF_TRY(parse_format_dataCustom()); } + if (access.IsUpperCase()) { + SF_TRY(parse_format_data_base()); + } else if (!access.IsLowerCase()) { + SF_TRY(parse_format_dataSpecial()); + } else { + SF_TRY(parse_format_dataCustom()); + } buf::FMTParamsManip(fmtstream).param_go_to(','); buf::TestManip(fmtstream).ignore_one_of(','); @@ -247,50 +208,43 @@ namespace stream::fmt::context template - [[nodiscard]] std::expected BasicContext::GetFormatIndex_Number() - { + [[nodiscard]] std::expected BasicContext::GetFormatIndex_Number() { std::int32_t index = -1; SF_TRY(buf::ReadManip(fmtstream).fast_read_integer(index)); - if (buf::TestAccess(fmtstream).is_equal_to(':') || buf::TestAccess(fmtstream).is_equal_to('}')) - { - if (index >= 0 && index < args_interface.size()) - { return index; } + if (buf::TestAccess(fmtstream).is_equal_to(':') || buf::TestAccess(fmtstream).is_equal_to('}')) { + if (index >= 0 && index < args_interface.size()) { + return index; + } } return std::unexpected(FMTResult::Context_ArgumentIndexResolution); } template - [[nodiscard]] std::expected BasicContext::GetFormatIndex_Name() - { + [[nodiscard]] std::expected BasicContext::GetFormatIndex_Name() { std::int32_t index = SF_TRY(args_interface.get_index_of_current_named_arg(fmtstream)); - if (buf::TestAccess(fmtstream).is_equal_to(':') || buf::TestAccess(fmtstream).is_equal_to('}')) - { - if (index >= 0 && index < args_interface.size()) - { return index; } + if (buf::TestAccess(fmtstream).is_equal_to(':') || buf::TestAccess(fmtstream).is_equal_to('}')) { + if (index >= 0 && index < args_interface.size()) { + return index; + } } return std::unexpected(FMTResult::Context_ArgumentIndexResolution); } template - [[nodiscard]] std::expected BasicContext::GetFormatIndex_SubIndex() - { + [[nodiscard]] std::expected BasicContext::GetFormatIndex_SubIndex() { buf::TestAccess access(fmtstream); - buf::TestManip manip(fmtstream); + buf::TestManip manip(fmtstream); - if (access.is_equal_to('{')) - { + if (access.is_equal_to('{')) { SF_TRY(buf::Manip(fmtstream).forward()); std::int32_t recIndex = SF_TRY(GetFormatIndex()); - if (access.is_equal_to('}') && recIndex >= 0 && recIndex < args_interface.size()) - { + if (access.is_equal_to('}') && recIndex >= 0 && recIndex < args_interface.size()) { SF_TRY(buf::Manip(fmtstream).forward()); manip.ignore_every_spaces(); - if (access.is_equal_to(':', '}')) - { + if (access.is_equal_to(':', '}')) { std::int32_t finalRecIndex = (std::int32_t)SF_TRY(args_interface.get_int_at(recIndex)); - if (finalRecIndex >= 0 && finalRecIndex < args_interface.size()) - return finalRecIndex; + if (finalRecIndex >= 0 && finalRecIndex < args_interface.size()) return finalRecIndex; } } } @@ -298,34 +252,30 @@ namespace stream::fmt::context } template - [[nodiscard]] std::expected BasicContext::GetFormatIndex() - { + [[nodiscard]] std::expected BasicContext::GetFormatIndex() { buf::TestAccess access(fmtstream); // I : if there is no number specified : ':' or '}' if (access.is_equal_to(':') || access.is_equal_to('}')) - if (values_index < args_interface.size()) - { return values_index++; } + if (values_index < args_interface.size()) { + return values_index++; + } // II: A number(idx) - if (access.is_a_digit()) - { + if (access.is_a_digit()) { return SF_FORWARD(GetFormatIndex_Number()); } // III : A name - if (access.IsLowerCase() || access.IsUpperCase()) - { + if (access.IsLowerCase() || access.IsUpperCase()) { return SF_FORWARD(GetFormatIndex_Name()); } // VI : { which is a idx to an argument - if (access.is_equal_to('{')) - { - const TChar* oldPos = fmtstream.current_pos; - std::expected res = GetFormatIndex_SubIndex(); - if (res.has_value() == false && res.error() == FMTResult::Context_ArgumentIndexResolution) - { + if (access.is_equal_to('{')) { + const TChar* oldPos = fmtstream.current_pos; + std::expected res = GetFormatIndex_SubIndex(); + if (res.has_value() == false && res.error() == FMTResult::Context_ArgumentIndexResolution) { fmtstream.current_pos = oldPos; return std::unexpected(FMTResult::Context_ArgumentIndexResolution); } @@ -336,22 +286,21 @@ namespace stream::fmt::context } template - [[nodiscard]] std::expected BasicContext::ParseVariable(std::int32_t formatIdx) - { - detail::FormatData saveFormatData = executor.data; - executor.data = detail::FormatData{}; + [[nodiscard]] std::expected BasicContext::ParseVariable(std::int32_t formatIdx) { + detail::FormatData saveFormatData = executor.data; + executor.data = detail::FormatData{}; detail::TextProperties::Properties saveTextProperties = executor.text_manager.save(); - if (buf::TestAccess(fmtstream).is_equal_to(':', '{')) - { + if (buf::TestAccess(fmtstream).is_equal_to(':', '{')) { SF_TRY(buf::Manip(fmtstream).forward()); SF_TRY(parse_format_data()); } SF_TRY(args_interface.run_type_at(formatIdx)); - if (executor.data.keep_new_style == false) - { SF_TRY(executor.text_manager.reload(saveTextProperties)); } + if (executor.data.keep_new_style == false) { + SF_TRY(executor.text_manager.reload(saveTextProperties)); + } executor.data = saveFormatData; @@ -359,27 +308,23 @@ namespace stream::fmt::context } template - [[nodiscard]] std::expected BasicContext::parse() - { + [[nodiscard]] std::expected BasicContext::parse() { buf::Manip(fmtstream).forward(); // Ignore { - if (buf::TestAccess(fmtstream).IsUpperCase()) - { + if (buf::TestAccess(fmtstream).IsUpperCase()) { SF_TRY(parse_format_data()); - return buf::FMTParamsManip(fmtstream).param_go_to_forward(); // Ignore } + return buf::FMTParamsManip(fmtstream).param_go_to_forward(); // Ignore } } auto formatIdx = GetFormatIndex(); - if (formatIdx.has_value()) - { - if (formatIdx.value() >= 0 && formatIdx.value() < args_interface.size()) - { + if (formatIdx.has_value()) { + if (formatIdx.value() >= 0 && formatIdx.value() < args_interface.size()) { SF_TRY(ParseVariable(formatIdx.value())); - return buf::FMTParamsManip(fmtstream).param_go_to_forward(); // Ignore } + return buf::FMTParamsManip(fmtstream).param_go_to_forward(); // Ignore } } } SF_TRY(executor.exec_raw_string("{")); return {}; } -} +} // namespace stream::fmt::context diff --git a/src/stream/fmt/context/basic_context/text_properties_executor.h b/src/stream/fmt/context/basic_context/text_properties_executor.h index b9ccaed8..2f2f8741 100644 --- a/src/stream/fmt/context/basic_context/text_properties_executor.h +++ b/src/stream/fmt/context/basic_context/text_properties_executor.h @@ -3,10 +3,8 @@ #include "stream/fmt/detail/prelude.h" #include "stream/fmt/text_properties/text_properties.h" -namespace stream::fmt::detail -{ - class ITextPropertiesExecutor - { +namespace stream::fmt::detail { + class ITextPropertiesExecutor { public: virtual ~ITextPropertiesExecutor() = default; @@ -45,4 +43,4 @@ namespace stream::fmt::detail [[nodiscard]] virtual std::expected execute_style(const TextProperties::TextStyle::Ideogram& t) = 0; [[nodiscard]] virtual std::expected execute_style(const TextProperties::TextStyle::Script& t) = 0; }; -} +} // namespace stream::fmt::detail diff --git a/src/stream/fmt/context/basic_context/text_properties_manager.cpp b/src/stream/fmt/context/basic_context/text_properties_manager.cpp index 73556045..20ab8632 100644 --- a/src/stream/fmt/context/basic_context/text_properties_manager.cpp +++ b/src/stream/fmt/context/basic_context/text_properties_manager.cpp @@ -1,13 +1,9 @@ #include "text_properties_manager.h" -namespace stream::fmt::detail -{ - [[nodiscard]] std::expected TextPropertiesapplyManager::reload_color_fg(const TextProperties::TextColor::ColorFG& target) - { - if (target.type != current_context_properties_.color.fg.type) - { - switch (target.type) - { +namespace stream::fmt::detail { + [[nodiscard]] std::expected TextPropertiesapplyManager::reload_color_fg(const TextProperties::TextColor::ColorFG& target) { + if (target.type != current_context_properties_.color.fg.type) { + switch (target.type) { case TextProperties::TextColor::ColorType::BasicColor: return apply_color(target.data.basic_color); case TextProperties::TextColor::ColorType::ColorCube: @@ -15,34 +11,25 @@ namespace stream::fmt::detail case TextProperties::TextColor::ColorType::Color24b: return apply_color(target.data.color24b); } - } - else - { - switch (target.type) - { + } else { + switch (target.type) { case TextProperties::TextColor::ColorType::BasicColor: - if (current_context_properties_.color.fg.data.basic_color != target.data.basic_color) - return apply_color(target.data.basic_color); + if (current_context_properties_.color.fg.data.basic_color != target.data.basic_color) return apply_color(target.data.basic_color); break; case TextProperties::TextColor::ColorType::ColorCube: - if (current_context_properties_.color.fg.data.color_cube != target.data.color_cube) - return apply_color(target.data.color_cube); + if (current_context_properties_.color.fg.data.color_cube != target.data.color_cube) return apply_color(target.data.color_cube); break; case TextProperties::TextColor::ColorType::Color24b: - if (current_context_properties_.color.fg.data.color24b != target.data.color24b) - return apply_color(target.data.color24b); + if (current_context_properties_.color.fg.data.color24b != target.data.color24b) return apply_color(target.data.color24b); break; } } return {}; } - [[nodiscard]] std::expected TextPropertiesapplyManager::reload_color_bg(const TextProperties::TextColor::ColorBG& target) - { - if (target.type != current_context_properties_.color.bg.type) - { - switch (target.type) - { + [[nodiscard]] std::expected TextPropertiesapplyManager::reload_color_bg(const TextProperties::TextColor::ColorBG& target) { + if (target.type != current_context_properties_.color.bg.type) { + switch (target.type) { case TextProperties::TextColor::ColorType::BasicColor: return apply_color(target.data.basic_color); case TextProperties::TextColor::ColorType::ColorCube: @@ -50,71 +37,55 @@ namespace stream::fmt::detail case TextProperties::TextColor::ColorType::Color24b: return apply_color(target.data.color24b); } - } - else - { - switch (target.type) - { + } else { + switch (target.type) { case TextProperties::TextColor::ColorType::BasicColor: - if (current_context_properties_.color.bg.data.basic_color != target.data.basic_color) - return apply_color(target.data.basic_color); + if (current_context_properties_.color.bg.data.basic_color != target.data.basic_color) return apply_color(target.data.basic_color); break; case TextProperties::TextColor::ColorType::ColorCube: - if (current_context_properties_.color.bg.data.color_cube != target.data.color_cube) - return apply_color(target.data.color_cube); + if (current_context_properties_.color.bg.data.color_cube != target.data.color_cube) return apply_color(target.data.color_cube); break; case TextProperties::TextColor::ColorType::Color24b: - if (current_context_properties_.color.bg.data.color24b != target.data.color24b) - return apply_color(target.data.color24b); + if (current_context_properties_.color.bg.data.color24b != target.data.color24b) return apply_color(target.data.color24b); break; } } return {}; } - [[nodiscard]] std::expected TextPropertiesapplyManager::reload_style(const TextProperties::TextStyle::Style& target) - { - if (target.intensity != current_context_properties_.style.intensity) - { + [[nodiscard]] std::expected TextPropertiesapplyManager::reload_style(const TextProperties::TextStyle::Style& target) { + if (target.intensity != current_context_properties_.style.intensity) { SF_TRY(apply_style(target.intensity)); current_context_properties_.style.intensity = target.intensity; } - if (target.italic != current_context_properties_.style.italic) - { + if (target.italic != current_context_properties_.style.italic) { SF_TRY(apply_style(target.italic)); current_context_properties_.style.italic = target.italic; } - if (target.blink != current_context_properties_.style.blink) - { + if (target.blink != current_context_properties_.style.blink) { SF_TRY(apply_style(target.blink)); current_context_properties_.style.blink = target.blink; } - if (target.inverted != current_context_properties_.style.inverted) - { + if (target.inverted != current_context_properties_.style.inverted) { SF_TRY(apply_style(target.inverted)); current_context_properties_.style.inverted = target.inverted; } - if (target.ideogram != current_context_properties_.style.ideogram) - { + if (target.ideogram != current_context_properties_.style.ideogram) { SF_TRY(apply_style(target.ideogram)); current_context_properties_.style.ideogram = target.ideogram; } - if (target.script != current_context_properties_.style.script) - { + if (target.script != current_context_properties_.style.script) { SF_TRY(apply_style(target.script)); current_context_properties_.style.script = target.script; } - if (target.underline != current_context_properties_.style.underline) - { + if (target.underline != current_context_properties_.style.underline) { SF_TRY(apply_style(target.underline)); current_context_properties_.style.underline = target.underline; } - if (target.underline_color.type != current_context_properties_.style.underline_color.type) - { - switch (target.underline_color.type) - { + if (target.underline_color.type != current_context_properties_.style.underline_color.type) { + switch (target.underline_color.type) { case TextProperties::TextStyle::UnderlineColor::ColorType::Default: SF_TRY(apply_style(TextProperties::TextStyle::UnderlineColor::ColorCube{TextProperties::TextStyle::UnderlineColor::ColorCube::Default})); break; @@ -128,23 +99,18 @@ namespace stream::fmt::detail break; } current_context_properties_.style.underline_color.type = target.underline_color.type; - } - else - { - switch (target.underline_color.type) - { + } else { + switch (target.underline_color.type) { case TextProperties::TextStyle::UnderlineColor::ColorType::Default: break; case TextProperties::TextStyle::UnderlineColor::ColorType::ColorCube: - if (current_context_properties_.style.underline_color.data.color_cube != target.underline_color.data.color_cube) - { + if (current_context_properties_.style.underline_color.data.color_cube != target.underline_color.data.color_cube) { SF_TRY(apply_style(target.underline_color.data.color_cube)); current_context_properties_.style.underline_color.data.color_cube = target.underline_color.data.color_cube; } break; case TextProperties::TextStyle::UnderlineColor::ColorType::Color24b: - if (current_context_properties_.style.underline_color.data.color24b != target.underline_color.data.color24b) - { + if (current_context_properties_.style.underline_color.data.color24b != target.underline_color.data.color24b) { SF_TRY(apply_style(target.underline_color.data.color24b)); current_context_properties_.style.underline_color.data.color24b = target.underline_color.data.color24b; } @@ -154,13 +120,11 @@ namespace stream::fmt::detail return {}; } - [[nodiscard]] std::expected TextPropertiesapplyManager::reload_front(const TextProperties::TextFront::Front& target) - { - if (current_context_properties_.front == target) - return {}; + [[nodiscard]] std::expected TextPropertiesapplyManager::reload_front(const TextProperties::TextFront::Front& target) { + if (current_context_properties_.front == target) return {}; SF_TRY(apply_front(target.CurrentID)); current_context_properties_.front = target; return {}; } -} +} // namespace stream::fmt::detail diff --git a/src/stream/fmt/context/basic_context/text_properties_manager.h b/src/stream/fmt/context/basic_context/text_properties_manager.h index 2f40ee7b..d3774563 100644 --- a/src/stream/fmt/context/basic_context/text_properties_manager.h +++ b/src/stream/fmt/context/basic_context/text_properties_manager.h @@ -7,91 +7,87 @@ #include "stream/fmt/buf/test_manip.h" #include "stream/fmt/buf/utils/buffer_utils.h" -namespace stream::fmt::detail -{ - class TextPropertiesapplyManager - { +namespace stream::fmt::detail { + class TextPropertiesapplyManager { public: - TextPropertiesapplyManager(ITextPropertiesExecutor& text_properties_executor) - : text_properties_executor_{text_properties_executor} - , current_context_properties_{} - {} + TextPropertiesapplyManager(ITextPropertiesExecutor& text_properties_executor) : text_properties_executor_{text_properties_executor}, current_context_properties_{} {} - [[nodiscard]] std::expected terminate() { return reload_default(); } + [[nodiscard]] std::expected terminate() { + return reload_default(); + } public: template - requires detail::text_properties_color_can_apply - [[nodiscard]] std::expected apply_color(const T& modif) - { + requires detail::text_properties_color_can_apply + [[nodiscard]] std::expected apply_color(const T& modif) { current_context_properties_.color.apply(modif); return text_properties_executor_.execute_color(modif); } template - requires detail::text_properties_style_can_apply - [[nodiscard]] std::expected apply_style(const T& modif) - { + requires detail::text_properties_style_can_apply + [[nodiscard]] std::expected apply_style(const T& modif) { current_context_properties_.style.apply(modif); return text_properties_executor_.execute_style(modif); } template - requires detail::text_properties_front_can_apply - [[nodiscard]] std::expected apply_front(const T& modif) - { + requires detail::text_properties_front_can_apply + [[nodiscard]] std::expected apply_front(const T& modif) { current_context_properties_.front.apply(modif); return text_properties_executor_.execute_front(modif); } - [[nodiscard]] std::expected all_properties_reset() - { + [[nodiscard]] std::expected all_properties_reset() { SF_TRY(apply_color_reset()); SF_TRY(apply_style_reset()); return apply_front_reset(); } - [[nodiscard]] std::expected apply_color_reset() - { + [[nodiscard]] std::expected apply_color_reset() { current_context_properties_.color.modify_reset(); return text_properties_executor_.reset_color(); } - [[nodiscard]] std::expected apply_style_reset() - { + [[nodiscard]] std::expected apply_style_reset() { current_context_properties_.style.modify_reset(); return text_properties_executor_.reset_style(); } - [[nodiscard]] std::expected apply_front_reset() - { + [[nodiscard]] std::expected apply_front_reset() { current_context_properties_.front.modify_reset(); return text_properties_executor_.reset_front(); } public: - detail::TextProperties::Properties save() { return current_context_properties_; } + detail::TextProperties::Properties save() { + return current_context_properties_; + } public: - [[nodiscard]] std::expected reload_default() - { + [[nodiscard]] std::expected reload_default() { SF_TRY(reload_default_color()); SF_TRY(reload_default_style()); return reload_default_front(); } - [[nodiscard]] std::expected reload_default_color() - { + [[nodiscard]] std::expected reload_default_color() { SF_TRY(reload_default_color_fg()); return reload_default_color_bg(); } - [[nodiscard]] std::expected reload_default_color_fg() { return reload_color_fg(detail::TextProperties::TextColor::ColorFG{}); } - [[nodiscard]] std::expected reload_default_color_bg() { return reload_color_bg(detail::TextProperties::TextColor::ColorBG{}); } - [[nodiscard]] std::expected reload_default_style() { return reload_style(detail::TextProperties::TextStyle::Style{}); } - [[nodiscard]] std::expected reload_default_front() { return reload_front(detail::TextProperties::TextFront::Front{}); } + [[nodiscard]] std::expected reload_default_color_fg() { + return reload_color_fg(detail::TextProperties::TextColor::ColorFG{}); + } + [[nodiscard]] std::expected reload_default_color_bg() { + return reload_color_bg(detail::TextProperties::TextColor::ColorBG{}); + } + [[nodiscard]] std::expected reload_default_style() { + return reload_style(detail::TextProperties::TextStyle::Style{}); + } + [[nodiscard]] std::expected reload_default_front() { + return reload_front(detail::TextProperties::TextFront::Front{}); + } - [[nodiscard]] std::expected reload(const detail::TextProperties::Properties& target) - { + [[nodiscard]] std::expected reload(const detail::TextProperties::Properties& target) { SF_TRY(reload_color(target.color)); SF_TRY(reload_style(target.style)); return reload_front(target.front); } - [[nodiscard]] std::expected reload_color(const detail::TextProperties::TextColor::Color& target) - { + [[nodiscard]] std::expected reload_color(const detail::TextProperties::TextColor::Color& target) { SF_TRY(reload_color_fg(target.fg)); return reload_color_bg(target.bg); } @@ -102,93 +98,82 @@ namespace stream::fmt::detail [[nodiscard]] std::expected reload_front(const detail::TextProperties::TextFront::Front& target); public: - ITextPropertiesExecutor& get_text_properties_executor() { return text_properties_executor_; } - detail::TextProperties::Properties& get_current_context_properties() { return current_context_properties_; } + ITextPropertiesExecutor& get_text_properties_executor() { + return text_properties_executor_; + } + detail::TextProperties::Properties& get_current_context_properties() { + return current_context_properties_; + } protected: - ITextPropertiesExecutor& text_properties_executor_; - detail::TextProperties::Properties current_context_properties_; + ITextPropertiesExecutor& text_properties_executor_; + detail::TextProperties::Properties current_context_properties_; public: template - requires detail::text_properties_color_can_apply - [[nodiscard]] inline std::expected ask_apply_color(const T& modif) - { - if (current_context_properties_.color.need_modif(modif)) - return apply_color(modif); + requires detail::text_properties_color_can_apply + [[nodiscard]] inline std::expected ask_apply_color(const T& modif) { + if (current_context_properties_.color.need_modif(modif)) return apply_color(modif); return {}; } template - requires detail::text_properties_style_can_apply - [[nodiscard]] inline std::expected ask_apply_style(const T& modif) - { - if (current_context_properties_.style.need_modif(modif)) - return apply_style(modif); + requires detail::text_properties_style_can_apply + [[nodiscard]] inline std::expected ask_apply_style(const T& modif) { + if (current_context_properties_.style.need_modif(modif)) return apply_style(modif); return {}; } template - requires detail::text_properties_front_can_apply - [[nodiscard]] inline std::expected ask_apply_front(const T& modif) - { - if (current_context_properties_.front.need_modif(modif)) - return apply_front(modif); + requires detail::text_properties_front_can_apply + [[nodiscard]] inline std::expected ask_apply_front(const T& modif) { + if (current_context_properties_.front.need_modif(modif)) return apply_front(modif); return {}; } - [[nodiscard]] std::expected ask_apply_color(const detail::TextProperties::TextColor::BasicColor& modif) - { - if (current_context_properties_.color.need_modif(modif.fg)) - { - if (current_context_properties_.color.need_modif(modif.bg)) - return apply_color(modif); + [[nodiscard]] std::expected ask_apply_color(const detail::TextProperties::TextColor::BasicColor& modif) { + if (current_context_properties_.color.need_modif(modif.fg)) { + if (current_context_properties_.color.need_modif(modif.bg)) return apply_color(modif); return apply_color(modif.fg); } - if (current_context_properties_.color.need_modif(modif.fg)) - return apply_color(modif.bg); + if (current_context_properties_.color.need_modif(modif.fg)) return apply_color(modif.bg); return {}; } - [[nodiscard]] std::expected ask_apply_color(const detail::TextProperties::TextColor::ColorCube& modif) - { - if (current_context_properties_.color.need_modif(modif.fg)) - { - if (current_context_properties_.color.need_modif(modif)) - return apply_color(modif); + [[nodiscard]] std::expected ask_apply_color(const detail::TextProperties::TextColor::ColorCube& modif) { + if (current_context_properties_.color.need_modif(modif.fg)) { + if (current_context_properties_.color.need_modif(modif)) return apply_color(modif); return apply_color(modif.fg); } - if (current_context_properties_.color.need_modif(modif.fg)) - return apply_color(modif.bg); + if (current_context_properties_.color.need_modif(modif.fg)) return apply_color(modif.bg); return {}; } - [[nodiscard]] std::expected ask_apply_color(const detail::TextProperties::TextColor::Color24b& modif) - { - if (current_context_properties_.color.need_modif(modif.fg)) - { - if (current_context_properties_.color.need_modif(modif)) - return apply_color(modif); + [[nodiscard]] std::expected ask_apply_color(const detail::TextProperties::TextColor::Color24b& modif) { + if (current_context_properties_.color.need_modif(modif.fg)) { + if (current_context_properties_.color.need_modif(modif)) return apply_color(modif); return apply_color(modif.fg); } - if (current_context_properties_.color.need_modif(modif.fg)) - return apply_color(modif.bg); + if (current_context_properties_.color.need_modif(modif.fg)) return apply_color(modif.bg); return {}; } - [[nodiscard]] std::expected ask_apply_color(const detail::TextProperties::TextColor::ColorFG& modif) { return reload_color_fg(modif); } - [[nodiscard]] std::expected ask_apply_color(const detail::TextProperties::TextColor::ColorBG& modif) { return reload_color_bg(modif); } - [[nodiscard]] std::expected ask_apply_color(const detail::TextProperties::TextColor::Color& modif) { return reload_color(modif); } + [[nodiscard]] std::expected ask_apply_color(const detail::TextProperties::TextColor::ColorFG& modif) { + return reload_color_fg(modif); + } + [[nodiscard]] std::expected ask_apply_color(const detail::TextProperties::TextColor::ColorBG& modif) { + return reload_color_bg(modif); + } + [[nodiscard]] std::expected ask_apply_color(const detail::TextProperties::TextColor::Color& modif) { + return reload_color(modif); + } }; template - class TextPropertiesManager : public TextPropertiesapplyManager - { + class TextPropertiesManager : public TextPropertiesapplyManager { public: - TextPropertiesManager(ITextPropertiesExecutor& text_properties_executor) - : TextPropertiesapplyManager(text_properties_executor) - {} + TextPropertiesManager(ITextPropertiesExecutor& text_properties_executor) : TextPropertiesapplyManager(text_properties_executor) {} public: [[nodiscard]] std::expected apply_colorOnIndex(context::BasicContext& context, std::int32_t index); @@ -202,25 +187,24 @@ namespace stream::fmt::detail private: template - [[nodiscard]] std::expected get_color_code(buf::StreamView& format); - [[nodiscard]] std::expected parse_style_named(buf::StreamView& format); + [[nodiscard]] std::expected get_color_code(buf::StreamView& format); + [[nodiscard]] std::expected parse_style_named(buf::StreamView& format); [[nodiscard]] std::expected select_underlined_color_style(buf::StreamView& format); }; -} +} // namespace stream::fmt::detail -namespace stream::fmt::detail -{ +namespace stream::fmt::detail { template template - [[nodiscard]] std::expected detail::TextPropertiesManager::get_color_code(buf::StreamView& format) - { + [[nodiscard]] std::expected detail::TextPropertiesManager::get_color_code(buf::StreamView& format) { static constexpr std::string_view colorCode[] = {"black", "red", "green", "yellow", "blue", "magenta", "cyan", "white", " ", "default"}; - bool bright = SF_TRY(buf::TestManip(format).is_equal_to_forward('+')); - std::uint8_t step = static_cast(bright ? T::BaseBStep : T::BaseStep); - std::uint8_t code = (std::uint8_t)SF_TRY(buf::UtilsManip(format).get_word_from_list(colorCode));; + bool bright = SF_TRY(buf::TestManip(format).is_equal_to_forward('+')); + std::uint8_t step = static_cast(bright ? T::BaseBStep : T::BaseStep); + std::uint8_t code = (std::uint8_t)SF_TRY(buf::UtilsManip(format).get_word_from_list(colorCode)); + ; return static_cast(code + step); } -} +} // namespace stream::fmt::detail #include "text_properties_manager_impl.h" diff --git a/src/stream/fmt/context/basic_context/text_properties_manager_impl.h b/src/stream/fmt/context/basic_context/text_properties_manager_impl.h index aff2b75f..78240298 100644 --- a/src/stream/fmt/context/basic_context/text_properties_manager_impl.h +++ b/src/stream/fmt/context/basic_context/text_properties_manager_impl.h @@ -8,185 +8,231 @@ #include "stream/fmt/buf/fmt_manip_io.h" #include "stream/fmt/buf/utils/buffer_utils.h" -namespace stream::fmt::detail -{ +namespace stream::fmt::detail { template - [[nodiscard]] std::expected detail::TextPropertiesManager::apply_colorOnIndex(context::BasicContext& context, std::int32_t index) - { + [[nodiscard]] std::expected detail::TextPropertiesManager::apply_colorOnIndex(context::BasicContext& context, std::int32_t index) { SF_TRY(context.args_interface.template run_func_from_type_at( - index, [this](const detail::TextProperties::TextColor::Color& data) -> std::expected { this->reload_color(data); return {}; })); + index, [this](const detail::TextProperties::TextColor::Color& data) -> std::expected { + this->reload_color(data); + return {}; + })); SF_TRY(context.args_interface.template run_func_from_type_at( - index, [this](const detail::TextProperties::TextColor::BasicColorFG& data) -> std::expected { this->ask_apply_color(data); return {}; })); + index, [this](const detail::TextProperties::TextColor::BasicColorFG& data) -> std::expected { + this->ask_apply_color(data); + return {}; + })); SF_TRY(context.args_interface.template run_func_from_type_at( - index, [this](const detail::TextProperties::TextColor::BasicColorBG& data) -> std::expected { this->ask_apply_color(data); return {}; })); + index, [this](const detail::TextProperties::TextColor::BasicColorBG& data) -> std::expected { + this->ask_apply_color(data); + return {}; + })); SF_TRY(context.args_interface.template run_func_from_type_at( - index, [this](const detail::TextProperties::TextColor::ColorCubeFG& data) -> std::expected { this->ask_apply_color(data); return {}; })); + index, [this](const detail::TextProperties::TextColor::ColorCubeFG& data) -> std::expected { + this->ask_apply_color(data); + return {}; + })); SF_TRY(context.args_interface.template run_func_from_type_at( - index, [this](const detail::TextProperties::TextColor::ColorCubeBG& data) -> std::expected { this->ask_apply_color(data); return {}; })); + index, [this](const detail::TextProperties::TextColor::ColorCubeBG& data) -> std::expected { + this->ask_apply_color(data); + return {}; + })); SF_TRY(context.args_interface.template run_func_from_type_at( - index, [this](const detail::TextProperties::TextColor::Color24bFG& data) -> std::expected { this->ask_apply_color(data); return {}; })); + index, [this](const detail::TextProperties::TextColor::Color24bFG& data) -> std::expected { + this->ask_apply_color(data); + return {}; + })); SF_TRY(context.args_interface.template run_func_from_type_at( - index, [this](const detail::TextProperties::TextColor::Color24bBG& data) -> std::expected { this->ask_apply_color(data); return {}; })); + index, [this](const detail::TextProperties::TextColor::Color24bBG& data) -> std::expected { + this->ask_apply_color(data); + return {}; + })); return {}; } template - [[nodiscard]] std::expected detail::TextPropertiesManager::apply_frontOnIndex(context::BasicContext& context, std::int32_t index) - { + [[nodiscard]] std::expected detail::TextPropertiesManager::apply_frontOnIndex(context::BasicContext& context, std::int32_t index) { SF_TRY(context.args_interface.template run_func_from_type_at( - index, [this](const detail::TextProperties::TextFront::Front& data) -> std::expected { this->reload_front(data); return {}; })); + index, [this](const detail::TextProperties::TextFront::Front& data) -> std::expected { + this->reload_front(data); + return {}; + })); SF_TRY(context.args_interface.template run_func_from_type_at( - index, [this](const detail::TextProperties::TextFront::FrontID& data) -> std::expected { this->ask_apply_front(data); return {}; })); + index, [this](const detail::TextProperties::TextFront::FrontID& data) -> std::expected { + this->ask_apply_front(data); + return {}; + })); return {}; } template - [[nodiscard]] std::expected detail::TextPropertiesManager::apply_styleOnIndex(context::BasicContext& context, std::int32_t index) - { + [[nodiscard]] std::expected detail::TextPropertiesManager::apply_styleOnIndex(context::BasicContext& context, std::int32_t index) { SF_TRY(context.args_interface.template run_func_from_type_at( - index, [this](const detail::TextProperties::TextStyle::Style& data) -> std::expected { return this->reload_style(data); return {}; })); + index, [this](const detail::TextProperties::TextStyle::Style& data) -> std::expected { + return this->reload_style(data); + return {}; + })); SF_TRY(context.args_interface.template run_func_from_type_at( - index, [this](const detail::TextProperties::TextStyle::Intensity& data) -> std::expected { return this->ask_apply_style(data); return {}; })); + index, [this](const detail::TextProperties::TextStyle::Intensity& data) -> std::expected { + return this->ask_apply_style(data); + return {}; + })); SF_TRY(context.args_interface.template run_func_from_type_at( - index, [this](const detail::TextProperties::TextStyle::Italic& data) -> std::expected { return this->ask_apply_style(data); return {}; })); + index, [this](const detail::TextProperties::TextStyle::Italic& data) -> std::expected { + return this->ask_apply_style(data); + return {}; + })); SF_TRY(context.args_interface.template run_func_from_type_at( - index, [this](const detail::TextProperties::TextStyle::Underline& data) -> std::expected { return this->ask_apply_style(data); return {}; })); + index, [this](const detail::TextProperties::TextStyle::Underline& data) -> std::expected { + return this->ask_apply_style(data); + return {}; + })); SF_TRY(context.args_interface.template run_func_from_type_at( - index, [this](const detail::TextProperties::TextStyle::Blink& data) -> std::expected { return this->ask_apply_style(data); return {}; })); + index, [this](const detail::TextProperties::TextStyle::Blink& data) -> std::expected { + return this->ask_apply_style(data); + return {}; + })); SF_TRY(context.args_interface.template run_func_from_type_at( - index, [this](const detail::TextProperties::TextStyle::Inverted& data) -> std::expected { return this->ask_apply_style(data); return {}; })); + index, [this](const detail::TextProperties::TextStyle::Inverted& data) -> std::expected { + return this->ask_apply_style(data); + return {}; + })); SF_TRY(context.args_interface.template run_func_from_type_at( - index, [this](const detail::TextProperties::TextStyle::Ideogram& data) -> std::expected { return this->ask_apply_style(data); return {}; })); + index, [this](const detail::TextProperties::TextStyle::Ideogram& data) -> std::expected { + return this->ask_apply_style(data); + return {}; + })); SF_TRY(context.args_interface.template run_func_from_type_at( - index, [this](const detail::TextProperties::TextStyle::Script& data) -> std::expected { return this->ask_apply_style(data); return {}; })); + index, [this](const detail::TextProperties::TextStyle::Script& data) -> std::expected { + return this->ask_apply_style(data); + return {}; + })); SF_TRY(context.args_interface.template run_func_from_type_at( - index, [this](const detail::TextProperties::TextStyle::UnderlineColor::ColorCube& data) -> std::expected { this->ask_apply_style(data); return {}; })); + index, [this](const detail::TextProperties::TextStyle::UnderlineColor::ColorCube& data) -> std::expected { + this->ask_apply_style(data); + return {}; + })); SF_TRY(context.args_interface.template run_func_from_type_at( - index, [this](const detail::TextProperties::TextStyle::UnderlineColor::Color24b& data) -> std::expected { this->ask_apply_style(data); return {}; })); + index, [this](const detail::TextProperties::TextStyle::UnderlineColor::Color24b& data) -> std::expected { + this->ask_apply_style(data); + return {}; + })); return {}; } template - [[nodiscard]] std::expected detail::TextPropertiesManager::parse_color(context::BasicContext& context) - { - if (buf::TestAccess(context.fmtstream).is_equal_to(':')) - { + [[nodiscard]] std::expected detail::TextPropertiesManager::parse_color(context::BasicContext& context) { + if (buf::TestAccess(context.fmtstream).is_equal_to(':')) { SF_TRY(buf::Manip(context.fmtstream).forward()); buf::TestManip(context.fmtstream).ignore_every_spaces(); - if (buf::TestAccess(context.fmtstream).is_equal_to('{')) - { + if (buf::TestAccess(context.fmtstream).is_equal_to('{')) { SF_TRY(buf::Manip(context.fmtstream).forward()); std::int32_t idx = SF_TRY(context.GetFormatIndex()); SF_TRY(apply_colorOnIndex(context, idx)); SF_TRY(buf::TestManip(context.fmtstream).skip_one_of('}')); - } - else - { + } else { auto color_fg = get_color_code(context.fmtstream); buf::FMTParamsManip(context.fmtstream).param_go_to('-', ','); - if (buf::TestAccess(context.fmtstream).is_equal_to('-')) - { + if (buf::TestAccess(context.fmtstream).is_equal_to('-')) { SF_TRY(buf::Manip(context.fmtstream).forward()); buf::TestManip(context.fmtstream).ignore_every_spaces(); auto color_bg = get_color_code(context.fmtstream); - if (color_bg.has_value() && color_fg.has_value()) - { return ask_apply_color(detail::TextProperties::TextColor::BasicColor{color_fg.value(), color_bg.value()}); } - else - { return reload_default_color(); } - } - else - { - if (color_fg.has_value()) - { return ask_apply_color(color_fg.value()); } - else - { return reload_default_color(); } + if (color_bg.has_value() && color_fg.has_value()) { + return ask_apply_color(detail::TextProperties::TextColor::BasicColor{color_fg.value(), color_bg.value()}); + } else { + return reload_default_color(); + } + } else { + if (color_fg.has_value()) { + return ask_apply_color(color_fg.value()); + } else { + return reload_default_color(); + } } } + } else { + return reload_default_color(); } - else - { return reload_default_color(); } return {}; } template - [[nodiscard]] std::expected detail::TextPropertiesManager::parse_style(context::BasicContext& context) - { - if (buf::TestAccess(context.fmtstream).is_equal_to(':')) - { + [[nodiscard]] std::expected detail::TextPropertiesManager::parse_style(context::BasicContext& context) { + if (buf::TestAccess(context.fmtstream).is_equal_to(':')) { SF_TRY(buf::Manip(context.fmtstream).forward()); - if (!buf::TestAccess(context.fmtstream).is_equal_to('}', ',')) - { + if (!buf::TestAccess(context.fmtstream).is_equal_to('}', ',')) { bool loop = true; - while (loop) - { + while (loop) { buf::TestManip(context.fmtstream).ignore_every_spaces(); - if (buf::TestAccess(context.fmtstream).is_equal_to('{')) - { + if (buf::TestAccess(context.fmtstream).is_equal_to('{')) { SF_TRY(buf::Manip(context.fmtstream).forward()); std::int32_t idx = SF_TRY(context.GetFormatIndex()); apply_styleOnIndex(context, idx); buf::TestManip(context.fmtstream).skip_one_of('}'); - } - else - { + } else { parse_style_named(context.fmtstream); } buf::FMTParamsManip(context.fmtstream).param_go_to('|', ','); loop = SF_TRY(buf::TestManip(context.fmtstream).is_equal_to_forward('|')); buf::TestManip(context.fmtstream).ignore_every_spaces(); } + } else { + return reload_default_style(); } - else - { return reload_default_style(); } + } else { + return reload_default_style(); } - else - { return reload_default_style(); } return {}; } template - [[nodiscard]] std::expected detail::TextPropertiesManager::parse_style_named(buf::StreamView& format) - { + [[nodiscard]] std::expected detail::TextPropertiesManager::parse_style_named(buf::StreamView& format) { buf::UtilsManip utils(format); - + static constexpr std::pair, detail::TextProperties::TextStyle::Intensity> styleIntensity[] = { - {"bold", detail::TextProperties::TextStyle::Intensity::Bold}, - {"dim", detail::TextProperties::TextStyle::Intensity::Dim}, + { "bold", detail::TextProperties::TextStyle::Intensity::Bold}, + { "dim", detail::TextProperties::TextStyle::Intensity::Dim}, {"n-intensity", detail::TextProperties::TextStyle::Intensity::Normal} }; static constexpr std::pair, detail::TextProperties::TextStyle::Italic> styleItalic[] = { - {"italic", detail::TextProperties::TextStyle::Italic::enable}, + { "italic", detail::TextProperties::TextStyle::Italic::enable}, {"n-italic", detail::TextProperties::TextStyle::Italic::Disable} }; // TODO: magic values static constexpr typename std::pair, detail::TextProperties::TextStyle::Underline> styleUnderline[] = { - {"underlined", detail::TextProperties::TextStyle::Underline::Underlined}, - {"d-underlined", detail::TextProperties::TextStyle::Underline::DoubleUnerlined}, - {"n-underlined", detail::TextProperties::TextStyle::Underline::Disable}, - {"c-underlined", detail::TextProperties::TextStyle::Underline::SelectUnderlinedColor}}; + { "underlined", detail::TextProperties::TextStyle::Underline::Underlined}, + {"d-underlined", detail::TextProperties::TextStyle::Underline::DoubleUnerlined}, + {"n-underlined", detail::TextProperties::TextStyle::Underline::Disable}, + {"c-underlined", detail::TextProperties::TextStyle::Underline::SelectUnderlinedColor} + }; - static constexpr typename std::pair, detail::TextProperties::TextStyle::Blink> styleBlink[] = {{"slowblink", detail::TextProperties::TextStyle::Blink::SlowBlink}, - {"fastblink", detail::TextProperties::TextStyle::Blink::FastBlink}, - {"n-blink", detail::TextProperties::TextStyle::Blink::Disable}}; + static constexpr typename std::pair, detail::TextProperties::TextStyle::Blink> styleBlink[] = { + {"slowblink", detail::TextProperties::TextStyle::Blink::SlowBlink}, + {"fastblink", detail::TextProperties::TextStyle::Blink::FastBlink}, + { "n-blink", detail::TextProperties::TextStyle::Blink::Disable} + }; static constexpr typename std::pair, detail::TextProperties::TextStyle::Inverted> styleInverted[] = { - {"inverted", detail::TextProperties::TextStyle::Inverted::enable}, + { "inverted", detail::TextProperties::TextStyle::Inverted::enable}, {"n-inverted", detail::TextProperties::TextStyle::Inverted::Disable}, }; static constexpr typename std::pair, detail::TextProperties::TextStyle::Ideogram> styleIdeogram[] = { - {"i-underlined", detail::TextProperties::TextStyle::Ideogram::Underlined}, {"i-d-underlined", detail::TextProperties::TextStyle::Ideogram::DoubleUnderlined}, - {"i-overlined", detail::TextProperties::TextStyle::Ideogram::Overlined}, {"i-d-overlined", detail::TextProperties::TextStyle::Ideogram::DoubleOverlined}, - {"i-stress", detail::TextProperties::TextStyle::Ideogram::StressMarking}, {"n-i", detail::TextProperties::TextStyle::Ideogram::AllDisable}, + { "i-underlined", detail::TextProperties::TextStyle::Ideogram::Underlined}, + {"i-d-underlined", detail::TextProperties::TextStyle::Ideogram::DoubleUnderlined}, + { "i-overlined", detail::TextProperties::TextStyle::Ideogram::Overlined}, + { "i-d-overlined", detail::TextProperties::TextStyle::Ideogram::DoubleOverlined}, + { "i-stress", detail::TextProperties::TextStyle::Ideogram::StressMarking}, + { "n-i", detail::TextProperties::TextStyle::Ideogram::AllDisable}, }; static constexpr typename std::pair, detail::TextProperties::TextStyle::Script> styleScript[] = { {"superscript", detail::TextProperties::TextStyle::Script::Superscript}, - {"subscript", detail::TextProperties::TextStyle::Script::Subscript}, - {"n-script", detail::TextProperties::TextStyle::Script::AllDisable}}; + { "subscript", detail::TextProperties::TextStyle::Script::Subscript}, + { "n-script", detail::TextProperties::TextStyle::Script::AllDisable} + }; std::uint8_t code = (std::uint8_t)SF_TRY(buf::UtilsManip(format).get_word_from_dict_pairs(styleIntensity)); if (code != 255) return apply_style(detail::TextProperties::TextStyle::Intensity{code}); @@ -202,10 +248,8 @@ namespace stream::fmt::detail if (code != 255) return apply_style(detail::TextProperties::TextStyle::Script{code}); code = (std::uint8_t)SF_TRY(buf::UtilsManip(format).get_word_from_dict_pairs(styleUnderline)); - if (code != 255) - { - if (code == (std::uint8_t)detail::TextProperties::TextStyle::Underline::SelectUnderlinedColor) - { + if (code != 255) { + if (code == (std::uint8_t)detail::TextProperties::TextStyle::Underline::SelectUnderlinedColor) { detail::TextProperties::TextStyle::UnderlineColor::ColorCube underlineColor = SF_TRY(select_underlined_color_style(format)); return apply_style(underlineColor); } @@ -215,28 +259,25 @@ namespace stream::fmt::detail } template - [[nodiscard]] std::expected TextPropertiesManager::select_underlined_color_style(buf::StreamView& format) - { + [[nodiscard]] std::expected TextPropertiesManager::select_underlined_color_style( + buf::StreamView& format) { // TODO // FIXME return std::unexpected(FMTResult::FunctionNotImpl); } template - [[nodiscard]] std::expected detail::TextPropertiesManager::parse_front(context::BasicContext& context) - { + [[nodiscard]] std::expected detail::TextPropertiesManager::parse_front(context::BasicContext& context) { static constexpr std::string_view frontCode[] = {"default", "front0", "front1", "front2", "front3", "front4", "front5", "front6", "front7", "front8", "front9"}; - if (buf::TestAccess(context.fmtstream).is_equal_to(':')) - { + if (buf::TestAccess(context.fmtstream).is_equal_to(':')) { SF_TRY(buf::Manip(context.fmtstream).forward()); buf::TestManip(context.fmtstream).ignore_every_spaces(); detail::TextProperties::TextFront::FrontID frontID = (std::uint8_t)SF_TRY(buf::UtilsManip(context.fmtstream).get_word_from_list(frontCode)); return apply_front(frontID); - } - else + } else return reload_default_front(); return {}; } -} +} // namespace stream::fmt::detail diff --git a/src/stream/fmt/context/formatter_executor/basic_formatter_executor.h b/src/stream/fmt/context/formatter_executor/basic_formatter_executor.h index 898ea0a4..22052281 100644 --- a/src/stream/fmt/context/formatter_executor/basic_formatter_executor.h +++ b/src/stream/fmt/context/formatter_executor/basic_formatter_executor.h @@ -12,19 +12,17 @@ #include "formatter_args.h" -namespace stream::fmt::context -{ - enum class EndOfStringCharMode - { +namespace stream::fmt::context { + enum class EndOfStringCharMode { Forced, Optional }; template - class BasicFormatterExecutor : public context_executor - { + class BasicFormatterExecutor : public context_executor { public: using TChar = CharType; + private: using M_Type = BasicFormatterExecutor; @@ -36,14 +34,13 @@ namespace stream::fmt::context public: buf::FMTStreamIO& ostream; - EndOfStringCharMode EndOfStringChar = EndOfStringCharMode::Optional; + EndOfStringCharMode EndOfStringChar = EndOfStringCharMode::Optional; using context_executor::data; using context_executor::text_manager; - + protected: - [[nodiscard]] std::expected exec_raw_string(std::basic_string_view sv) override - { + [[nodiscard]] std::expected exec_raw_string(std::basic_string_view sv) override { return buf::WriteManip(ostream).fast_write_string(sv); } [[nodiscard]] std::expected exec_settings() override; @@ -56,69 +53,62 @@ namespace stream::fmt::context public: template - [[nodiscard]] inline std::expected write_type(Type&& type, Rest&&... rest) - { + [[nodiscard]] inline std::expected write_type(Type&& type, Rest&&... rest) { auto&& formatErr = FormatterType>::type, M_Type>::format(std::forward(type), *this); SF_TRY(formatErr); - if constexpr (sizeof...(rest) > 0) - { SF_TRY(write_type(std::forward(rest)...)); } + if constexpr (sizeof...(rest) > 0) { + SF_TRY(write_type(std::forward(rest)...)); + } return {}; } }; -} +} // namespace stream::fmt::context -namespace stream::fmt::context -{ +namespace stream::fmt::context { template BasicFormatterExecutor::BasicFormatterExecutor(buf::FMTStreamIO& ostream_, detail::ITextPropertiesExecutor& text_properties_executor_) - : context_executor(text_properties_executor_) - , ostream(ostream_) - { + : context_executor(text_properties_executor_), ostream(ostream_) { text_properties_executor_.link_to_executor(this); } template - [[nodiscard]] std::expected BasicFormatterExecutor::terminate() - { + [[nodiscard]] std::expected BasicFormatterExecutor::terminate() { buf::ManipIO(ostream).compute_generated_size(); // End char not included in buffer manager context to deduce size correctly auto res = buf::ManipIO(ostream).pushback('\0'); - if (EndOfStringChar == EndOfStringCharMode::Forced) - { SF_TRY(res); } + if (EndOfStringChar == EndOfStringCharMode::Forced) { + SF_TRY(res); + } return {}; } template - [[nodiscard]] std::expected BasicFormatterExecutor::exec_settings() - { + [[nodiscard]] std::expected BasicFormatterExecutor::exec_settings() { // indent auto indent = data.specifiers.get("indent"); - if (indent != nullptr) - ostream.indent = indent->as_number; + if (indent != nullptr) ostream.indent = indent->as_number; return {}; } template template - [[nodiscard]] std::expected BasicFormatterExecutor::run_(buf::StreamView format, Args&&... args) - { + [[nodiscard]] std::expected BasicFormatterExecutor::run_(buf::StreamView format, Args&&... args) { auto args_interface = detail::FormatterArgsInterface, Args...>(*this, std::forward(args)...); detail::TextProperties::Properties saveTextProperties = text_manager.save(); - context::BasicContext context(*this, format, args_interface); + context::BasicContext context(*this, format, args_interface); SF_TRY(context.run()); return text_manager.reload(saveTextProperties); } template template - [[nodiscard]] std::expected BasicFormatterExecutor::run(Format&& format_input, Args&&... args) - { + [[nodiscard]] std::expected BasicFormatterExecutor::run(Format&& format_input, Args&&... args) { return run_(buf::StreamView{format_input}, std::forward(args)...); } -} +} // namespace stream::fmt::context #include "format_basics_impl.h" #include "format_text_properties_impl.h" diff --git a/src/stream/fmt/context/formatter_executor/format_basics_impl.h b/src/stream/fmt/context/formatter_executor/format_basics_impl.h index fb85ff9a..55ceb1cd 100644 --- a/src/stream/fmt/context/formatter_executor/format_basics_impl.h +++ b/src/stream/fmt/context/formatter_executor/format_basics_impl.h @@ -4,21 +4,20 @@ #include "stream/fmt/buf/fmt_write_manip.h" -namespace stream::fmt -{ +namespace stream::fmt { //---------------------------------------------// //----------------- Internals -----------------// //---------------------------------------------// template - struct FormatterType, FormatterExecutor> - { - [[nodiscard]] static std::expected format(const typename FormatterExecutor::detail::template FormatSpecifier& specifier, FormatterExecutor& executor) - { - if (specifier.ValueIsText) - { SF_TRY(executor.run("{ '{}', '{}' }", specifier.name, specifier.as_text)); } - else - { SF_TRY(executor.run("{ '{}', '{}' }", specifier.name, specifier.as_number)); } + struct FormatterType, FormatterExecutor> { + [[nodiscard]] static std::expected format(const typename FormatterExecutor::detail::template FormatSpecifier& specifier, + FormatterExecutor& executor) { + if (specifier.ValueIsText) { + SF_TRY(executor.run("{ '{}', '{}' }", specifier.name, specifier.as_text)); + } else { + SF_TRY(executor.run("{ '{}', '{}' }", specifier.name, specifier.as_number)); + } return {}; } }; @@ -27,34 +26,33 @@ namespace stream::fmt //----------------- Forwarders -----------------// //----------------------------------------------// - namespace detail::Forwarders - { + namespace detail::Forwarders { template - [[nodiscard]] std::expected FormatObjectArray(const T* const buffer, std::size_t totalsize, FormatterExecutor& executor) - { + [[nodiscard]] std::expected FormatObjectArray(const T* const buffer, std::size_t totalsize, FormatterExecutor& executor) { std::size_t beginIdx = (std::size_t)executor.data.specifiers.get_as_number("begin", 0); - totalsize = executor.data.specifiers.get_as_number("totalsize", totalsize); - totalsize = executor.data.specifiers.get_as_number("end", totalsize); - + totalsize = executor.data.specifiers.get_as_number("totalsize", totalsize); + totalsize = executor.data.specifiers.get_as_number("end", totalsize); + std::size_t size = executor.data.specifiers.get_as_number("size", totalsize - beginIdx); - if (size == std::numeric_limits::max()) - { return std::unexpected(FMTResult::GivenArgs_UnableToDeduceSize); } + if (size == std::numeric_limits::max()) { + return std::unexpected(FMTResult::GivenArgs_UnableToDeduceSize); + } SF_TRY(buf::WriteManip(executor.ostream).fast_write_string(executor.data.specifiers.get_as_text("begin", STDEnumerableUtility::DefaultBegin))); std::basic_string_view join = executor.data.specifiers.get_as_text("join", STDEnumerableUtility::DefaultJoin); - bool first = true; + bool first = true; const T* itbegin = buffer + beginIdx; - const T* itend = buffer + size + beginIdx; - - while (itbegin < itend) - { - if (first) - { first = false; } - else - { SF_TRY(buf::FMTWriteManip(executor.ostream).write_indent_string(join)); } + const T* itend = buffer + size + beginIdx; + + while (itbegin < itend) { + if (first) { + first = false; + } else { + SF_TRY(buf::FMTWriteManip(executor.ostream).write_indent_string(join)); + } SF_TRY(executor.write_type(*itbegin++)); } @@ -62,37 +60,38 @@ namespace stream::fmt } template - [[nodiscard]] std::expected format_string(const T* buffer, std::size_t size, FormatterExecutor& executor) - { + [[nodiscard]] std::expected format_string(const T* buffer, std::size_t size, FormatterExecutor& executor) { std::size_t beginIdx = (std::size_t)executor.data.specifiers.get_as_number("begin", 0); - size = executor.data.specifiers.get_as_number("size", size); - if (size == std::numeric_limits::max()) - { size = std::basic_string_view(buffer).size(); } + size = executor.data.specifiers.get_as_number("size", size); + if (size == std::numeric_limits::max()) { + size = std::basic_string_view(buffer).size(); + } - if (executor.data.specifiers.has("array")) - return FormatObjectArray(buffer, size, executor); + if (executor.data.specifiers.has("array")) return FormatObjectArray(buffer, size, executor); if (beginIdx > size) return {}; const T* begin = buffer + beginIdx; // TODO: current indent ignore shift - if (executor.data.specifiers.has("indent")) - return buf::FMTWriteManip(executor.ostream).write_indent_char_ptr(begin, size); + if (executor.data.specifiers.has("indent")) return buf::FMTWriteManip(executor.ostream).write_indent_char_ptr(begin, size); - if (executor.data.prefix_suffix) - { SF_TRY(buf::ManipIO(executor.ostream).pushback('\"')); } + if (executor.data.prefix_suffix) { + SF_TRY(buf::ManipIO(executor.ostream).pushback('\"')); + } - if (executor.data.has_spec == false) - { SF_TRY(buf::WriteManip(executor.ostream).fast_write_char_array(begin, size)); } - else - { SF_TRY(buf::FMTWriteManip(executor.ostream).write_char_ptr(begin, size, executor.data.shift)); } + if (executor.data.has_spec == false) { + SF_TRY(buf::WriteManip(executor.ostream).fast_write_char_array(begin, size)); + } else { + SF_TRY(buf::FMTWriteManip(executor.ostream).write_char_ptr(begin, size, executor.data.shift)); + } + + if (executor.data.prefix_suffix) { + SF_TRY(buf::ManipIO(executor.ostream).pushback('\"')); + } - if (executor.data.prefix_suffix) - { SF_TRY(buf::ManipIO(executor.ostream).pushback('\"')); } - return {}; } - } + } // namespace detail::Forwarders //-----------------------------------------------// //----------------- C/CXX Types -----------------// @@ -100,19 +99,14 @@ namespace stream::fmt // Bool template - struct FormatterType - { - [[nodiscard]] static std::expected format(const bool t, FormatterExecutor& executor) - { - if (executor.data.prefix_suffix) - { + struct FormatterType { + [[nodiscard]] static std::expected format(const bool t, FormatterExecutor& executor) { + if (executor.data.prefix_suffix) { if (t == true) return buf::WriteManip(executor.ostream).fast_write_string_literal("True"); else return buf::WriteManip(executor.ostream).fast_write_string_literal("False"); - } - else - { + } else { if (t == true) return buf::ManipIO(executor.ostream).pushback('1'); else @@ -124,27 +118,27 @@ namespace stream::fmt }; template - requires (std::is_integral_v && !std::is_floating_point_v && !detail::IsCharType::value) - struct FormatterType - { - [[nodiscard]] static inline std::expected format(const T t, FormatterExecutor& executor) - { return buf::FMTWriteManip(executor.ostream).write_integer_format_data(t, executor.data); } + requires(std::is_integral_v && !std::is_floating_point_v && !detail::IsCharType::value) + struct FormatterType { + [[nodiscard]] static inline std::expected format(const T t, FormatterExecutor& executor) { + return buf::FMTWriteManip(executor.ostream).write_integer_format_data(t, executor.data); + } }; template - requires std::is_floating_point_v - struct FormatterType - { - [[nodiscard]] static inline std::expected format(const T t, FormatterExecutor& executor) - { return buf::FMTWriteManip(executor.ostream).write_float_formatdata(t, executor.data); } + requires std::is_floating_point_v + struct FormatterType { + [[nodiscard]] static inline std::expected format(const T t, FormatterExecutor& executor) { + return buf::FMTWriteManip(executor.ostream).write_float_formatdata(t, executor.data); + } }; template - requires detail::IsCharType::value - struct FormatterType - { - [[nodiscard]] static inline std::expected format(const T t, FormatterExecutor& executor) - { return buf::ManipIO(executor.ostream).pushback(t); } + requires detail::IsCharType::value + struct FormatterType { + [[nodiscard]] static inline std::expected format(const T t, FormatterExecutor& executor) { + return buf::ManipIO(executor.ostream).pushback(t); + } }; //-------------------------------------------------------// @@ -152,50 +146,43 @@ namespace stream::fmt //-------------------------------------------------------// template - struct FormatterType - { - [[nodiscard]] static inline std::expected format(const void* const t, FormatterExecutor& executor) - { - if (t == nullptr) - return buf::ManipIO(executor.ostream).fast_write_string(executor.data.get_as_text("null", "nullptr")); + struct FormatterType { + [[nodiscard]] static inline std::expected format(const void* const t, FormatterExecutor& executor) { + if (t == nullptr) return buf::ManipIO(executor.ostream).fast_write_string(executor.data.get_as_text("null", "nullptr")); return buf::WriteManip(executor.ostream).fast_write_integer(std::size_t(t)); } }; template - struct FormatterType - { - [[nodiscard]] static inline std::expected format(const T* const t, FormatterExecutor& executor) - { - if (t == nullptr) - { return buf::WriteManip(executor.ostream).fast_write_string(executor.data.specifiers.get_as_text("null", "nullptr")); } - - if constexpr (detail::IsCharType::value) - { return detail::Forwarders::format_string(t, std::numeric_limits::max(), executor); } - else - { detail::Forwarders::FormatObjectArray(t, std::numeric_limits::max(), executor); } + struct FormatterType { + [[nodiscard]] static inline std::expected format(const T* const t, FormatterExecutor& executor) { + if (t == nullptr) { + return buf::WriteManip(executor.ostream).fast_write_string(executor.data.specifiers.get_as_text("null", "nullptr")); + } + + if constexpr (detail::IsCharType::value) { + return detail::Forwarders::format_string(t, std::numeric_limits::max(), executor); + } else { + detail::Forwarders::FormatObjectArray(t, std::numeric_limits::max(), executor); + } return {}; } }; template - struct FormatterType - { - [[nodiscard]] static inline std::expected format(T const (&t)[SIZE], FormatterExecutor& executor) - { - if constexpr (detail::IsCharType::value) - { + struct FormatterType { + [[nodiscard]] static inline std::expected format(T const (&t)[SIZE], FormatterExecutor& executor) { + if constexpr (detail::IsCharType::value) { std::size_t size = SIZE; - while (t[size - 1] == '\0') --size; + while (t[size - 1] == '\0') + --size; return detail::Forwarders::format_string(t, size, executor); - } - else - { + } else { return detail::Forwarders::FormatObjectArray(t, SIZE, executor); } - + return {}; } }; -} +} // namespace stream::fmt diff --git a/src/stream/fmt/context/formatter_executor/format_text_properties_impl.h b/src/stream/fmt/context/formatter_executor/format_text_properties_impl.h index 5e11a337..c7ca38d0 100644 --- a/src/stream/fmt/context/formatter_executor/format_text_properties_impl.h +++ b/src/stream/fmt/context/formatter_executor/format_text_properties_impl.h @@ -2,44 +2,35 @@ #include "basic_formatter_executor.h" -namespace stream::fmt -{ +namespace stream::fmt { //------------------------------------------// //----------------- Resets -----------------// //------------------------------------------// template - struct FormatterType - { - [[nodiscard]] static std::expected format(const detail::TextProperties::ResetProperties, FormatterExecutor& executor) - { + struct FormatterType { + [[nodiscard]] static std::expected format(const detail::TextProperties::ResetProperties, FormatterExecutor& executor) { return executor.text_manager.all_properties_reset(); } }; template - struct FormatterType - { - [[nodiscard]] static std::expected format(const detail::TextProperties::TextColor::reset_color, FormatterExecutor& executor) - { + struct FormatterType { + [[nodiscard]] static std::expected format(const detail::TextProperties::TextColor::reset_color, FormatterExecutor& executor) { return executor.text_manager.apply_color_reset(); } }; template - struct FormatterType - { - [[nodiscard]] static std::expected format(const detail::TextProperties::TextStyle::reset_style, FormatterExecutor& executor) - { + struct FormatterType { + [[nodiscard]] static std::expected format(const detail::TextProperties::TextStyle::reset_style, FormatterExecutor& executor) { return executor.text_manager.apply_style_reset(); } }; template - struct FormatterType - { - [[nodiscard]] static std::expected format(const detail::TextProperties::TextFront::reset_front, FormatterExecutor& executor) - { + struct FormatterType { + [[nodiscard]] static std::expected format(const detail::TextProperties::TextFront::reset_front, FormatterExecutor& executor) { return executor.text_manager.apply_front_reset(); } }; @@ -49,32 +40,26 @@ namespace stream::fmt //---------------------------------------// template - requires detail::text_properties_color_is_apply - struct FormatterType - { - [[nodiscard]] static std::expected format(const T& t, FormatterExecutor& executor) - { + requires detail::text_properties_color_is_apply + struct FormatterType { + [[nodiscard]] static std::expected format(const T& t, FormatterExecutor& executor) { return executor.text_manager.ask_apply_color(t); } }; template - requires detail::TextPropertiesStyleIsapply - struct FormatterType - { - [[nodiscard]] static std::expected format(const T& t, FormatterExecutor& executor) - { + requires detail::TextPropertiesStyleIsapply + struct FormatterType { + [[nodiscard]] static std::expected format(const T& t, FormatterExecutor& executor) { return executor.text_manager.ask_apply_style(t); } }; template - requires detail::TextPropertiesFrontIsapply - struct FormatterType - { - [[nodiscard]] static std::expected format(const T& t, FormatterExecutor& executor) - { + requires detail::TextPropertiesFrontIsapply + struct FormatterType { + [[nodiscard]] static std::expected format(const T& t, FormatterExecutor& executor) { return executor.text_manager.ask_apply_front(t); } }; -} +} // namespace stream::fmt diff --git a/src/stream/fmt/context/formatter_executor/formatter_args.h b/src/stream/fmt/context/formatter_executor/formatter_args.h index e53e13fb..b1a2a472 100644 --- a/src/stream/fmt/context/formatter_executor/formatter_args.h +++ b/src/stream/fmt/context/formatter_executor/formatter_args.h @@ -6,8 +6,7 @@ #include "formatter_type.h" -namespace stream::fmt::detail -{ +namespace stream::fmt::detail { /****************************/ /******** Args tuple ********/ /****************************/ @@ -15,57 +14,50 @@ namespace stream::fmt::detail struct FormatterArgs; template <> - struct FormatterArgs<> - { + struct FormatterArgs<> { public: - static inline constexpr std::size_t size() { return 0; } + static inline constexpr std::size_t size() { + return 0; + } public: template - [[nodiscard]] inline std::expected run_type_at(FormatterExecutor&, std::int32_t) - { + [[nodiscard]] inline std::expected run_type_at(FormatterExecutor&, std::int32_t) { return std::unexpected(FMTResult::ArgsInterface_IndexOutOfBounds); } template - [[nodiscard]] inline std::expected get_index_of_current_named_arg(buf::StreamView&, std::int32_t) - { + [[nodiscard]] inline std::expected get_index_of_current_named_arg(buf::StreamView&, std::int32_t) { return std::unexpected(FMTResult::ArgsInterface_CantMatchNamedArgs); } - [[nodiscard]] inline std::expected get_pointerid_at(std::int32_t) - { + [[nodiscard]] inline std::expected get_pointerid_at(std::int32_t) { return std::unexpected(FMTResult::ArgsInterface_IndexOutOfBounds); } template - [[nodiscard]] inline std::expected get_converted_type_at(std::int32_t) - { + [[nodiscard]] inline std::expected get_converted_type_at(std::int32_t) { return std::unexpected(FMTResult::ArgsInterface_IndexOutOfBounds); } }; template - struct FormatterArgs : public FormatterArgs - { + struct FormatterArgs : public FormatterArgs { private: using TypeWithoutRef = std::remove_reference_t; public: - FormatterArgs(const TypeWithoutRef& t, Rest&&... rest) - : FormatterArgs(std::forward(rest)...) - , m_Value(t) - {} + FormatterArgs(const TypeWithoutRef& t, Rest&&... rest) : FormatterArgs(std::forward(rest)...), m_Value(t) {} private: const TypeWithoutRef& m_Value; public: - static inline constexpr std::size_t size() { return sizeof...(Rest) + 1; } + static inline constexpr std::size_t size() { + return sizeof...(Rest) + 1; + } public: template - [[nodiscard]] inline std::expected run_type_at(Executor& executor, std::int32_t idx) - { - if (idx == 0) - { + [[nodiscard]] inline std::expected run_type_at(Executor& executor, std::int32_t idx) { + if (idx == 0) { return executor.write_type(m_Value); } return FormatterArgs::run_type_at(executor, idx - 1); @@ -73,35 +65,29 @@ namespace stream::fmt::detail public: template - [[nodiscard]] inline std::expected get_index_of_current_named_arg(buf::StreamView& format, std::int32_t begin_search_index) - { - if constexpr (detail::IsANamedArgs>::value) - { + [[nodiscard]] inline std::expected get_index_of_current_named_arg(buf::StreamView& format, std::int32_t begin_search_index) { + if constexpr (detail::IsANamedArgs>::value) { bool current_is_a_named_arg = SF_TRY(buf::FMTParamsManip(format).next_is_named_args(m_Value.get_name())); - if (current_is_a_named_arg) - return begin_search_index; + if (current_is_a_named_arg) return begin_search_index; } return FormatterArgs::get_index_of_current_named_arg(format, begin_search_index + 1); } public: - [[nodiscard]] inline std::expected get_pointerid_at(std::int32_t idx) - { - if (idx == 0) - return PointerID{.type_info = typeid(const TypeWithoutRef), .ptr = const_cast(static_cast(&m_Value))}; + [[nodiscard]] inline std::expected get_pointerid_at(std::int32_t idx) { + if (idx == 0) return PointerID{.type_info = typeid(const TypeWithoutRef), .ptr = const_cast(static_cast(&m_Value))}; return FormatterArgs::get_pointerid_at(idx - 1); } public: template - [[nodiscard]] inline std::expected get_converted_type_at(std::int32_t idx) - { - if (idx == 0) - { - if constexpr (FMTCanContextConvert) - { return FMTContextConvert::convert(m_Value); } - else - { return std::unexpected(FMTResult::ArgsInterface_InvalidConversion); } + [[nodiscard]] inline std::expected get_converted_type_at(std::int32_t idx) { + if (idx == 0) { + if constexpr (FMTCanContextConvert) { + return FMTContextConvert::convert(m_Value); + } else { + return std::unexpected(FMTResult::ArgsInterface_InvalidConversion); + } } return FormatterArgs::template get_converted_type_at(idx - 1); } @@ -112,47 +98,39 @@ namespace stream::fmt::detail /******** Args interface ********/ /********************************/ template - class FormatterArgsInterface : public BasicArgsInterface - { + class FormatterArgsInterface : public BasicArgsInterface { public: using ContextArgsType = FormatterArgs; - + public: - FormatterArgsInterface(FormatterExecutor& executor, Args&&... args) - : BasicArgsInterface() - , executor(executor) - , args_interface(std::forward(args)...) - {} + FormatterArgsInterface(FormatterExecutor& executor, Args&&... args) : BasicArgsInterface(), executor(executor), args_interface(std::forward(args)...) {} ~FormatterArgsInterface() override = default; public: - size_t size() override { return args_interface.size(); } + size_t size() override { + return args_interface.size(); + } - [[nodiscard]] std::expected run_type_at(std::int32_t idx) override - { + [[nodiscard]] std::expected run_type_at(std::int32_t idx) override { return args_interface.run_type_at(executor, idx); } - [[nodiscard]] std::expected get_index_of_current_named_arg(buf::StreamView& format) override - { + [[nodiscard]] std::expected get_index_of_current_named_arg(buf::StreamView& format) override { return args_interface.get_index_of_current_named_arg(format, std::int32_t{0}); } - [[nodiscard]] std::expected get_pointerid_at(std::int32_t idx) override - { - return args_interface.get_pointerid_at(idx); + [[nodiscard]] std::expected get_pointerid_at(std::int32_t idx) override { + return args_interface.get_pointerid_at(idx); } public: - [[nodiscard]] std::expected, FMTResult> get_string_at(std::int32_t idx) override - { + [[nodiscard]] std::expected, FMTResult> get_string_at(std::int32_t idx) override { return args_interface.template get_converted_type_at>(idx); } - [[nodiscard]] std::expected get_int_at(std::int32_t idx) override - { + [[nodiscard]] std::expected get_int_at(std::int32_t idx) override { return args_interface.template get_converted_type_at(idx); } protected: FormatterExecutor& executor; - ContextArgsType args_interface; + ContextArgsType args_interface; }; -} +} // namespace stream::fmt::detail diff --git a/src/stream/fmt/context/formatter_executor/formatter_text_properties_executor/formatter_text_properties_executor.h b/src/stream/fmt/context/formatter_executor/formatter_text_properties_executor/formatter_text_properties_executor.h index d19e6fae..52c52e72 100644 --- a/src/stream/fmt/context/formatter_executor/formatter_text_properties_executor/formatter_text_properties_executor.h +++ b/src/stream/fmt/context/formatter_executor/formatter_text_properties_executor/formatter_text_properties_executor.h @@ -4,31 +4,26 @@ #include "stream/fmt/buf/fmt_manip_io.h" #include "stream/fmt/context/formatter_executor/basic_formatter_executor.h" -namespace stream::fmt::detail -{ +namespace stream::fmt::detail { template - class IFormatterTextPropertiesExecutor : public ITextPropertiesExecutor - { + class IFormatterTextPropertiesExecutor : public ITextPropertiesExecutor { public: ~IFormatterTextPropertiesExecutor() override = default; - void link_to_executor(void* executor) override - { + void link_to_executor(void* executor) override { buffer = &reinterpret_cast*>(executor)->ostream; } protected: buf::FMTStreamIO* buffer{nullptr}; }; -} +} // namespace stream::fmt::detail -namespace stream::fmt::detail -{ +namespace stream::fmt::detail { template - class FormatterNOTextPropertiesExecutor final : public IFormatterTextPropertiesExecutor - { + class FormatterNOTextPropertiesExecutor final : public IFormatterTextPropertiesExecutor { public: - FormatterNOTextPropertiesExecutor() = default; + FormatterNOTextPropertiesExecutor() = default; ~FormatterNOTextPropertiesExecutor() override = default; public: @@ -63,4 +58,4 @@ namespace stream::fmt::detail [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Ideogram&) override {} [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Script&) override {} }; -} +} // namespace stream::fmt::detail diff --git a/src/stream/fmt/context/formatter_executor/formatter_text_properties_executor/formatter_text_properties_executor_ansi.h b/src/stream/fmt/context/formatter_executor/formatter_text_properties_executor/formatter_text_properties_executor_ansi.h index ce2aaeef..f634af5c 100644 --- a/src/stream/fmt/context/formatter_executor/formatter_text_properties_executor/formatter_text_properties_executor_ansi.h +++ b/src/stream/fmt/context/formatter_executor/formatter_text_properties_executor/formatter_text_properties_executor_ansi.h @@ -3,143 +3,119 @@ #include "formatter_text_properties_executor.h" #include "stream/fmt/detail/indent_handlers.h" -namespace stream::fmt::detail -{ +namespace stream::fmt::detail { template - class FormatterTextPropertiesExecutorANSI final : public IFormatterTextPropertiesExecutor - { + class FormatterTextPropertiesExecutorANSI final : public IFormatterTextPropertiesExecutor { public: - FormatterTextPropertiesExecutorANSI() = default; + FormatterTextPropertiesExecutorANSI() = default; ~FormatterTextPropertiesExecutorANSI() override = default; using IFormatterTextPropertiesExecutor::buffer; public: - [[nodiscard]] std::expected all_properties_reset() override - { + [[nodiscard]] std::expected all_properties_reset() override { NoStrideFunction no_stride(*buffer); return buf::WriteManip(*buffer).fast_write_string_literal("\033[0m"); } public: - [[nodiscard]] std::expected reset_color() override - { + [[nodiscard]] std::expected reset_color() override { NoStrideFunction no_stride(*buffer); return buf::WriteManip(*buffer).fast_write_string_literal("\033[39;49m"); } - - [[nodiscard]] std::expected execute_color(const TextProperties::TextColor::BasicColorFG& t) - { + + [[nodiscard]] std::expected execute_color(const TextProperties::TextColor::BasicColorFG& t) { NoStrideFunction no_stride(*buffer); return buf::WriteManip(*buffer).basic_write_type("\033[", static_cast(t), "m"); } - [[nodiscard]] std::expected execute_color(const TextProperties::TextColor::BasicColorBG& t) - { + [[nodiscard]] std::expected execute_color(const TextProperties::TextColor::BasicColorBG& t) { NoStrideFunction no_stride(*buffer); return buf::WriteManip(*buffer).basic_write_type("\033[", static_cast(t), "m"); } - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::BasicColor& t) override - { + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::BasicColor& t) override { NoStrideFunction no_stride(*buffer); return buf::WriteManip(*buffer).basic_write_type("\033[", static_cast(t.fg), ";", static_cast(t.bg), "m"); } - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::Color24bFG& t) override - { + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::Color24bFG& t) override { NoStrideFunction no_stride(*buffer); return buf::WriteManip(*buffer).basic_write_type("\033[38;2;", t.r, ";", t.g, ";", t.b, "m"); } - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::Color24bBG& t) override - { + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::Color24bBG& t) override { NoStrideFunction no_stride(*buffer); return buf::WriteManip(*buffer).basic_write_type("\033[48;2;", t.r, ";", t.g, ";", t.b, "m"); } - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::Color24b& t) override - { + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::Color24b& t) override { NoStrideFunction no_stride(*buffer); return buf::WriteManip(*buffer).basic_write_type("\033[38;2;", t.fg.r, ";", t.fg.g, ";", t.fg.b, "; 48; 2;", t.bg.r, ";", t.bg.g, ";", t.bg.b, "m"); } - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::ColorCubeFG& t) override - { + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::ColorCubeFG& t) override { NoStrideFunction no_stride(*buffer); return buf::WriteManip(*buffer).basic_write_type("\033[38;5;", t.get_color_ref(), "m"); } - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::ColorCubeBG& t) override - { + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::ColorCubeBG& t) override { NoStrideFunction no_stride(*buffer); return buf::WriteManip(*buffer).basic_write_type("\033[48;5;", t.get_color_ref(), "m"); } - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::ColorCube& t) override - { + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::ColorCube& t) override { NoStrideFunction no_stride(*buffer); return buf::WriteManip(*buffer).basic_write_type("\033[48;5;", t.fg.get_color_ref(), ";48;5;", t.bg.get_color_ref(), "m"); } + public: - [[nodiscard]] std::expected reset_front() override - { + [[nodiscard]] std::expected reset_front() override { NoStrideFunction no_stride(*buffer); return buf::WriteManip(*buffer).basic_write_type("\033[", detail::TextProperties::TextFront::FrontID::DefaultFrontID, "m"); } - [[nodiscard]] std::expected execute_front(const detail::TextProperties::TextFront::FrontID& t) override - { + [[nodiscard]] std::expected execute_front(const detail::TextProperties::TextFront::FrontID& t) override { NoStrideFunction no_stride(*buffer); return buf::WriteManip(*buffer).basic_write_type("\033[", t.ID, "m"); } + public: - [[nodiscard]] std::expected reset_style() override - { + [[nodiscard]] std::expected reset_style() override { // TODO NoStrideFunction no_stride(*buffer); return buf::WriteManip(*buffer).fast_write_string_literal("\033[0m"); } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Intensity& t) override - { + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Intensity& t) override { NoStrideFunction no_stride(*buffer); return buf::WriteManip(*buffer).basic_write_type("\033[", static_cast(t), "m"); } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Italic& t) override - { + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Italic& t) override { NoStrideFunction no_stride(*buffer); return buf::WriteManip(*buffer).basic_write_type("\033[", static_cast(t), "m"); } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Underline& t) override - { + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Underline& t) override { NoStrideFunction no_stride(*buffer); return buf::WriteManip(*buffer).basic_write_type("\033[", static_cast(t), "m"); } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::UnderlineColor::Color&) override - { + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::UnderlineColor::Color&) override { NoStrideFunction no_stride(*buffer); return buf::WriteManip(*buffer).basic_write_type("\033[59m"); } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::UnderlineColor::ColorCube& t) override - { + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::UnderlineColor::ColorCube& t) override { NoStrideFunction no_stride(*buffer); return buf::WriteManip(*buffer).basic_write_type("\033[58;5;", t.get_color_ref(), "m"); } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::UnderlineColor::Color24b& t) override - { + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::UnderlineColor::Color24b& t) override { NoStrideFunction no_stride(*buffer); return buf::WriteManip(*buffer).basic_write_type("\033[58;2;", t.r, ";", t.g, ";", t.b, "m"); } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Blink& t) override - { + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Blink& t) override { NoStrideFunction no_stride(*buffer); return buf::WriteManip(*buffer).basic_write_type("\033[", static_cast(t), "m"); } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Inverted& t) override - { + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Inverted& t) override { NoStrideFunction no_stride(*buffer); return buf::WriteManip(*buffer).basic_write_type("\033[", static_cast(t), "m"); } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Ideogram& t) override - { + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Ideogram& t) override { NoStrideFunction no_stride(*buffer); return buf::WriteManip(*buffer).basic_write_type("\033[", static_cast(t), "m"); } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Script& t) override - { + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Script& t) override { NoStrideFunction no_stride(*buffer); return buf::WriteManip(*buffer).basic_write_type("\033[", static_cast(t), "m"); } }; -} +} // namespace stream::fmt::detail diff --git a/src/stream/fmt/context/formatter_executor/formatter_type.h b/src/stream/fmt/context/formatter_executor/formatter_type.h index 7c5dabed..35f15d74 100644 --- a/src/stream/fmt/context/formatter_executor/formatter_type.h +++ b/src/stream/fmt/context/formatter_executor/formatter_type.h @@ -3,13 +3,10 @@ #include "stream/fmt/detail/prelude.h" #define STREAMFORMAT_FORMATTER_DECLARED -namespace stream::fmt -{ +namespace stream::fmt { template - struct FormatterType - { - [[nodiscard]] static std::expected format(const T&, FormatterExecutor& executor) - { + struct FormatterType { + [[nodiscard]] static std::expected format(const T&, FormatterExecutor& executor) { #ifdef UNKOWN_TYPE_MESSAGE executor.run("({C:red}FMT unknow type: {})", typeid(T).name()); #endif @@ -19,21 +16,23 @@ namespace stream::fmt #ifdef UNKOWN_TYPE_DEBUG STREAMFORMAT_DEBUGBREAK(); #endif - return {}; + return {}; } }; -} +} // namespace stream::fmt -#define STREAMFORMAT_AUTO_FORMATTER(Type, formatstr, ...) \ - template \ - struct stream::fmt::FormatterType \ - { \ - [[nodiscard]] static std::expected format(const Type&, FormatterExecutor& executor) { return executor.run(formatstr, __VA_ARGS__); } \ +#define STREAMFORMAT_AUTO_FORMATTER(Type, formatstr, ...) \ + template \ + struct stream::fmt::FormatterType { \ + [[nodiscard]] static std::expected format(const Type&, FormatterExecutor& executor) { \ + return executor.run(formatstr, __VA_ARGS__); \ + } \ }; -#define STREAMFORMAT_AUTO_FORMATTER_T(Type, formatstr, ...) \ - template \ - struct stream::fmt::FormatterType \ - { \ - [[nodiscard]] static std::expected format(const Type&, FormatterExecutor& executor) { return executor.run(formatstr, __VA_ARGS__); } \ +#define STREAMFORMAT_AUTO_FORMATTER_T(Type, formatstr, ...) \ + template \ + struct stream::fmt::FormatterType { \ + [[nodiscard]] static std::expected format(const Type&, FormatterExecutor& executor) { \ + return executor.run(formatstr, __VA_ARGS__); \ + } \ }; diff --git a/src/stream/fmt/context/formatter_executor/index_args.h b/src/stream/fmt/context/formatter_executor/index_args.h index 2f35354c..f3f8a055 100644 --- a/src/stream/fmt/context/formatter_executor/index_args.h +++ b/src/stream/fmt/context/formatter_executor/index_args.h @@ -2,22 +2,21 @@ #include "formatter_type.h" -namespace stream::fmt -{ +namespace stream::fmt { template - struct FCIndexArgs - { + struct FCIndexArgs { public: - FCIndexArgs(const std::uint8_t idx, const T& t) - : m_Value(t) - , idx_(idx) - {} + FCIndexArgs(const std::uint8_t idx, const T& t) : m_Value(t), idx_(idx) {} public: - inline bool IsRightIdx(std::uint8_t idx) const { return idx == idx_; } + inline bool IsRightIdx(std::uint8_t idx) const { + return idx == idx_; + } public: - inline const T& get_value() const { return m_Value; } + inline const T& get_value() const { + return m_Value; + } protected: const T& m_Value; @@ -25,12 +24,10 @@ namespace stream::fmt }; template - struct FormatterType, FormatterExecutor> - { + struct FormatterType, FormatterExecutor> { template - [[nodiscard]] static inline std::expected format(const FCIndexArgs& t, FormatterExecutor& executor) - { + [[nodiscard]] static inline std::expected format(const FCIndexArgs& t, FormatterExecutor& executor) { return executor.write_type(t.get_value()); } }; -} +} // namespace stream::fmt diff --git a/src/stream/fmt/context/formatter_executor/named_args.h b/src/stream/fmt/context/formatter_executor/named_args.h index bc9fed35..7d14d48b 100644 --- a/src/stream/fmt/context/formatter_executor/named_args.h +++ b/src/stream/fmt/context/formatter_executor/named_args.h @@ -2,28 +2,26 @@ #include "formatter_type.h" -namespace stream::fmt -{ +namespace stream::fmt { /////---------- string_view NamedArgs Do not allocate memory (Best) ----------///// template - struct StringViewNamedArgs - { + struct StringViewNamedArgs { public: template - StringViewNamedArgs(const CharName (&name)[SIZE], const T& t) - : name_(name) - , value(t) - {} + StringViewNamedArgs(const CharName (&name)[SIZE], const T& t) : name_(name), value(t) {} - StringViewNamedArgs(std::basic_string_view name, const T& t) - : name_(name) - , value(t) - {} + StringViewNamedArgs(std::basic_string_view name, const T& t) : name_(name), value(t) {} public: - T& get_value() { return value; } - const T& get_value() const { return value; } - std::basic_string_view get_name() const { return name_; } + T& get_value() { + return value; + } + const T& get_value() const { + return value; + } + std::basic_string_view get_name() const { + return name_; + } protected: std::basic_string_view name_; @@ -31,33 +29,30 @@ namespace stream::fmt }; template - struct FormatterType, FormatterExecutor> - { - [[nodiscard]] static inline std::expected format(const StringViewNamedArgs& t, FormatterExecutor& executor) - { + struct FormatterType, FormatterExecutor> { + [[nodiscard]] static inline std::expected format(const StringViewNamedArgs& t, FormatterExecutor& executor) { return executor.write_type(t.get_value()); } }; /////---------- stringNamedArgs Allocate memory (Only if necessary) ----------///// template - struct StringNamedArgs - { + struct StringNamedArgs { public: - StringNamedArgs(const std::string& str, const T& t) - : name_(str) - , value(t) - {} + StringNamedArgs(const std::string& str, const T& t) : name_(str), value(t) {} - StringNamedArgs(std::string&& str, const T& t) - : name_(std::move(str)) - , value(t) - {} + StringNamedArgs(std::string&& str, const T& t) : name_(std::move(str)), value(t) {} public: - T& get_value() { return value; } - const T& get_value() const { return value; } - std::basic_string_view get_name() const { return name_; } + T& get_value() { + return value; + } + const T& get_value() const { + return value; + } + std::basic_string_view get_name() const { + return name_; + } protected: std::basic_string name_; @@ -65,32 +60,26 @@ namespace stream::fmt }; template - struct FormatterType, FormatterExecutor> - { - [[nodiscard]] static inline std::expected format(const StringNamedArgs& t, FormatterExecutor& executor) - { + struct FormatterType, FormatterExecutor> { + [[nodiscard]] static inline std::expected format(const StringNamedArgs& t, FormatterExecutor& executor) { return executor.write_type(t.get_value()); } }; - namespace detail - { + namespace detail { template - struct IsANamedArgs - { + struct IsANamedArgs { public: [[maybe_unused]] inline constexpr static bool value = false; }; template - struct IsANamedArgs> - { + struct IsANamedArgs> { [[maybe_unused]] inline constexpr static bool value = true; }; template - struct IsANamedArgs> - { + struct IsANamedArgs> { [[maybe_unused]] inline constexpr static bool value = true; }; @@ -102,9 +91,9 @@ namespace stream::fmt template inline constexpr bool IsANamedArgsValue> = true; - } -} + } // namespace detail +} // namespace stream::fmt -#define FORMAT(value) stream::fmt::StringViewNamedArgs(#value, value) -#define FORMAT_SV(name, value) stream::fmt::StringViewNamedArgs(name, value) +#define FORMAT(value) stream::fmt::StringViewNamedArgs(#value, value) +#define FORMAT_SV(name, value) stream::fmt::StringViewNamedArgs(name, value) #define FORMAT_STR(name, value) stream::fmt::StringNamedArgs(name, value) diff --git a/src/stream/fmt/context/formatter_executor/std_enumerable.h b/src/stream/fmt/context/formatter_executor/std_enumerable.h index 7f4f6df7..ec66e9da 100644 --- a/src/stream/fmt/context/formatter_executor/std_enumerable.h +++ b/src/stream/fmt/context/formatter_executor/std_enumerable.h @@ -7,10 +7,8 @@ #include #include -namespace stream::fmt -{ - class STDEnumerableUtility - { +namespace stream::fmt { + class STDEnumerableUtility { public: static constexpr std::string_view DefaultJoin = ", "; static constexpr std::string_view DefaultBegin = "{ "; @@ -18,28 +16,32 @@ namespace stream::fmt }; template - class STDEnumerable - { + class STDEnumerable { public: explicit inline STDEnumerable(const T& value, std::basic_string_view strJoin = ", ", std::basic_string_view strBegin = "{ ", - std::basic_string_view strEnd = " }", const std::int32_t beginIdx = 0, - const std::int32_t size = -1) - : m_Value(value) - , m_StrJoin(strJoin) - , m_StrBegin(strBegin) - , m_StrEnd(strEnd) - , m_BeginIdx(beginIdx) - , m_Size(size < 0 ? (std::int32_t)value.size() - beginIdx : size) - {} + std::basic_string_view strEnd = " }", const std::int32_t beginIdx = 0, const std::int32_t size = -1) + : m_Value(value), m_StrJoin(strJoin), m_StrBegin(strBegin), m_StrEnd(strEnd), m_BeginIdx(beginIdx), m_Size(size < 0 ? (std::int32_t)value.size() - beginIdx : size) {} - inline const T& get_value() const { return m_Value; } + inline const T& get_value() const { + return m_Value; + } - inline std::basic_string_view get_str_join() const { return m_StrJoin; } - inline std::basic_string_view get_str_begin() const { return m_StrBegin; } - inline std::basic_string_view get_str_end() const { return m_StrEnd; } + inline std::basic_string_view get_str_join() const { + return m_StrJoin; + } + inline std::basic_string_view get_str_begin() const { + return m_StrBegin; + } + inline std::basic_string_view get_str_end() const { + return m_StrEnd; + } - inline std::int32_t get_begin_idx() const { return m_BeginIdx; } - inline std::int32_t get_size() const { return m_Size; } + inline std::int32_t get_begin_idx() const { + return m_BeginIdx; + } + inline std::int32_t get_size() const { + return m_Size; + } private: const T& m_Value; @@ -53,10 +55,8 @@ namespace stream::fmt }; template - struct FormatterType, FormatterExecutor> - { - [[nodiscard]] static std::expected format(const STDEnumerable& enumerable, FormatterExecutor& executor) - { + struct FormatterType, FormatterExecutor> { + [[nodiscard]] static std::expected format(const STDEnumerable& enumerable, FormatterExecutor& executor) { SF_TRY(executor.ostream.write_indent_string_view(enumerable.get_str_begin())); SF_TRY(executor.ostream.add_indent(enumerable.get_str_begin().size())); @@ -66,10 +66,11 @@ namespace stream::fmt bool first = true; std::for_each_n(enumerable.get_value().cbegin() + enumerable.get_begin_idx(), enumerable.get_size(), [&](const auto& element) { - if (first) - { first = false; } - else - { SF_TRY(executor.ostream.write_indent_string_view(enumerable.get_str_join())); } + if (first) { + first = false; + } else { + SF_TRY(executor.ostream.write_indent_string_view(enumerable.get_str_join())); + } SF_TRY(executor.write_type(element)); }); @@ -81,23 +82,17 @@ namespace stream::fmt }; template - struct ForwardAsSTDEnumerable - { - }; + struct ForwardAsSTDEnumerable {}; template - struct FormatterType, FormatterExecutor> - { - [[nodiscard]] static inline std::expected format(const T& container, FormatterExecutor& executor) - { + struct FormatterType, FormatterExecutor> { + [[nodiscard]] static inline std::expected format(const T& container, FormatterExecutor& executor) { STDEnumerable enumerable(container, executor.data.get_as_text("join", STDEnumerableUtility::DefaultJoin), - executor.data.get_as_text("begin", STDEnumerableUtility::DefaultBegin), - executor.data.get_as_text("end", STDEnumerableUtility::DefaultEnd), - executor.data.get_as_number("begin", 0), - executor.data.get_as_number("size", -1)); + executor.data.get_as_text("begin", STDEnumerableUtility::DefaultBegin), executor.data.get_as_text("end", STDEnumerableUtility::DefaultEnd), + executor.data.get_as_number("begin", 0), executor.data.get_as_number("size", -1)); return executor.write_type(enumerable); } }; -} +} // namespace stream::fmt diff --git a/src/stream/fmt/context/formatter_executor/utility_functions.h b/src/stream/fmt/context/formatter_executor/utility_functions.h index c1deff94..a4e77a9b 100644 --- a/src/stream/fmt/context/formatter_executor/utility_functions.h +++ b/src/stream/fmt/context/formatter_executor/utility_functions.h @@ -10,65 +10,54 @@ #include -namespace stream::fmt -{ +namespace stream::fmt { /////---------- Impl with as Format ----------////// - namespace detail - { + namespace detail { template - requires(IsCharType::value) - [[nodiscard]] std::expected format_in_manager( - buf::BasicStreamIOManager& ostream_manager, - bool newline, - buf::StreamView format, - Args&&... args - ) - { + requires(IsCharType::value) + [[nodiscard]] std::expected format_in_manager(buf::BasicStreamIOManager& ostream_manager, bool newline, buf::StreamView format, + Args&&... args) { using TCharResolved = std::remove_const_t; detail::FormatterTextPropertiesExecutorANSI text_properties_executor; - buf::FMTStreamIO ostream = SF_TRY(buf::FMTStreamIO::create(ostream_manager)); - context::BasicFormatterExecutor executor(ostream, text_properties_executor); + buf::FMTStreamIO ostream = SF_TRY(buf::FMTStreamIO::create(ostream_manager)); + context::BasicFormatterExecutor executor(ostream, text_properties_executor); SF_TRY(executor.run(format, std::forward(args)...)); if (newline) SF_TRY(buf::ManipIO(ostream).pushback('\n')); return executor.terminate(); } template - requires(IsCharType::value) - [[nodiscard]] std::expected format_in_manager(buf::BasicStreamIOManager& ostream_manager, bool newline, T&& t) - { + requires(IsCharType::value) + [[nodiscard]] std::expected format_in_manager(buf::BasicStreamIOManager& ostream_manager, bool newline, T&& t) { using TCharResolved = std::remove_const_t; detail::FormatterTextPropertiesExecutorANSI text_properties_executor; - buf::FMTStreamIO ostream = SF_TRY(buf::FMTStreamIO::create(ostream_manager)); - context::BasicFormatterExecutor executor(ostream, text_properties_executor); + buf::FMTStreamIO ostream = SF_TRY(buf::FMTStreamIO::create(ostream_manager)); + context::BasicFormatterExecutor executor(ostream, text_properties_executor); SF_TRY(executor.write_type(std::forward(t))); if (newline) SF_TRY(buf::ManipIO(ostream).pushback('\n')); return executor.terminate(); } - } + } // namespace detail template - requires(detail::IsCharType::value && buf::convertible_to_buffer_info_view) - [[nodiscard]] std::expected format_in_char(TChar (&buffer)[BUFFER_SIZE], Format&& format_input, Args&&... args) - { + requires(detail::IsCharType::value && buf::convertible_to_buffer_info_view) + [[nodiscard]] std::expected format_in_char(TChar (&buffer)[BUFFER_SIZE], Format&& format_input, Args&&... args) { buf::GivenStreamIOManager ostream_manager(buffer); return detail::format_in_manager(ostream_manager, false, buf::StreamView{format_input}, std::forward(args)...); } template - requires(detail::IsCharType::value && buf::convertible_to_buffer_info_view) - [[nodiscard]] std::expected format_in_char(TChar* const buffer, const std::size_t buffer_size, Format&& format_input, Args&&... args) - { + requires(detail::IsCharType::value && buf::convertible_to_buffer_info_view) + [[nodiscard]] std::expected format_in_char(TChar* const buffer, const std::size_t buffer_size, Format&& format_input, Args&&... args) { buf::GivenStreamIOManager ostream_manager(buffer, buffer_size); return detail::format_in_manager(ostream_manager, false, buf::StreamView{format_input}, std::forward(args)...); } template - requires(detail::IsCharType::value && buf::convertible_to_buffer_info_view) - [[nodiscard]] std::expected cfile_print(FILE* stream, Format&& format_input, Args&&... args) - { + requires(detail::IsCharType::value && buf::convertible_to_buffer_info_view) + [[nodiscard]] std::expected cfile_print(FILE* stream, Format&& format_input, Args&&... args) { buf::DynamicStreamIOManager ostream_manager(256); SF_TRY(detail::format_in_manager(ostream_manager, false, buf::StreamView{format_input}, std::forward(args)...)); @@ -78,9 +67,8 @@ namespace stream::fmt } template - requires(detail::IsCharType::value && buf::convertible_to_buffer_info_view) - [[nodiscard]] std::expected cfile_println(FILE* stream, Format&& format_input, Args&&... args) - { + requires(detail::IsCharType::value && buf::convertible_to_buffer_info_view) + [[nodiscard]] std::expected cfile_println(FILE* stream, Format&& format_input, Args&&... args) { buf::DynamicStreamIOManager ostream_manager(256); SF_TRY(detail::format_in_manager(ostream_manager, true, buf::StreamView{format_input}, std::forward(args)...)); @@ -90,9 +78,8 @@ namespace stream::fmt } template - requires(detail::IsCharType::value && buf::convertible_to_buffer_info_view) - [[nodiscard]] std::expected file_print(std::basic_ostream& stream, Format&& format_input, Args&&... args) - { + requires(detail::IsCharType::value && buf::convertible_to_buffer_info_view) + [[nodiscard]] std::expected file_print(std::basic_ostream& stream, Format&& format_input, Args&&... args) { buf::DynamicStreamIOManager ostream_manager(256); SF_TRY(detail::format_in_manager(ostream_manager, false, buf::StreamView{format_input}, std::forward(args)...)); @@ -102,9 +89,8 @@ namespace stream::fmt } template - requires(detail::IsCharType::value && buf::convertible_to_buffer_info_view) - [[nodiscard]] std::expected file_println(std::basic_ostream& stream, Format&& format_input, Args&&... args) - { + requires(detail::IsCharType::value && buf::convertible_to_buffer_info_view) + [[nodiscard]] std::expected file_println(std::basic_ostream& stream, Format&& format_input, Args&&... args) { buf::DynamicStreamIOManager ostream_manager(256); SF_TRY(detail::format_in_manager(ostream_manager, true, buf::StreamView{format_input}, std::forward(args)...)); @@ -114,9 +100,8 @@ namespace stream::fmt } template - requires(detail::IsCharType::value && buf::convertible_to_buffer_info_view) - [[nodiscard]] std::expected format_in_string(std::basic_string& str, Format&& format_input, Args&&... args) - { + requires(detail::IsCharType::value && buf::convertible_to_buffer_info_view) + [[nodiscard]] std::expected format_in_string(std::basic_string& str, Format&& format_input, Args&&... args) { buf::DynamicStreamIOManager ostream_manager(256); SF_TRY(detail::format_in_manager(ostream_manager, false, buf::StreamView{format_input}, std::forward(args)...)); str = ostream_manager.get_last_generated_string_view(); @@ -124,9 +109,8 @@ namespace stream::fmt } template - requires(detail::IsCharType::value && buf::convertible_to_buffer_info_view) - [[nodiscard]] inline std::expected, FMTResult> format_string(Format&& format_input, Args&&... args) - { + requires(detail::IsCharType::value && buf::convertible_to_buffer_info_view) + [[nodiscard]] inline std::expected, FMTResult> format_string(Format&& format_input, Args&&... args) { buf::DynamicStreamIOManager ostream_manager(256); SF_TRY(detail::format_in_manager(ostream_manager, false, buf::StreamView{format_input}, std::forward(args)...)); return std::basic_string{ostream_manager.get_last_generated_string_view()}; @@ -135,25 +119,22 @@ namespace stream::fmt /////---------- NO-FORMAT Impl except for string which are formatted to avoid {} ----------////// template - requires(detail::IsCharType::value) - [[nodiscard]] std::expected format_in_char(TChar (&buffer)[BUFFER_SIZE], T&& t) - { + requires(detail::IsCharType::value) + [[nodiscard]] std::expected format_in_char(TChar (&buffer)[BUFFER_SIZE], T&& t) { buf::GivenStreamIOManager ostream_manager(buffer, BUFFER_SIZE); return detail::format_in_manager(ostream_manager, false, std::forward(t)); } template - requires(detail::IsCharType::value) - [[nodiscard]] std::expected format_in_char(TChar* const buffer, const std::size_t buffer_size, T&& t) - { + requires(detail::IsCharType::value) + [[nodiscard]] std::expected format_in_char(TChar* const buffer, const std::size_t buffer_size, T&& t) { buf::GivenStreamIOManager ostream_manager(buffer, buffer_size); return detail::format_in_manager(ostream_manager, false, std::forward(t)); } template - requires(detail::IsCharType::value) - [[nodiscard]] std::expected cfile_print(FILE* stream, T&& t) - { + requires(detail::IsCharType::value) + [[nodiscard]] std::expected cfile_print(FILE* stream, T&& t) { buf::DynamicStreamIOManager ostream_manager(32); SF_TRY(detail::format_in_manager(ostream_manager, false, std::forward(t))); @@ -163,9 +144,8 @@ namespace stream::fmt } template - requires(detail::IsCharType::value) - [[nodiscard]] std::expected cfile_println(FILE* stream, T&& t) - { + requires(detail::IsCharType::value) + [[nodiscard]] std::expected cfile_println(FILE* stream, T&& t) { buf::DynamicStreamIOManager ostream_manager(32); SF_TRY(detail::format_in_manager(ostream_manager, true, std::forward(t))); @@ -175,9 +155,8 @@ namespace stream::fmt } template - requires(detail::IsCharType::value) - [[nodiscard]] std::expected file_print(std::basic_ostream& stream, T&& t) - { + requires(detail::IsCharType::value) + [[nodiscard]] std::expected file_print(std::basic_ostream& stream, T&& t) { buf::DynamicStreamIOManager ostream_manager(32); SF_TRY(detail::format_in_manager(ostream_manager, false, std::forward(t))); @@ -187,9 +166,8 @@ namespace stream::fmt } template - requires(detail::IsCharType::value) - [[nodiscard]] std::expected file_println(std::basic_ostream& stream, T&& t) - { + requires(detail::IsCharType::value) + [[nodiscard]] std::expected file_println(std::basic_ostream& stream, T&& t) { buf::DynamicStreamIOManager ostream_manager(32); SF_TRY(detail::format_in_manager(ostream_manager, true, std::forward(t))); @@ -199,9 +177,8 @@ namespace stream::fmt } template - requires(detail::IsCharType::value) - [[nodiscard]] std::expected format_in_string(std::basic_string& str, T&& t) - { + requires(detail::IsCharType::value) + [[nodiscard]] std::expected format_in_string(std::basic_string& str, T&& t) { buf::DynamicStreamIOManager ostream_manager(32); SF_TRY(detail::format_in_manager(ostream_manager, false, std::forward(t))); str = ostream_manager.get_last_generated_string_view(); @@ -209,24 +186,19 @@ namespace stream::fmt } template - requires(detail::IsCharType::value) - [[nodiscard]] inline std::expected, FMTResult> format_string(T&& t) - { + requires(detail::IsCharType::value) + [[nodiscard]] inline std::expected, FMTResult> format_string(T&& t) { buf::DynamicStreamIOManager ostream_manager(32); SF_TRY(detail::format_in_manager(ostream_manager, false, std::forward(t))); return std::string{ostream_manager.get_last_generated_string_view()}; } -} +} // namespace stream::fmt -namespace stream::fmt -{ +namespace stream::fmt { template - struct FormatterType - { - [[nodiscard]] static std::expected format(FMTResult result, FormatterExecutor& executor) - { - switch(result) - { + struct FormatterType { + [[nodiscard]] static std::expected format(FMTResult result, FormatterExecutor& executor) { + switch (result) { case FMTResult::FunctionNotImpl: return buf::WriteManip(executor.ostream).fast_write_string_literal("FunctionNotImpl"); case FMTResult::Buffer_NonValid: @@ -272,4 +244,4 @@ namespace stream::fmt } } }; -} +} // namespace stream::fmt diff --git a/src/stream/fmt/context/parser_executor/basic_parser_executor.h b/src/stream/fmt/context/parser_executor/basic_parser_executor.h index c07527a9..3e71acdf 100644 --- a/src/stream/fmt/context/parser_executor/basic_parser_executor.h +++ b/src/stream/fmt/context/parser_executor/basic_parser_executor.h @@ -12,13 +12,12 @@ #include "parser_text_properties_executor/parser_text_properties_executor.h" -namespace stream::fmt::context -{ +namespace stream::fmt::context { template - class BasicParserExecutor : public context_executor - { + class BasicParserExecutor : public context_executor { public: using TChar = CharType; + private: using M_Type = BasicParserExecutor; @@ -35,12 +34,13 @@ namespace stream::fmt::context using context_executor::text_manager; protected: - [[nodiscard]] std::expected exec_raw_string(std::basic_string_view sv) override - { + [[nodiscard]] std::expected exec_raw_string(std::basic_string_view sv) override { SF_TRY(buf::TestManip(istream).is_same_forward(sv.data(), sv.size())); return {}; } - [[nodiscard]] std::expected exec_settings() override { return {}; }; + [[nodiscard]] std::expected exec_settings() override { + return {}; + }; public: template @@ -50,52 +50,44 @@ namespace stream::fmt::context public: template - [[nodiscard]] inline std::expected read_type(Type& type, Rest&... rest) - { + [[nodiscard]] inline std::expected read_type(Type& type, Rest&... rest) { auto&& parseErr = ParserType>::type, M_Type>::parse(type, *this); SF_TRY(parseErr); - if constexpr (sizeof...(rest) > 0) - SF_TRY(read_type(std::forward(rest)...)); + if constexpr (sizeof...(rest) > 0) SF_TRY(read_type(std::forward(rest)...)); return {}; } }; -} +} // namespace stream::fmt::context -namespace stream::fmt::context -{ +namespace stream::fmt::context { template BasicParserExecutor::BasicParserExecutor(buf::StreamView& istream_, detail::ITextPropertiesExecutor& text_properties_executor_) - : context_executor(text_properties_executor_) - , istream{istream_} - { + : context_executor(text_properties_executor_), istream{istream_} { text_properties_executor_.link_to_executor(this); } template - [[nodiscard]] std::expected BasicParserExecutor::terminate() - { + [[nodiscard]] std::expected BasicParserExecutor::terminate() { return {}; } template template - [[nodiscard]] std::expected BasicParserExecutor::run_(buf::StreamView format, Args&&... args) - { + [[nodiscard]] std::expected BasicParserExecutor::run_(buf::StreamView format, Args&&... args) { auto args_interface = detail::ParserArgsInterface, Args...>(*this, std::forward(args)...); detail::TextProperties::Properties saveTextProperties = text_manager.save(); - context::BasicContext context(*this, format, args_interface); + context::BasicContext context(*this, format, args_interface); SF_TRY(context.run()); return text_manager.reload(saveTextProperties); } template template - [[nodiscard]] std::expected BasicParserExecutor::run(Format&& format_input, Args&&... args) - { + [[nodiscard]] std::expected BasicParserExecutor::run(Format&& format_input, Args&&... args) { return run_(buf::StreamView{format_input}, std::forward(args)...); } -} +} // namespace stream::fmt::context #include "parse_basics_impl.h" #include "parse_text_properties_impl.h" diff --git a/src/stream/fmt/context/parser_executor/parse_basics_impl.h b/src/stream/fmt/context/parser_executor/parse_basics_impl.h index 896426af..eeb7a7f9 100644 --- a/src/stream/fmt/context/parser_executor/parse_basics_impl.h +++ b/src/stream/fmt/context/parser_executor/parse_basics_impl.h @@ -3,8 +3,7 @@ #include "basic_parser_executor.h" #include "stream/fmt/buf/fmt_read_manip.h" -namespace stream::fmt -{ +namespace stream::fmt { //----------------------------------------------// //----------------- Forwarders -----------------// //----------------------------------------------// @@ -14,40 +13,27 @@ namespace stream::fmt //-----------------------------------------------// template - struct ParserType - { - [[nodiscard]] static std::expected parse(bool& t, ParserExecutor& executor) - { - if (!executor.data.prefix_suffix) - { - if (buf::TestAccess(executor.istream).is_equal_to('t', 'T')) - { + struct ParserType { + [[nodiscard]] static std::expected parse(bool& t, ParserExecutor& executor) { + if (!executor.data.prefix_suffix) { + if (buf::TestAccess(executor.istream).is_equal_to('t', 'T')) { SF_TRY(buf::Manip(executor.istream).forward()); - if (buf::TestAccess(executor.istream).is_same("rue")) - { + if (buf::TestAccess(executor.istream).is_same("rue")) { SF_TRY(buf::Manip(executor.istream).forward()); t = true; } - } - else if (buf::TestAccess(executor.istream).is_equal_to('f', 'F')) - { + } else if (buf::TestAccess(executor.istream).is_equal_to('f', 'F')) { SF_TRY(buf::Manip(executor.istream).forward()); - if (buf::TestAccess(executor.istream).is_same("alse")) - { + if (buf::TestAccess(executor.istream).is_same("alse")) { SF_TRY(buf::Manip(executor.istream).forward()); t = false; } } - } - else - { - if (buf::TestAccess(executor.istream).is_equal_to('1')) - { + } else { + if (buf::TestAccess(executor.istream).is_equal_to('1')) { SF_TRY(buf::Manip(executor.istream).forward()); t = true; - } - else if (buf::TestAccess(executor.istream).is_equal_to('0')) - { + } else if (buf::TestAccess(executor.istream).is_equal_to('0')) { SF_TRY(buf::Manip(executor.istream).forward()); t = false; } @@ -57,19 +43,19 @@ namespace stream::fmt }; template - requires (std::is_integral_v && !std::is_floating_point_v && !detail::IsCharType::value) - struct ParserType - { - [[nodiscard]] static inline std::expected parse(T& t, ParserExecutor& executor) - { return buf::FMTReadManip(executor.istream).read_integer_format_data(t, executor.data); } + requires(std::is_integral_v && !std::is_floating_point_v && !detail::IsCharType::value) + struct ParserType { + [[nodiscard]] static inline std::expected parse(T& t, ParserExecutor& executor) { + return buf::FMTReadManip(executor.istream).read_integer_format_data(t, executor.data); + } }; template - requires std::is_floating_point_v - struct ParserType - { - [[nodiscard]] static inline std::expected parse(T& t, ParserExecutor& executor) - { return buf::FMTReadManip(executor.istream).read_float_format_data(t, executor.data); } + requires std::is_floating_point_v + struct ParserType { + [[nodiscard]] static inline std::expected parse(T& t, ParserExecutor& executor) { + return buf::FMTReadManip(executor.istream).read_float_format_data(t, executor.data); + } }; //-------------------------------------------------------// @@ -77,10 +63,8 @@ namespace stream::fmt //-------------------------------------------------------// template - struct ParserType - { - [[nodiscard]] static inline std::expected parse(void*&, ParserExecutor&) - { + struct ParserType { + [[nodiscard]] static inline std::expected parse(void*&, ParserExecutor&) { // FIXME // TODO return std::unexpected(FMTResult::FunctionNotImpl); @@ -88,10 +72,8 @@ namespace stream::fmt }; template - struct ParserType - { - [[nodiscard]] static inline std::expected parse(T*&, ParserExecutor&) - { + struct ParserType { + [[nodiscard]] static inline std::expected parse(T*&, ParserExecutor&) { // FIXME // TODO return std::unexpected(FMTResult::FunctionNotImpl); @@ -99,13 +81,11 @@ namespace stream::fmt }; template - struct ParserType - { - [[nodiscard]] static inline std::expected parse(T (&)[SIZE], ParserExecutor&) - { + struct ParserType { + [[nodiscard]] static inline std::expected parse(T (&)[SIZE], ParserExecutor&) { // FIXME // TODO return std::unexpected(FMTResult::FunctionNotImpl); } }; -} +} // namespace stream::fmt diff --git a/src/stream/fmt/context/parser_executor/parse_text_properties_impl.h b/src/stream/fmt/context/parser_executor/parse_text_properties_impl.h index 48c51875..867e77b5 100644 --- a/src/stream/fmt/context/parser_executor/parse_text_properties_impl.h +++ b/src/stream/fmt/context/parser_executor/parse_text_properties_impl.h @@ -2,44 +2,35 @@ #include "basic_parser_executor.h" -namespace stream::fmt -{ +namespace stream::fmt { //------------------------------------------// //----------------- Resets -----------------// //------------------------------------------// template - struct ParserType - { - [[nodiscard]] static inline std::expected parse(detail::TextProperties::ResetProperties, ParserExecutor& executor) - { + struct ParserType { + [[nodiscard]] static inline std::expected parse(detail::TextProperties::ResetProperties, ParserExecutor& executor) { return executor.text_manager.all_properties_reset(); } }; template - struct ParserType - { - [[nodiscard]] static inline std::expected parse(detail::TextProperties::TextColor::reset_color, ParserExecutor& executor) - { + struct ParserType { + [[nodiscard]] static inline std::expected parse(detail::TextProperties::TextColor::reset_color, ParserExecutor& executor) { return executor.text_manager.apply_color_reset(); } }; template - struct ParserType - { - [[nodiscard]] static inline std::expected parse(detail::TextProperties::TextStyle::reset_style, ParserExecutor& executor) - { + struct ParserType { + [[nodiscard]] static inline std::expected parse(detail::TextProperties::TextStyle::reset_style, ParserExecutor& executor) { return executor.text_manager.apply_style_reset(); } }; template - struct ParserType - { - [[nodiscard]] static inline std::expected parse(detail::TextProperties::TextFront::reset_front, ParserExecutor& executor) - { + struct ParserType { + [[nodiscard]] static inline std::expected parse(detail::TextProperties::TextFront::reset_front, ParserExecutor& executor) { return executor.text_manager.apply_front_reset(); } }; @@ -49,32 +40,26 @@ namespace stream::fmt //---------------------------------------// template - requires detail::text_properties_color_is_apply - struct ParserType - { - [[nodiscard]] static inline std::expected parse(T& t, ParserExecutor& executor) - { + requires detail::text_properties_color_is_apply + struct ParserType { + [[nodiscard]] static inline std::expected parse(T& t, ParserExecutor& executor) { return executor.text_manager.ask_apply_color(t); } }; template - requires detail::TextPropertiesStyleIsapply - struct ParserType - { - [[nodiscard]] static inline std::expected parse(T& t, ParserExecutor& executor) - { + requires detail::TextPropertiesStyleIsapply + struct ParserType { + [[nodiscard]] static inline std::expected parse(T& t, ParserExecutor& executor) { return executor.text_manager.ask_apply_style(t); } }; template - requires detail::TextPropertiesFrontIsapply - struct ParserType - { - [[nodiscard]] static inline std::expected parse(T& t, ParserExecutor& executor) - { + requires detail::TextPropertiesFrontIsapply + struct ParserType { + [[nodiscard]] static inline std::expected parse(T& t, ParserExecutor& executor) { return executor.text_manager.ask_apply_front(t); } }; -} +} // namespace stream::fmt diff --git a/src/stream/fmt/context/parser_executor/parser_args.h b/src/stream/fmt/context/parser_executor/parser_args.h index af68175e..ff97329b 100644 --- a/src/stream/fmt/context/parser_executor/parser_args.h +++ b/src/stream/fmt/context/parser_executor/parser_args.h @@ -3,8 +3,7 @@ #include "stream/fmt/context/basic_context/basic_args_interface.h" #include "stream/fmt/detail/prelude.h" -namespace stream::fmt::detail -{ +namespace stream::fmt::detail { /****************************/ /******** Args tuple ********/ /****************************/ @@ -12,60 +11,53 @@ namespace stream::fmt::detail struct ParserArgs; template <> - struct ParserArgs<> - { + struct ParserArgs<> { public: ParserArgs() = default; public: - static inline constexpr std::size_t size() { return 0; } + static inline constexpr std::size_t size() { + return 0; + } public: template - [[nodiscard]] inline std::expected run_type_at(FormatterExecutor&, std::int32_t) - { + [[nodiscard]] inline std::expected run_type_at(FormatterExecutor&, std::int32_t) { return std::unexpected(FMTResult::ArgsInterface_IndexOutOfBounds); } template - [[nodiscard]] inline std::expected get_index_of_current_named_arg(buf::StreamView& format, std::int32_t) - { + [[nodiscard]] inline std::expected get_index_of_current_named_arg(buf::StreamView& format, std::int32_t) { return std::unexpected(FMTResult::ArgsInterface_CantMatchNamedArgs); } - [[nodiscard]] inline std::expected get_pointerid_at(std::int32_t) - { + [[nodiscard]] inline std::expected get_pointerid_at(std::int32_t) { return std::unexpected(FMTResult::ArgsInterface_IndexOutOfBounds); } template - [[nodiscard]] inline std::expected get_converted_type_at(std::int32_t) - { + [[nodiscard]] inline std::expected get_converted_type_at(std::int32_t) { return std::unexpected(FMTResult::ArgsInterface_IndexOutOfBounds); } }; template - struct ParserArgs : ParserArgs - { + struct ParserArgs : ParserArgs { private: using TypeWithoutRef = std::remove_reference_t; public: - ParserArgs(TypeWithoutRef& t, Rest&... rest) - : ParserArgs(std::forward(rest)...) - , m_Value(t) - {} + ParserArgs(TypeWithoutRef& t, Rest&... rest) : ParserArgs(std::forward(rest)...), m_Value(t) {} private: TypeWithoutRef& m_Value; public: - static inline constexpr std::size_t size() { return sizeof...(Rest) + 1; } + static inline constexpr std::size_t size() { + return sizeof...(Rest) + 1; + } public: template - [[nodiscard]] inline std::expected run_type_at(Executor& executor, std::int32_t idx) - { - if (idx == 0) - { + [[nodiscard]] inline std::expected run_type_at(Executor& executor, std::int32_t idx) { + if (idx == 0) { return executor.read_type(m_Value); } return ParserArgs::run_type_at(executor, idx - 1); @@ -73,34 +65,29 @@ namespace stream::fmt::detail public: template - [[nodiscard]] inline std::expected get_index_of_current_named_arg(buf::StreamView& format, std::int32_t begin_search_index) - { - if constexpr (detail::IsANamedArgs>::value) - { + [[nodiscard]] inline std::expected get_index_of_current_named_arg(buf::StreamView& format, std::int32_t begin_search_index) { + if constexpr (detail::IsANamedArgs>::value) { bool current_is_a_named_arg = SF_TRY(buf::FMTParamsManip(format).next_is_named_args(m_Value.get_name())); - if (current_is_a_named_arg) - return begin_search_index; + if (current_is_a_named_arg) return begin_search_index; } return ParserArgs::get_index_of_current_named_arg(format, begin_search_index + 1); } public: - [[nodiscard]] inline std::expected get_pointerid_at(std::int32_t idx) - { + [[nodiscard]] inline std::expected get_pointerid_at(std::int32_t idx) { if (idx == 0) return PointerID{.type_info = typeid(TypeWithoutRef), .ptr = static_cast(&m_Value)}; return ParserArgs::get_pointerid_at(idx - 1); } public: template - [[nodiscard]] inline std::expected get_converted_type_at(std::int32_t idx) - { - if (idx == 0) - { - if constexpr (FMTCanContextConvert) - { return FMTContextConvert::convert(m_Value); } - else - { return std::unexpected(FMTResult::ArgsInterface_InvalidConversion); } + [[nodiscard]] inline std::expected get_converted_type_at(std::int32_t idx) { + if (idx == 0) { + if constexpr (FMTCanContextConvert) { + return FMTContextConvert::convert(m_Value); + } else { + return std::unexpected(FMTResult::ArgsInterface_InvalidConversion); + } } return ParserArgs::template get_converted_type_at(idx - 1); } @@ -111,43 +98,35 @@ namespace stream::fmt::detail /******** Args interface ********/ /********************************/ template - class ParserArgsInterface : public BasicArgsInterface - { + class ParserArgsInterface : public BasicArgsInterface { public: using ContextArgsType = ParserArgs; public: - ParserArgsInterface(ParserExecutor& executor, Args&&... args) - : BasicArgsInterface() - , executor(executor) - , args_interface(std::forward(args)...) - {} + ParserArgsInterface(ParserExecutor& executor, Args&&... args) : BasicArgsInterface(), executor(executor), args_interface(std::forward(args)...) {} ~ParserArgsInterface() override = default; public: - std::size_t size() override { return args_interface.size(); } + std::size_t size() override { + return args_interface.size(); + } public: - [[nodiscard]] std::expected run_type_at(std::int32_t idx) override - { + [[nodiscard]] std::expected run_type_at(std::int32_t idx) override { return args_interface.run_type_at(executor, idx); } - [[nodiscard]] std::expected get_index_of_current_named_arg(buf::StreamView& format) override - { + [[nodiscard]] std::expected get_index_of_current_named_arg(buf::StreamView& format) override { return args_interface.get_index_of_current_named_arg(format, std::int32_t{0}); } - [[nodiscard]] inline std::expected get_pointerid_at(std::int32_t idx) override - { + [[nodiscard]] inline std::expected get_pointerid_at(std::int32_t idx) override { return args_interface.get_pointerid_at(idx); } public: - [[nodiscard]] std::expected, FMTResult> get_string_at(std::int32_t idx) override - { + [[nodiscard]] std::expected, FMTResult> get_string_at(std::int32_t idx) override { return args_interface.template get_converted_type_at>(idx); } - [[nodiscard]] std::expected get_int_at(std::int32_t idx) override - { + [[nodiscard]] std::expected get_int_at(std::int32_t idx) override { return args_interface.template get_converted_type_at(idx); } @@ -155,4 +134,4 @@ namespace stream::fmt::detail ParserExecutor& executor; ContextArgsType args_interface; }; -} +} // namespace stream::fmt::detail diff --git a/src/stream/fmt/context/parser_executor/parser_text_properties_executor/parser_text_properties_executor.h b/src/stream/fmt/context/parser_executor/parser_text_properties_executor/parser_text_properties_executor.h index 65e798b3..bba4bc69 100644 --- a/src/stream/fmt/context/parser_executor/parser_text_properties_executor/parser_text_properties_executor.h +++ b/src/stream/fmt/context/parser_executor/parser_text_properties_executor/parser_text_properties_executor.h @@ -4,66 +4,107 @@ #include "stream/fmt/detail/prelude.h" #include "stream/fmt/context/parser_executor/basic_parser_executor.h" -namespace stream::fmt::detail -{ +namespace stream::fmt::detail { template - class IParserTextPropertiesExecutor : public ITextPropertiesExecutor - { + class IParserTextPropertiesExecutor : public ITextPropertiesExecutor { public: - IParserTextPropertiesExecutor() = default; + IParserTextPropertiesExecutor() = default; ~IParserTextPropertiesExecutor() override = default; - void link_to_executor(void* executor) override - { + void link_to_executor(void* executor) override { buffer = &reinterpret_cast*>(executor)->istream; } protected: buf::StreamView* buffer{nullptr}; }; -} +} // namespace stream::fmt::detail -namespace stream::fmt::detail -{ +namespace stream::fmt::detail { template - class ParserNOTextPropertiesExecutor : public IParserTextPropertiesExecutor - { + class ParserNOTextPropertiesExecutor : public IParserTextPropertiesExecutor { public: - ParserNOTextPropertiesExecutor() = default; + ParserNOTextPropertiesExecutor() = default; ~ParserNOTextPropertiesExecutor() override = default; using IParserTextPropertiesExecutor::buffer; public: - [[nodiscard]] std::expected all_properties_reset() override { return {}; } + [[nodiscard]] std::expected all_properties_reset() override { + return {}; + } public: [[nodiscard]] std::expected reset_color() override {} - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::BasicColorFG&) override { return {}; } - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::BasicColorBG&) override { return {}; } - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::BasicColor&) override { return {}; } - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::Color24bFG&) override { return {}; } - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::Color24bBG&) override { return {}; } - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::Color24b&) override { return {}; } - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::ColorCubeFG&) override { return {}; } - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::ColorCubeBG&) override { return {}; } - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::ColorCube&) override { return {}; } + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::BasicColorFG&) override { + return {}; + } + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::BasicColorBG&) override { + return {}; + } + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::BasicColor&) override { + return {}; + } + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::Color24bFG&) override { + return {}; + } + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::Color24bBG&) override { + return {}; + } + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::Color24b&) override { + return {}; + } + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::ColorCubeFG&) override { + return {}; + } + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::ColorCubeBG&) override { + return {}; + } + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::ColorCube&) override { + return {}; + } public: - [[nodiscard]] std::expected reset_front() override { return {}; } - [[nodiscard]] std::expected execute_front(const detail::TextProperties::TextFront::FrontID&) override { return {}; } + [[nodiscard]] std::expected reset_front() override { + return {}; + } + [[nodiscard]] std::expected execute_front(const detail::TextProperties::TextFront::FrontID&) override { + return {}; + } public: - [[nodiscard]] std::expected reset_style() override { return {}; } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Intensity&) override { return {}; } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Italic&) override { return {}; } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Underline&) override { return {}; } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::UnderlineColor::Color&) override { return {}; } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::UnderlineColor::ColorCube&) override { return {}; } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::UnderlineColor::Color24b&) override { return {}; } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Blink&) override { return {}; } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Inverted&) override { return {}; } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Ideogram&) override { return {}; } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Script&) override { return {}; } + [[nodiscard]] std::expected reset_style() override { + return {}; + } + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Intensity&) override { + return {}; + } + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Italic&) override { + return {}; + } + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Underline&) override { + return {}; + } + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::UnderlineColor::Color&) override { + return {}; + } + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::UnderlineColor::ColorCube&) override { + return {}; + } + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::UnderlineColor::Color24b&) override { + return {}; + } + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Blink&) override { + return {}; + } + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Inverted&) override { + return {}; + } + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Ideogram&) override { + return {}; + } + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Script&) override { + return {}; + } }; -} +} // namespace stream::fmt::detail diff --git a/src/stream/fmt/context/parser_executor/parser_text_properties_executor/parser_text_properties_executor_ansi.h b/src/stream/fmt/context/parser_executor/parser_text_properties_executor/parser_text_properties_executor_ansi.h index f5141b39..245e606b 100644 --- a/src/stream/fmt/context/parser_executor/parser_text_properties_executor/parser_text_properties_executor_ansi.h +++ b/src/stream/fmt/context/parser_executor/parser_text_properties_executor/parser_text_properties_executor_ansi.h @@ -2,143 +2,117 @@ #include "parser_text_properties_executor.h" -namespace stream::fmt::detail -{ +namespace stream::fmt::detail { template - class ParserANSITextPropertiesExecutor : public IParserTextPropertiesExecutor - { + class ParserANSITextPropertiesExecutor : public IParserTextPropertiesExecutor { public: - ParserANSITextPropertiesExecutor() = default; + ParserANSITextPropertiesExecutor() = default; ~ParserANSITextPropertiesExecutor() override = default; - + using IParserTextPropertiesExecutor::buffer; public: - [[nodiscard]] std::expected all_properties_reset() override - { + [[nodiscard]] std::expected all_properties_reset() override { return std::unexpected(FMTResult::FunctionNotImpl); /*ReadManip(buffer).BasicReadType('\033', '[', 0, 'm');*/ } public: - [[nodiscard]] std::expected reset_color() override - { + [[nodiscard]] std::expected reset_color() override { return std::unexpected(FMTResult::FunctionNotImpl); /*ReadManip(buffer).BasicReadType('\033', '[', 39, ';', 49, 'm');*/ } - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::BasicColorFG&) override - { + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::BasicColorFG&) override { return std::unexpected(FMTResult::FunctionNotImpl); /*ReadManip(buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ } - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::BasicColorBG&) override - { + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::BasicColorBG&) override { return std::unexpected(FMTResult::FunctionNotImpl); /*ReadManip(buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ } - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::BasicColor&) override - { + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::BasicColor&) override { return std::unexpected(FMTResult::FunctionNotImpl); /*ReadManip(buffer).BasicReadType('\033', '[', static_cast(t.fg) , ';', static_cast(t.bg), 'm');*/ } - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::Color24bFG&) override - { + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::Color24bFG&) override { return std::unexpected(FMTResult::FunctionNotImpl); /*ReadManip(buffer).BasicReadType("\033[38;2;", t.r, ';', t.g, ';', t.b, 'm');*/ } - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::Color24bBG&) override - { + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::Color24bBG&) override { return std::unexpected(FMTResult::FunctionNotImpl); /*ReadManip(buffer).BasicReadType("\033[48;2;", t.r, ';', t.g, ';', t.b, 'm');*/ } - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::Color24b&) override - { + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::Color24b&) override { return std::unexpected(FMTResult::FunctionNotImpl); /*ReadManip(buffer).BasicReadType("\033[38;2;", t.fg.r, ';', t.fg.g, ';', t.fg.b, "; 48; 2;", t.bg.r, ';', t.bg.g, ';', t.bg.b, 'm');*/ } - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::ColorCubeFG&) override - { + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::ColorCubeFG&) override { return std::unexpected(FMTResult::FunctionNotImpl); /*ReadManip(buffer).BasicReadType("\033[38;5;", t.get_color_ref(), 'm');*/ } - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::ColorCubeBG&) override - { + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::ColorCubeBG&) override { return std::unexpected(FMTResult::FunctionNotImpl); /*ReadManip(buffer).BasicReadType("\033[48;5;", t.get_color_ref(), 'm');*/ } - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::ColorCube&) override - { + [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::ColorCube&) override { return std::unexpected(FMTResult::FunctionNotImpl); /*ReadManip(buffer).BasicReadType("\033[48;5;", t.fg.get_color_ref(), ";48;5;", t.bg.get_color_ref(), 'm');*/ } public: - [[nodiscard]] std::expected reset_front() override - { + [[nodiscard]] std::expected reset_front() override { return std::unexpected(FMTResult::FunctionNotImpl); /*ReadManip(buffer).BasicReadType('\033', '[', detail::TextProperties::TextFront::FrontID::DefaultFrontID, 'm');*/ } - [[nodiscard]] std::expected execute_front(const detail::TextProperties::TextFront::FrontID&) override - { + [[nodiscard]] std::expected execute_front(const detail::TextProperties::TextFront::FrontID&) override { return std::unexpected(FMTResult::FunctionNotImpl); /*ReadManip(buffer).BasicReadType('\033', '[', t.ID, 'm');*/ } public: - [[nodiscard]] std::expected reset_style() override - { + [[nodiscard]] std::expected reset_style() override { return std::unexpected(FMTResult::FunctionNotImpl); /*ReadManip(buffer).BasicReadType('\033', '[', 0, 'm');*/ } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Intensity&) override - { + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Intensity&) override { return std::unexpected(FMTResult::FunctionNotImpl); /*ReadManip(buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Italic&) override - { + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Italic&) override { return std::unexpected(FMTResult::FunctionNotImpl); /*ReadManip(buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Underline&) override - { + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Underline&) override { return std::unexpected(FMTResult::FunctionNotImpl); /*ReadManip(buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::UnderlineColor::Color&) override - { + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::UnderlineColor::Color&) override { return std::unexpected(FMTResult::FunctionNotImpl); /*ReadManip(buffer).BasicReadType("\033[59m");*/ } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::UnderlineColor::ColorCube&) override - { + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::UnderlineColor::ColorCube&) override { return std::unexpected(FMTResult::FunctionNotImpl); /*ReadManip(buffer).BasicReadType("\033[58;5;", t.get_color_ref(), 'm');*/ } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::UnderlineColor::Color24b&) override - { + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::UnderlineColor::Color24b&) override { return std::unexpected(FMTResult::FunctionNotImpl); /*ReadManip(buffer).BasicReadType("\033[58;2;", t.r, ';', t.g, ';', t.b, 'm');*/ } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Blink&) override - { + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Blink&) override { return std::unexpected(FMTResult::FunctionNotImpl); /*ReadManip(buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Inverted&) override - { + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Inverted&) override { return std::unexpected(FMTResult::FunctionNotImpl); /*ReadManip(buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Ideogram&) override - { + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Ideogram&) override { return std::unexpected(FMTResult::FunctionNotImpl); /*ReadManip(buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Script&) override - { + [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Script&) override { return std::unexpected(FMTResult::FunctionNotImpl); /*ReadManip(buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ } }; -} +} // namespace stream::fmt::detail diff --git a/src/stream/fmt/context/parser_executor/parser_type.h b/src/stream/fmt/context/parser_executor/parser_type.h index 68e54d9b..5c451366 100644 --- a/src/stream/fmt/context/parser_executor/parser_type.h +++ b/src/stream/fmt/context/parser_executor/parser_type.h @@ -3,13 +3,10 @@ #include "stream/fmt/detail/prelude.h" #define STREAMFORMAT_PARSER_DECLARED -namespace stream::fmt -{ +namespace stream::fmt { template > - struct ParserType - { - static inline bool parse(T&, ParserExecutor&) - { + struct ParserType { + static inline bool parse(T&, ParserExecutor&) { #ifdef UNKOWN_TYPE_MESSAGE // FIXME STREAMFORMAT_DEBUGBREAK(); @@ -25,11 +22,12 @@ namespace stream::fmt } }; -} +} // namespace stream::fmt -#define STREAMFORMAT_AUTO_PARSER(type, fmt, ...) \ - template \ - struct stream::fmt::ParserType \ - { \ - static bool parse(Type& value, ParserExecutor& executor) { return executor.run(fmt, __VA_ARGS__); } \ +#define STREAMFORMAT_AUTO_PARSER(type, fmt, ...) \ + template \ + struct stream::fmt::ParserType { \ + static bool parse(Type& value, ParserExecutor& executor) { \ + return executor.run(fmt, __VA_ARGS__); \ + } \ }; diff --git a/src/stream/fmt/context/parser_executor/utility_functions.h b/src/stream/fmt/context/parser_executor/utility_functions.h index 64ad48dc..1f97ec7c 100644 --- a/src/stream/fmt/context/parser_executor/utility_functions.h +++ b/src/stream/fmt/context/parser_executor/utility_functions.h @@ -7,18 +7,16 @@ #include "parser_text_properties_executor/parser_text_properties_executor_ansi.h" -namespace stream::fmt -{ +namespace stream::fmt { template - [[nodiscard]] std::expected parse(Buffer&& buffer_input, Format&& format_input, Args&&... args) - { + [[nodiscard]] std::expected parse(Buffer&& buffer_input, Format&& format_input, Args&&... args) { buf::StreamView buffer{buffer_input}; buf::StreamView format{format_input}; using TChar = typename decltype(format)::TChar; detail::ParserNOTextPropertiesExecutor> text_properties_executor; - context::BasicParserExecutor> executor(buffer, text_properties_executor); + context::BasicParserExecutor> executor(buffer, text_properties_executor); SF_TRY(executor.run(format, std::forward(args)...)); return executor.terminate(); } -} +} // namespace stream::fmt diff --git a/src/stream/fmt/context/utils/context_functions.h b/src/stream/fmt/context/utils/context_functions.h index d4c67196..fc84f838 100644 --- a/src/stream/fmt/context/utils/context_functions.h +++ b/src/stream/fmt/context/utils/context_functions.h @@ -2,21 +2,18 @@ #include "stream/fmt/detail/specifiers.h" -namespace stream::fmt::detail -{ +namespace stream::fmt::detail { template - struct FunctionapplyNextOverride - { - inline explicit FunctionapplyNextOverride(FormatterExecutor& executor) - : executor(executor) - , formatdata(executor.data) - { + struct FunctionapplyNextOverride { + inline explicit FunctionapplyNextOverride(FormatterExecutor& executor) : executor(executor), formatdata(executor.data) { executor.formatdata_apply_next_override(); } - inline ~FunctionapplyNextOverride() { executor.data = formatdata; } + inline ~FunctionapplyNextOverride() { + executor.data = formatdata; + } - FormatterExecutor& executor; + FormatterExecutor& executor; detail::FormatData formatdata; }; -} +} // namespace stream::fmt::detail diff --git a/src/stream/fmt/detail/convert_traits.h b/src/stream/fmt/detail/convert_traits.h index d26957d5..1f73ab28 100644 --- a/src/stream/fmt/detail/convert_traits.h +++ b/src/stream/fmt/detail/convert_traits.h @@ -2,60 +2,55 @@ #include "prelude.h" -namespace stream::fmt::detail -{ +namespace stream::fmt::detail { template - struct FormatTypeForwardAs - { + struct FormatTypeForwardAs { using type = T; }; template - struct FMTContextConvert - { + struct FMTContextConvert { static constexpr bool is_convertible = false; }; template - requires(std::is_convertible_v&& std::is_convertible_v) struct FMTContextConvert - { + requires(std::is_convertible_v && std::is_convertible_v) + struct FMTContextConvert { static constexpr bool is_convertible = true; - static constexpr To convert(const From& from) { return static_cast(from); } + static constexpr To convert(const From& from) { + return static_cast(from); + } }; template - requires(std::is_convertible_v&& - std::is_convertible_v) struct FMTContextConvert - { - static constexpr bool is_convertible = true; - static constexpr std::int32_t convert(const From& from) { return std::int32_t(static_cast(from)); } + requires(std::is_convertible_v && std::is_convertible_v) + struct FMTContextConvert { + static constexpr bool is_convertible = true; + static constexpr std::int32_t convert(const From& from) { + return std::int32_t(static_cast(from)); + } }; template - concept FMTCanContextConvert = requires(const From& from) - { + concept FMTCanContextConvert = requires(const From& from) { requires FMTContextConvert::is_convertible; - { - FMTContextConvert::convert(from) - } -> std::same_as; + { FMTContextConvert::convert(from) } -> std::same_as; }; template - struct FMTContextSame - { + struct FMTContextSame { static constexpr bool same_as = false; }; template - requires(std::is_same_v, detail::get_base_type>) struct FMTContextSame - { + requires(std::is_same_v, detail::get_base_type>) + struct FMTContextSame { static constexpr bool same_as = true; }; template - concept fmt_is_context_same = requires(To* to, const From& from) - { + concept fmt_is_context_same = requires(To* to, const From& from) { requires FMTContextSame::same_as; *to = from; }; -} +} // namespace stream::fmt::detail diff --git a/src/stream/fmt/detail/fmt_result.h b/src/stream/fmt/detail/fmt_result.h index 3d85e54d..a410b945 100644 --- a/src/stream/fmt/detail/fmt_result.h +++ b/src/stream/fmt/detail/fmt_result.h @@ -2,10 +2,8 @@ #include "stream/core/prelude.h" -namespace stream::fmt -{ - enum class FMTResult - { +namespace stream::fmt { + enum class FMTResult { FunctionNotImpl, Buffer_NonValid, @@ -28,23 +26,19 @@ namespace stream::fmt Context_ArgumentIndexResolution, Context_ArgumentIndexExpected, Context_CannotapplyType, - + GivenArgs_UnableToDeduceSize, Manager_StaticMemory, Manager_AllocationFailed, }; -} - -namespace stream::detail -{ - template<> - inline fmt::FMTResult forward_error(fmt::FMTResult t) - { - if (t == fmt::FMTResult::ArgsInterface_CantMatchNamedArgs) - return t; - if (t == fmt::FMTResult::Manager_StaticMemory) - return t; +} // namespace stream::fmt + +namespace stream::detail { + template <> + inline fmt::FMTResult forward_error(fmt::FMTResult t) { + if (t == fmt::FMTResult::ArgsInterface_CantMatchNamedArgs) return t; + if (t == fmt::FMTResult::Manager_StaticMemory) return t; return t; } -} +} // namespace stream::detail diff --git a/src/stream/fmt/detail/indent_handlers.h b/src/stream/fmt/detail/indent_handlers.h index 9c5d4bce..eeab721e 100644 --- a/src/stream/fmt/detail/indent_handlers.h +++ b/src/stream/fmt/detail/indent_handlers.h @@ -3,19 +3,16 @@ #include "stream/fmt/detail/prelude.h" #include "stream/fmt/buf/fmt_manip_io.h" -namespace stream::fmt::detail -{ +namespace stream::fmt::detail { template - struct NoStrideFunction - { - inline explicit NoStrideFunction(buf::FMTStreamIO& buffer_) - : buffer(buffer_) - , size_buffer(buf::Access(buffer_).get_buffer_current_size()) - {} + struct NoStrideFunction { + inline explicit NoStrideFunction(buf::FMTStreamIO& buffer_) : buffer(buffer_), size_buffer(buf::Access(buffer_).get_buffer_current_size()) {} - ~NoStrideFunction() { buf::FMTManipIO(buffer).add_no_stride(buf::Access(buffer).get_buffer_current_size() - size_buffer); } + ~NoStrideFunction() { + buf::FMTManipIO(buffer).add_no_stride(buf::Access(buffer).get_buffer_current_size() - size_buffer); + } buf::FMTStreamIO& buffer; - std::size_t size_buffer; + std::size_t size_buffer; }; -} +} // namespace stream::fmt::detail diff --git a/src/stream/fmt/detail/prelude.h b/src/stream/fmt/detail/prelude.h index 1d24aa01..43b146f3 100644 --- a/src/stream/fmt/detail/prelude.h +++ b/src/stream/fmt/detail/prelude.h @@ -24,8 +24,7 @@ // End writing all writer and reader (string / char pt) // -namespace stream::fmt::context -{ +namespace stream::fmt::context { template class BasicContext; @@ -36,4 +35,4 @@ namespace stream::fmt::context template class BasicParserExecutor; -} +} // namespace stream::fmt::context diff --git a/src/stream/fmt/detail/specifiers.h b/src/stream/fmt/detail/specifiers.h index 572b4f5c..b909806d 100644 --- a/src/stream/fmt/detail/specifiers.h +++ b/src/stream/fmt/detail/specifiers.h @@ -7,24 +7,20 @@ #include #include -namespace stream::fmt::detail -{ - enum class IntegerPrintBase : char - { - Dec = 'd', - Bin = 'b', +namespace stream::fmt::detail { + enum class IntegerPrintBase : char { + Dec = 'd', + Bin = 'b', BinUpper = 'B', - Hex = 'x', + Hex = 'x', HexUpper = 'X', - Oct = 'o', + Oct = 'o', OctUpper = 'O', }; - struct ShiftInfo - { + struct ShiftInfo { public: - enum class ShiftType : std::int8_t - { + enum class ShiftType : std::int8_t { Nothing, Right, Left, @@ -33,205 +29,162 @@ namespace stream::fmt::detail Default = Nothing }; - struct ShiftPrint - { + struct ShiftPrint { public: - constexpr ShiftPrint() - : before(' ') - , after(' ') - {} + constexpr ShiftPrint() : before(' '), after(' ') {} - constexpr ShiftPrint(char c) - : before(c) - , after(c) - {} + constexpr ShiftPrint(char c) : before(c), after(c) {} - constexpr ShiftPrint(char before, char after) - : before(before) - , after(after) - {} + constexpr ShiftPrint(char before, char after) : before(before), after(after) {} public: char before; char after; public: - constexpr bool before_is_a_digit() const { return before >= '0' && before <= '9'; } + constexpr bool before_is_a_digit() const { + return before >= '0' && before <= '9'; + } }; public: - ShiftType type = ShiftType::Default; // < - > - ^ - ShiftPrint print = ShiftPrint{}; // 0 - ' ' - * ..... - std::int32_t size = -1; // ? - ^? + ShiftType type = ShiftType::Default; // < - > - ^ + ShiftPrint print = ShiftPrint{}; // 0 - ' ' - * ..... + std::int32_t size = -1; // ? - ^? }; -} +} // namespace stream::fmt::detail -namespace stream::fmt::detail -{ +namespace stream::fmt::detail { template - struct FormatSpecifier - { - FormatSpecifier() - : name(nullptr, 0) - , as_text(nullptr, 0) - , as_number(0) - , has_text(false) - , has_number(false) - {} - - FormatSpecifier(std::basic_string_view name) - : name(name) - , as_text(nullptr, 0) - , as_number(0) - , has_text(false) - , has_number(false) - {} - - FormatSpecifier(std::basic_string_view name, std::basic_string_view value) - : name(name) - , as_text(value) - , as_number(0) - , has_text(true) - , has_number(false) - {} - - FormatSpecifier(std::basic_string_view name, const std::int32_t value) - : name(name) - , as_text(nullptr, 0) - , as_number(value) - , has_text(false) - , has_number(true) - {} + struct FormatSpecifier { + FormatSpecifier() : name(nullptr, 0), as_text(nullptr, 0), as_number(0), has_text(false), has_number(false) {} + + FormatSpecifier(std::basic_string_view name) : name(name), as_text(nullptr, 0), as_number(0), has_text(false), has_number(false) {} + + FormatSpecifier(std::basic_string_view name, std::basic_string_view value) : name(name), as_text(value), as_number(0), has_text(true), has_number(false) {} + + FormatSpecifier(std::basic_string_view name, const std::int32_t value) : name(name), as_text(nullptr, 0), as_number(value), has_text(false), has_number(true) {} FormatSpecifier(std::basic_string_view name, const std::int32_t value_as_number, std::basic_string_view value_as_text) - : name(name) - , as_text(value_as_text) - , as_number(value_as_number) - , has_text(true) - , has_number(true) - {} - - std::basic_string_view name = ""; - std::basic_string_view as_text = ""; - std::int32_t as_number = 0; - bool has_text = false; - bool has_number = false; + : name(name), as_text(value_as_text), as_number(value_as_number), has_text(true), has_number(true) {} + + std::basic_string_view name = ""; + std::basic_string_view as_text = ""; + std::int32_t as_number = 0; + bool has_text = false; + bool has_number = false; }; template - struct FormatSpecifierList - { + struct FormatSpecifierList { public: - std::uint8_t specifier_count = 0; - std::array, SIZE> specifiers{}; + std::uint8_t specifier_count = 0; + std::array, SIZE> specifiers{}; - struct Constraint - { - bool has_text = false; + struct Constraint { + bool has_text = false; bool has_number = false; }; public: - static inline constexpr std::uint8_t NotFound() { return (std::numeric_limits::max)(); } + static inline constexpr std::uint8_t NotFound() { + return (std::numeric_limits::max)(); + } - FormatSpecifier* get(std::basic_string_view name, const Constraint& constraint = Constraint{}) - { + FormatSpecifier* get(std::basic_string_view name, const Constraint& constraint = Constraint{}) { STREAMFORMAT_ASSERT(specifier_count <= SIZE); for (std::uint8_t i = 0; i < specifier_count; ++i) - if (specifiers[i].name == name) - { - bool text_contraint_satisfied = !constraint.has_text || specifiers[i].has_text; + if (specifiers[i].name == name) { + bool text_contraint_satisfied = !constraint.has_text || specifiers[i].has_text; bool number_contraint_satisfied = !constraint.has_number || specifiers[i].has_number; - if (text_contraint_satisfied && number_contraint_satisfied) - return &specifiers[i]; + if (text_contraint_satisfied && number_contraint_satisfied) return &specifiers[i]; } return nullptr; } - const FormatSpecifier* get(std::basic_string_view name, const Constraint& constraint = Constraint{}) const - { + const FormatSpecifier* get(std::basic_string_view name, const Constraint& constraint = Constraint{}) const { STREAMFORMAT_ASSERT(specifier_count <= SIZE); for (std::uint8_t i = 0; i < specifier_count; ++i) - if (specifiers[i].name == name) - { - bool text_contraint_satisfied = !constraint.has_text || specifiers[i].has_text; + if (specifiers[i].name == name) { + bool text_contraint_satisfied = !constraint.has_text || specifiers[i].has_text; bool number_contraint_satisfied = !constraint.has_number || specifiers[i].has_number; - if (text_contraint_satisfied && number_contraint_satisfied) - return &specifiers[i]; + if (text_contraint_satisfied && number_contraint_satisfied) return &specifiers[i]; } return nullptr; } - bool has(std::basic_string_view name) const { return get(name) != nullptr; } + bool has(std::basic_string_view name) const { + return get(name) != nullptr; + } - std::int32_t get_as_number(std::basic_string_view name, std::int32_t default_value) const - { + std::int32_t get_as_number(std::basic_string_view name, std::int32_t default_value) const { const FormatSpecifier* getptr = get(name, Constraint{.has_number = true}); - if (getptr == nullptr || !getptr->has_number) - return default_value; + if (getptr == nullptr || !getptr->has_number) return default_value; return getptr->as_number; } - std::basic_string_view get_as_text(std::basic_string_view name, std::basic_string_view default_value) const - { + std::basic_string_view get_as_text(std::basic_string_view name, std::basic_string_view default_value) const { const FormatSpecifier* getptr = get(name, Constraint{.has_text = true}); - if (getptr == nullptr || !getptr->has_text) - return default_value; + if (getptr == nullptr || !getptr->has_text) return default_value; return getptr->as_text; } public: - [[nodiscard]] std::expected pushback(const FormatSpecifier& specifier) - { - if (specifier_count >= SIZE) - return std::unexpected(FMTResult::Specifiers_Full); + [[nodiscard]] std::expected pushback(const FormatSpecifier& specifier) { + if (specifier_count >= SIZE) return std::unexpected(FMTResult::Specifiers_Full); specifiers[specifier_count++] = specifier; return {}; } - [[nodiscard]] std::expected concat(const FormatSpecifier& specifier) - { + [[nodiscard]] std::expected concat(const FormatSpecifier& specifier) { FormatSpecifier* local = get(specifier.name); - if (local == nullptr) - return pushback(specifier); + if (local == nullptr) return pushback(specifier); - if (specifier.has_text) - { local->has_text = true; local->as_text = specifier.as_text; } - if (specifier.has_number) - { local->has_number = true; local->as_number = specifier.as_number; } + if (specifier.has_text) { + local->has_text = true; + local->as_text = specifier.as_text; + } + if (specifier.has_number) { + local->has_number = true; + local->as_number = specifier.as_number; + } return {}; } }; template - struct FormatData - { + struct FormatData { public: - bool has_spec = false; - bool keep_new_style = false; // W + bool has_spec = false; + bool keep_new_style = false; // W - bool prefix_suffix = false; // # - IntegerPrintBase integer_print = IntegerPrintBase::Dec; // b - X - O - D - std::int32_t float_precision = -1; // . - ShiftInfo shift; + bool prefix_suffix = false; // # + IntegerPrintBase integer_print = IntegerPrintBase::Dec; // b - X - O - D + std::int32_t float_precision = -1; // . + ShiftInfo shift; FormatSpecifierList specifiers; std::basic_string_view next_override = std::basic_string_view(nullptr, 0); public: - void apply(const FormatData& given) { *this = given; } + void apply(const FormatData& given) { + *this = given; + } - void apply(const IntegerPrintBase& given) { integer_print = given; } - void apply(const ShiftInfo& given) { shift = given; } - void apply(const FormatSpecifier& given) { specifiers.concat(given); } + void apply(const IntegerPrintBase& given) { + integer_print = given; + } + void apply(const ShiftInfo& given) { + shift = given; + } + void apply(const FormatSpecifier& given) { + specifiers.concat(given); + } template bool testapply(const T* given) - requires requires(const T& value, FormatData& data) - { - data.apply(value); - } + requires requires(const T& value, FormatData& data) { data.apply(value); } { if (given == nullptr) return false; apply(*given); @@ -240,8 +193,5 @@ namespace stream::fmt::detail }; template - concept format_data_can_apply = requires(const T& value, FormatData& data) - { - data.apply(value); - }; -} + concept format_data_can_apply = requires(const T& value, FormatData& data) { data.apply(value); }; +} // namespace stream::fmt::detail diff --git a/src/stream/fmt/detail/types_traits.h b/src/stream/fmt/detail/types_traits.h index f28808df..5ea339f2 100644 --- a/src/stream/fmt/detail/types_traits.h +++ b/src/stream/fmt/detail/types_traits.h @@ -4,16 +4,14 @@ #include -namespace stream::fmt::detail -{ +namespace stream::fmt::detail { template using get_base_type = std::remove_cv_t>; template - struct IsCharType - { + struct IsCharType { using BaseType = get_base_type; static constexpr bool value = std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v; }; -} +} // namespace stream::fmt::detail diff --git a/src/stream/fmt/serializers/compilation_data.h b/src/stream/fmt/serializers/compilation_data.h index 502980f3..73422323 100644 --- a/src/stream/fmt/serializers/compilation_data.h +++ b/src/stream/fmt/serializers/compilation_data.h @@ -3,53 +3,36 @@ #include "stream/core/prelude.h" #include "stream/flog.h" -namespace stream::fmt::detail -{ - struct FileLocation - { - FileLocation(std::string_view file_name_, int file_line_ = 0) - : file_name(file_name_) - , file_line(file_line_) - {} +namespace stream::fmt::detail { + struct FileLocation { + FileLocation(std::string_view file_name_, int file_line_ = 0) : file_name(file_name_), file_line(file_line_) {} std::string_view file_name; // __FILE__ int file_line; // __LINE__ }; - struct FunctionProperties - { + struct FunctionProperties { FunctionProperties(std::string_view file_name_, int file_line_ = 0, std::string_view functionName = "", std::string_view function_signature_ = "", std::string_view function_assembly_name_ = "") - : location(file_name_, file_line_) - , function_name(functionName) - , function_signature(function_signature_) - , function_assembly_name(function_assembly_name_) - {} + : location(file_name_, file_line_), function_name(functionName), function_signature(function_signature_), function_assembly_name(function_assembly_name_) {} FunctionProperties(FileLocation location, std::string_view functionName = "", std::string_view function_signature_ = "", std::string_view function_assembly_name_ = "") - : location(location) - , function_name(functionName) - , function_signature(function_signature_) - , function_assembly_name(function_assembly_name_) - {} + : location(location), function_name(functionName), function_signature(function_signature_), function_assembly_name(function_assembly_name_) {} FileLocation location; - std::string_view function_name; // __FUNCTION__ - std::string_view function_signature; // __FUNCSIG__ -- __PRETTY_FUNCTION__ + std::string_view function_name; // __FUNCTION__ + std::string_view function_signature; // __FUNCSIG__ -- __PRETTY_FUNCTION__ std::string_view function_assembly_name; // __FUNCDNAME__ }; -} +} // namespace stream::fmt::detail -#define STREAMFORMAT_FMT_FILE_LOCATION() stream::fmt::detail::FileLocation(__FILE__, __LINE__) +#define STREAMFORMAT_FMT_FILE_LOCATION() stream::fmt::detail::FileLocation(__FILE__, __LINE__) #define STREAMFORMAT_FMT_FUNCTION_PROPERTIES() stream::fmt::detail::FunctionProperties(STREAMFORMAT_FMT_FILE_LOCATION(), __FUNCTION__, __FUNCSIG__, __FUNCDNAME__) -namespace stream::fmt -{ +namespace stream::fmt { template - struct FormatterType - { - [[nodiscard]] static inline std::expected format(const detail::FileLocation& t, FormatterExecutor& executor) - { + struct FormatterType { + [[nodiscard]] static inline std::expected format(const detail::FileLocation& t, FormatterExecutor& executor) { SF_TRY(executor.write_type(t.file_name)); SF_TRY(executor.ostream.pushback(':')); return executor.write_type(t.file_line); @@ -57,13 +40,11 @@ namespace stream::fmt }; template - struct FormatterType - { - [[nodiscard]] static inline std::expected format(const detail::FunctionProperties& t, FormatterExecutor& executor) - { + struct FormatterType { + [[nodiscard]] static inline std::expected format(const detail::FunctionProperties& t, FormatterExecutor& executor) { SF_TRY(executor.write_type(t.location)); SF_TRY(executor.ostream.write_char_array(" @ ")); return executor.write_type(t.function_name); } }; -} +} // namespace stream::fmt diff --git a/src/stream/fmt/serializers/format_chrono.h b/src/stream/fmt/serializers/format_chrono.h index 85187d48..ed781ba1 100644 --- a/src/stream/fmt/serializers/format_chrono.h +++ b/src/stream/fmt/serializers/format_chrono.h @@ -9,37 +9,30 @@ #include -namespace stream::fmt::detail -{ - enum class TimePrintMode : std::uint8_t - { +namespace stream::fmt::detail { + enum class TimePrintMode : std::uint8_t { FullTime, Mod, Sub, }; template - [[nodiscard]] std::expected write_sub_time_(const std::chrono::time_point& value, buf::StreamView& pattern, buf::FMTStreamIO& buffer, TimePrintMode mode) - { + [[nodiscard]] std::expected write_sub_time_(const std::chrono::time_point& value, buf::StreamView& pattern, + buf::FMTStreamIO& buffer, TimePrintMode mode) { ShiftInfo shift; - shift.type = detail::ShiftInfo::ShiftType::Right; + shift.type = detail::ShiftInfo::ShiftType::Right; shift.print = detail::ShiftInfo::ShiftPrint('0', ' '); - shift.size = 0; + shift.size = 0; (void)buf::ReadManip(pattern).fast_read_integer(shift.size); - if (mode == TimePrintMode::Mod && shift.size < 0) - shift.size = 3; + if (mode == TimePrintMode::Mod && shift.size < 0) shift.size = 3; - if (buf::TestAccess(pattern).is_same("ns", 2)) - { + if (buf::TestAccess(pattern).is_same("ns", 2)) { SF_TRY(buf::Manip(pattern).forward()); std::uint32_t ns = static_cast(std::chrono::time_point_cast(value).time_since_epoch().count()); - if (mode == TimePrintMode::Mod) - ns = ns % 1000; + if (mode == TimePrintMode::Mod) ns = ns % 1000; SF_TRY(buf::FMTWriteManip(buffer).write_integer(static_cast(ns) % 1000, shift)); - } - else if (buf::TestAccess(pattern).is_same("us", 2)) - { + } else if (buf::TestAccess(pattern).is_same("us", 2)) { SF_TRY(buf::Manip(pattern).forward()); std::uint32_t us = static_cast(std::chrono::time_point_cast(value).time_since_epoch().count()); if (mode == TimePrintMode::Mod) @@ -47,9 +40,7 @@ namespace stream::fmt::detail else if (mode == TimePrintMode::Sub) us = us / 1000; SF_TRY(buf::FMTWriteManip(buffer).write_integer(static_cast(us) % 1000, shift)); - } - else if (buf::TestAccess(pattern).is_same("ms", 2)) - { + } else if (buf::TestAccess(pattern).is_same("ms", 2)) { SF_TRY(buf::Manip(pattern).forward()); std::uint32_t ms = static_cast(std::chrono::time_point_cast(value).time_since_epoch().count()); if (mode == TimePrintMode::Mod) @@ -57,9 +48,7 @@ namespace stream::fmt::detail else if (mode == TimePrintMode::Sub) ms = ms / 1000000; SF_TRY(buf::FMTWriteManip(buffer).write_integer(static_cast(ms) % 1000, shift)); - } - else if (buf::TestAccess(pattern).is_equal_to('s')) - { + } else if (buf::TestAccess(pattern).is_equal_to('s')) { SF_TRY(buf::Manip(pattern).forward()); std::uint32_t sec = static_cast(std::chrono::time_point_cast(value).time_since_epoch().count()); if (mode == TimePrintMode::Mod) @@ -67,21 +56,15 @@ namespace stream::fmt::detail else if (mode == TimePrintMode::Sub) sec = sec / 1000000000; SF_TRY(buf::FMTWriteManip(buffer).write_integer(static_cast(sec) % 1000, shift)); - } - else if (buf::TestAccess(pattern).is_equal_to('m')) - { + } else if (buf::TestAccess(pattern).is_equal_to('m')) { SF_TRY(buf::Manip(pattern).forward()); std::uint32_t min = static_cast(std::chrono::time_point_cast(value).time_since_epoch().count()); - if (mode == TimePrintMode::Mod) - min = min % 60; + if (mode == TimePrintMode::Mod) min = min % 60; SF_TRY(buf::FMTWriteManip(buffer).write_integer(static_cast(min) % 1000, shift)); - } - else if (buf::TestAccess(pattern).is_equal_to('h')) - { + } else if (buf::TestAccess(pattern).is_equal_to('h')) { SF_TRY(buf::Manip(pattern).forward()); std::uint32_t min = static_cast(std::chrono::time_point_cast(value).time_since_epoch().count()); - if (mode == TimePrintMode::Mod) - min = min % 24; + if (mode == TimePrintMode::Mod) min = min % 24; SF_TRY(buf::FMTWriteManip(buffer).write_integer(static_cast(min) % 1000, shift)); } @@ -89,15 +72,14 @@ namespace stream::fmt::detail } template - [[nodiscard]] std::expected WriteTime(const std::chrono::time_point& value, buf::StreamView pattern, buf::FMTStreamIO& buffer) - { - auto view = SF_TRY(buf::TestManip(pattern).ViewExec( - [&] -> std::expected { buf::FMTParamsManip(pattern).param_go_to('%', '#', '/'); return {}; } - )); + [[nodiscard]] std::expected WriteTime(const std::chrono::time_point& value, buf::StreamView pattern, buf::FMTStreamIO& buffer) { + auto view = SF_TRY(buf::TestManip(pattern).ViewExec([&] -> std::expected { + buf::FMTParamsManip(pattern).param_go_to('%', '#', '/'); + return {}; + })); SF_TRY(buf::WriteManip(buffer).fast_write_string(view)); - while (!buf::Access(pattern).is_end_of_string()) - { + while (!buf::Access(pattern).is_end_of_string()) { TimePrintMode mode; if (buf::TestAccess(pattern).is_equal_to('%')) mode = TimePrintMode::Mod; @@ -105,60 +87,53 @@ namespace stream::fmt::detail mode = TimePrintMode::FullTime; else if (buf::TestAccess(pattern).is_equal_to('/')) mode = TimePrintMode::Sub; - + SF_TRY(buf::Manip(pattern).forward()); SF_TRY(write_sub_time_(value, pattern, buffer, mode)); - auto view = SF_TRY(buf::TestManip(pattern).ViewExec( - [&] -> std::expected { buf::FMTParamsManip(pattern).param_go_to('%', '#', '/'); return {}; } - )); + auto view = SF_TRY(buf::TestManip(pattern).ViewExec([&] -> std::expected { + buf::FMTParamsManip(pattern).param_go_to('%', '#', '/'); + return {}; + })); SF_TRY(buf::WriteManip(buffer).fast_write_string(view)); } return {}; } -} +} // namespace stream::fmt::detail -namespace stream::fmt -{ +namespace stream::fmt { template - struct FormatterType, FormatterExecutor> - { - [[nodiscard]] static inline std::expected format(const std::chrono::time_point& t, FormatterExecutor& executor) - { + struct FormatterType, FormatterExecutor> { + [[nodiscard]] static inline std::expected format(const std::chrono::time_point& t, FormatterExecutor& executor) { return detail::WriteTime(t, buf::StreamView(executor.data.specifiers.get_as_text("pattern", "%h:%m:%s.%ms")), executor.ostream); } }; template - struct FormatterType, FormatterExecutor> - { - [[nodiscard]] static inline std::expected format(const std::chrono::duration& t, FormatterExecutor& executor) - { - if (executor.data.specifiers.has("pattern")) - { - return detail::WriteTime( - std::chrono::time_point>(t), - buf::StreamView(executor.data.specifiers.get_as_text("pattern", "%h:%m:%s.%ms")), - executor.ostream - ); + struct FormatterType, FormatterExecutor> { + [[nodiscard]] static inline std::expected format(const std::chrono::duration& t, FormatterExecutor& executor) { + if (executor.data.specifiers.has("pattern")) { + return detail::WriteTime(std::chrono::time_point>(t), + buf::StreamView(executor.data.specifiers.get_as_text("pattern", "%h:%m:%s.%ms")), executor.ostream); } SF_TRY(buf::WriteManip(executor.ostream).fast_write_integer(t.count())); - if constexpr (std::is_same_v, std::chrono::seconds>) - { SF_TRY(buf::ManipIO(executor.ostream).pushback('s')); } - else if constexpr (std::is_same_v, std::chrono::minutes>) - { SF_TRY(buf::ManipIO(executor.ostream).pushback('m')); } - else if constexpr (std::is_same_v, std::chrono::hours>) - { SF_TRY(buf::ManipIO(executor.ostream).pushback('h')); } - else if constexpr (std::is_same_v, std::chrono::milliseconds>) - { SF_TRY(buf::ManipIO(executor.ostream).pushback('m', 's')); } - else if constexpr (std::is_same_v, std::chrono::microseconds>) - { SF_TRY(buf::ManipIO(executor.ostream).pushback('u', 's')); } - else if constexpr (std::is_same_v, std::chrono::nanoseconds>) - { SF_TRY(buf::ManipIO(executor.ostream).pushback('n', 's')); } - + if constexpr (std::is_same_v, std::chrono::seconds>) { + SF_TRY(buf::ManipIO(executor.ostream).pushback('s')); + } else if constexpr (std::is_same_v, std::chrono::minutes>) { + SF_TRY(buf::ManipIO(executor.ostream).pushback('m')); + } else if constexpr (std::is_same_v, std::chrono::hours>) { + SF_TRY(buf::ManipIO(executor.ostream).pushback('h')); + } else if constexpr (std::is_same_v, std::chrono::milliseconds>) { + SF_TRY(buf::ManipIO(executor.ostream).pushback('m', 's')); + } else if constexpr (std::is_same_v, std::chrono::microseconds>) { + SF_TRY(buf::ManipIO(executor.ostream).pushback('u', 's')); + } else if constexpr (std::is_same_v, std::chrono::nanoseconds>) { + SF_TRY(buf::ManipIO(executor.ostream).pushback('n', 's')); + } + return {}; } }; -} +} // namespace stream::fmt diff --git a/src/stream/fmt/serializers/format_stdlib.h b/src/stream/fmt/serializers/format_stdlib.h index bbe3ba37..9ee49160 100644 --- a/src/stream/fmt/serializers/format_stdlib.h +++ b/src/stream/fmt/serializers/format_stdlib.h @@ -7,31 +7,30 @@ #include #include -namespace stream::fmt -{ +namespace stream::fmt { //------------------------------------------// //----------------- String -----------------// //------------------------------------------// template - struct FormatterType, FormatterExecutor> - { - [[nodiscard]] static inline std::expected format(const std::basic_string& t, FormatterExecutor& executor) - { return buf::WriteManip(executor.ostream).fast_write_string(t); } + struct FormatterType, FormatterExecutor> { + [[nodiscard]] static inline std::expected format(const std::basic_string& t, FormatterExecutor& executor) { + return buf::WriteManip(executor.ostream).fast_write_string(t); + } }; template - struct FormatterType, FormatterExecutor> - { - [[nodiscard]] static inline std::expected format(std::basic_string_view t, FormatterExecutor& executor) - { return buf::WriteManip(executor.ostream).fast_write_string(t); } + struct FormatterType, FormatterExecutor> { + [[nodiscard]] static inline std::expected format(std::basic_string_view t, FormatterExecutor& executor) { + return buf::WriteManip(executor.ostream).fast_write_string(t); + } }; template - struct FormatterType, FormatterExecutor> - { - [[nodiscard]] static inline std::expected format(const std::basic_stringstream& t, FormatterExecutor& executor) - { return buf::WriteManip(executor.ostream).fast_write_char_array(t.str(), t.size()); } + struct FormatterType, FormatterExecutor> { + [[nodiscard]] static inline std::expected format(const std::basic_stringstream& t, FormatterExecutor& executor) { + return buf::WriteManip(executor.ostream).fast_write_char_array(t.str(), t.size()); + } }; //------------------------------------------// @@ -40,10 +39,8 @@ namespace stream::fmt // UniquePtr template - struct FormatterType, FormatterExecutor> - { - [[nodiscard]] static inline std::expected format(const std::unique_ptr& t, FormatterExecutor& executor) - { + struct FormatterType, FormatterExecutor> { + [[nodiscard]] static inline std::expected format(const std::unique_ptr& t, FormatterExecutor& executor) { if (executor.data.TrueValue) return FormatterType::format(t.get(), executor); else @@ -55,10 +52,8 @@ namespace stream::fmt // SharedPtr template - struct FormatterType, FormatterExecutor> - { - [[nodiscard]] static inline std::expected format(const std::shared_ptr& t, FormatterExecutor& executor) - { + struct FormatterType, FormatterExecutor> { + [[nodiscard]] static inline std::expected format(const std::shared_ptr& t, FormatterExecutor& executor) { if (executor.data.TrueValue) return FormatterType::format(t.get(), executor); else @@ -70,9 +65,9 @@ namespace stream::fmt // WeakPtr template - struct FormatterType, FormatterExecutor> - { - [[nodiscard]] static inline std::expected format(const std::weak_ptr& t, FormatterExecutor& executor) - { return FormatterType, FormatterExecutor>::format(t.lock(), executor); } + struct FormatterType, FormatterExecutor> { + [[nodiscard]] static inline std::expected format(const std::weak_ptr& t, FormatterExecutor& executor) { + return FormatterType, FormatterExecutor>::format(t.lock(), executor); + } }; -} +} // namespace stream::fmt diff --git a/src/stream/fmt/serializers/parse_chrono.h b/src/stream/fmt/serializers/parse_chrono.h index de36cfab..4f7d8e60 100644 --- a/src/stream/fmt/serializers/parse_chrono.h +++ b/src/stream/fmt/serializers/parse_chrono.h @@ -3,12 +3,6 @@ #include #include "stream/fmt/context/parser_executor/basic_parser_executor.h" -namespace stream::fmt::detail -{ +namespace stream::fmt::detail {} -} - -namespace stream::fmt -{ - -} +namespace stream::fmt {} diff --git a/src/stream/fmt/serializers/parse_stdlib.h b/src/stream/fmt/serializers/parse_stdlib.h index f32691af..3bd27579 100644 --- a/src/stream/fmt/serializers/parse_stdlib.h +++ b/src/stream/fmt/serializers/parse_stdlib.h @@ -6,7 +6,6 @@ #include #include -namespace stream::fmt -{ +namespace stream::fmt { // TODO: } diff --git a/src/stream/fmt/serializers/std_container/FMT_deque.h b/src/stream/fmt/serializers/std_container/FMT_deque.h deleted file mode 100644 index 6f59ef21..00000000 --- a/src/stream/fmt/serializers/std_container/FMT_deque.h +++ /dev/null @@ -1,14 +0,0 @@ -#pragma once - -#include -#include "stream/fmt/context/formatter_executor/formatter_type.h" - -namespace stream::fmt -{ - template - struct FormatterType, FormatterExecutor> - { - [[nodiscard]] static inline std::expected format(const std::deque& t, FormatterExecutor& executor) - { return FormatterType>, FormatterExecutor>::format(t, executor); } - }; -} diff --git a/src/stream/fmt/serializers/std_container/FMT_list.h b/src/stream/fmt/serializers/std_container/FMT_list.h deleted file mode 100644 index 60878f3f..00000000 --- a/src/stream/fmt/serializers/std_container/FMT_list.h +++ /dev/null @@ -1,14 +0,0 @@ -#pragma once - -#include -#include "stream/fmt/context/formatter_executor/formatter_type.h" - -namespace stream::fmt -{ - template - struct FormatterType, FormatterExecutor> - { - [[nodiscard]] static inline std::expected format(const std::list& t, FormatterExecutor& executor) - { return FormatterType>, FormatterExecutor>::format(t, executor); } - }; -} diff --git a/src/stream/fmt/serializers/std_container/FMT_queue.h b/src/stream/fmt/serializers/std_container/FMT_queue.h deleted file mode 100644 index 08be1fc2..00000000 --- a/src/stream/fmt/serializers/std_container/FMT_queue.h +++ /dev/null @@ -1,16 +0,0 @@ -#pragma once - -#include -#include "stream/fmt/context/formatter_executor/formatter_type.h" - -namespace stream::fmt -{ - template - struct FormatterType, FormatterExecutor> - { - [[nodiscard]] static inline std::expected format(const std::queue& t, FormatterExecutor& executor) - { - return std::unexpected(FMTResult::FunctionNotImpl); - } - }; -} diff --git a/src/stream/fmt/serializers/std_container/FMT_set.h b/src/stream/fmt/serializers/std_container/FMT_set.h deleted file mode 100644 index d3d4c312..00000000 --- a/src/stream/fmt/serializers/std_container/FMT_set.h +++ /dev/null @@ -1,21 +0,0 @@ -#pragma once - -#include -#include "stream/fmt/context/formatter_executor/formatter_type.h" - -namespace stream::fmt -{ - template - struct FormatterType, FormatterExecutor> - { - [[nodiscard]] static inline std::expected format(const std::set& t, FormatterExecutor& executor) - { return FormatterType>, FormatterExecutor>::format(t, executor); } - }; - - template - struct FormatterType, FormatterExecutor> - { - [[nodiscard]] static inline std::expected format(const std::multiset& t, FormatterExecutor& executor) - { return FormatterType>, FormatterExecutor>::format(t, executor); } - }; -} diff --git a/src/stream/fmt/serializers/std_container/FMT_vector.h b/src/stream/fmt/serializers/std_container/FMT_vector.h deleted file mode 100644 index 897a7a6a..00000000 --- a/src/stream/fmt/serializers/std_container/FMT_vector.h +++ /dev/null @@ -1,14 +0,0 @@ -#pragma once - -#include -#include "stream/fmt/context/formatter_executor/formatter_type.h" - -namespace stream::fmt -{ - template - struct FormatterType, FormatterExecutor> - { - [[nodiscard]] static inline std::expected format(const std::vector& t, FormatterExecutor& executor) - { return FormatterType>, FormatterExecutor>::format(t, executor); } - }; -} diff --git a/src/stream/fmt/serializers/std_container/FMT_array.h b/src/stream/fmt/serializers/std_container/array.h similarity index 59% rename from src/stream/fmt/serializers/std_container/FMT_array.h rename to src/stream/fmt/serializers/std_container/array.h index a3183f2a..e590546d 100644 --- a/src/stream/fmt/serializers/std_container/FMT_array.h +++ b/src/stream/fmt/serializers/std_container/array.h @@ -1,16 +1,15 @@ #pragma once -#include #include "stream/fmt/context/formatter_executor/formatter_type.h" +#include "stream/fmt/context/formatter_executor/std_enumerable.h" + +#include -namespace stream::fmt -{ +namespace stream::fmt { template - struct FormatterType, FormatterExecutor> - { - [[nodiscard]] static inline std::expected format(const std::array& t, FormatterExecutor& executor) - { + struct FormatterType, FormatterExecutor> { + [[nodiscard]] static std::expected format(const std::array& t, FormatterExecutor& executor) { return FormatterType>, FormatterExecutor>::format(t, executor); } }; -} +} // namespace stream::fmt diff --git a/src/stream/fmt/serializers/std_container/deque.h b/src/stream/fmt/serializers/std_container/deque.h new file mode 100644 index 00000000..5f037951 --- /dev/null +++ b/src/stream/fmt/serializers/std_container/deque.h @@ -0,0 +1,15 @@ +#pragma once + +#include "stream/fmt/context/formatter_executor/formatter_type.h" +#include "stream/fmt/context/formatter_executor/std_enumerable.h" + +#include + +namespace stream::fmt { + template + struct FormatterType, FormatterExecutor> { + [[nodiscard]] static std::expected format(const std::deque& t, FormatterExecutor& executor) { + return FormatterType>, FormatterExecutor>::format(t, executor); + } + }; +} // namespace stream::fmt diff --git a/src/stream/fmt/serializers/std_container/FMT_forward_list.h b/src/stream/fmt/serializers/std_container/forward_list.h similarity index 58% rename from src/stream/fmt/serializers/std_container/FMT_forward_list.h rename to src/stream/fmt/serializers/std_container/forward_list.h index ef7a5992..b585e574 100644 --- a/src/stream/fmt/serializers/std_container/FMT_forward_list.h +++ b/src/stream/fmt/serializers/std_container/forward_list.h @@ -1,16 +1,15 @@ #pragma once -#include #include "stream/fmt/context/formatter_executor/formatter_type.h" +#include "stream/fmt/context/formatter_executor/std_enumerable.h" + +#include -namespace stream::fmt -{ +namespace stream::fmt { template - struct FormatterType, FormatterExecutor> - { - [[nodiscard]] static inline std::expected format(const std::forward_list& t, FormatterExecutor& executor) - { + struct FormatterType, FormatterExecutor> { + [[nodiscard]] static std::expected format(const std::forward_list& t, FormatterExecutor& executor) { return FormatterType>, FormatterExecutor>::format(t, executor); } }; -} +} // namespace stream::fmt diff --git a/src/stream/fmt/serializers/std_container/list.h b/src/stream/fmt/serializers/std_container/list.h new file mode 100644 index 00000000..d52deef1 --- /dev/null +++ b/src/stream/fmt/serializers/std_container/list.h @@ -0,0 +1,15 @@ +#pragma once + +#include "stream/fmt/context/formatter_executor/formatter_type.h" +#include "stream/fmt/context/formatter_executor/std_enumerable.h" + +#include + +namespace stream::fmt { + template + struct FormatterType, FormatterExecutor> { + [[nodiscard]] static std::expected format(const std::list& t, FormatterExecutor& executor) { + return FormatterType>, FormatterExecutor>::format(t, executor); + } + }; +} // namespace stream::fmt diff --git a/src/stream/fmt/serializers/std_container/FMT_map.h b/src/stream/fmt/serializers/std_container/map.h similarity index 55% rename from src/stream/fmt/serializers/std_container/FMT_map.h rename to src/stream/fmt/serializers/std_container/map.h index d676a352..57c725c6 100644 --- a/src/stream/fmt/serializers/std_container/FMT_map.h +++ b/src/stream/fmt/serializers/std_container/map.h @@ -2,26 +2,22 @@ #include #include "stream/fmt/context/formatter_executor/formatter_type.h" +#include "stream/fmt/context/formatter_executor/std_enumerable.h" -#include "FMT_tuple.h" +#include "tuple.h" -namespace stream::fmt -{ +namespace stream::fmt { template - struct FormatterType, FormatterExecutor> - { - [[nodiscard]] static inline std::expected format(const std::map& t, FormatterExecutor& executor) - { + struct FormatterType, FormatterExecutor> { + [[nodiscard]] static std::expected format(const std::map& t, FormatterExecutor& executor) { return FormatterType>, FormatterExecutor>::format(t, executor); } }; template - struct FormatterType, FormatterExecutor> - { - [[nodiscard]] static inline std::expected format(const std::multimap& t, FormatterExecutor& executor) - { + struct FormatterType, FormatterExecutor> { + [[nodiscard]] static std::expected format(const std::multimap& t, FormatterExecutor& executor) { return ormatterType>, FormatterExecutor>::format(t, executor); } }; -} +} // namespace stream::fmt diff --git a/src/stream/fmt/serializers/std_container/queue.h b/src/stream/fmt/serializers/std_container/queue.h new file mode 100644 index 00000000..4f746ea3 --- /dev/null +++ b/src/stream/fmt/serializers/std_container/queue.h @@ -0,0 +1,13 @@ +#pragma once + +#include +#include "stream/fmt/context/formatter_executor/formatter_type.h" + +namespace stream::fmt { + template + struct FormatterType, FormatterExecutor> { + [[nodiscard]] static std::expected format(const std::queue& t, FormatterExecutor& executor) { + return std::unexpected(FMTResult::FunctionNotImpl); + } + }; +} // namespace stream::fmt diff --git a/src/stream/fmt/serializers/std_container/set.h b/src/stream/fmt/serializers/std_container/set.h new file mode 100644 index 00000000..b4abbb15 --- /dev/null +++ b/src/stream/fmt/serializers/std_container/set.h @@ -0,0 +1,22 @@ +#pragma once + +#include "stream/fmt/context/formatter_executor/formatter_type.h" +#include "stream/fmt/context/formatter_executor/std_enumerable.h" + +#include + +namespace stream::fmt { + template + struct FormatterType, FormatterExecutor> { + [[nodiscard]] static std::expected format(const std::set& t, FormatterExecutor& executor) { + return FormatterType>, FormatterExecutor>::format(t, executor); + } + }; + + template + struct FormatterType, FormatterExecutor> { + [[nodiscard]] static std::expected format(const std::multiset& t, FormatterExecutor& executor) { + return FormatterType>, FormatterExecutor>::format(t, executor); + } + }; +} // namespace stream::fmt diff --git a/src/stream/fmt/serializers/std_container/FMT_stack.h b/src/stream/fmt/serializers/std_container/stack.h similarity index 94% rename from src/stream/fmt/serializers/std_container/FMT_stack.h rename to src/stream/fmt/serializers/std_container/stack.h index 3417791e..f36e8079 100644 --- a/src/stream/fmt/serializers/std_container/FMT_stack.h +++ b/src/stream/fmt/serializers/std_container/stack.h @@ -3,8 +3,7 @@ #include #include "stream/fmt/context/formatter_executor/formatter_type.h" -namespace stream::fmt -{ +namespace stream::fmt { /* template struct FormatterType, FormatterExecutor> diff --git a/src/stream/fmt/serializers/std_container/FMT_tuple.h b/src/stream/fmt/serializers/std_container/tuple.h similarity index 61% rename from src/stream/fmt/serializers/std_container/FMT_tuple.h rename to src/stream/fmt/serializers/std_container/tuple.h index 68c70eda..ccfd26a6 100644 --- a/src/stream/fmt/serializers/std_container/FMT_tuple.h +++ b/src/stream/fmt/serializers/std_container/tuple.h @@ -4,64 +4,54 @@ #include #include "stream/fmt/context/formatter_executor/formatter_type.h" -namespace stream::fmt::TupleDetail -{ +namespace stream::fmt::tuple_detail { template using NthTypeOf = typename std::tuple_element>::Type; template - constexpr NthTypeOf& get(Args&&... args) - { + constexpr NthTypeOf& get(Args&&... args) { std::tuple tuple(args...); return std::get(tuple); } template - [[nodiscard]] static inline std::expected TupleFormatRec(FormatterExecutor& executor) - { + [[nodiscard]] static inline std::expected tuple_format_rec(FormatterExecutor& executor) { return {}; } template - [[nodiscard]] static inline std::expected TupleFormatRec(FormatterExecutor& executor, const T& t) - { + [[nodiscard]] static inline std::expected tuple_format_rec(FormatterExecutor& executor, const T& t) { return executor.write_type(t); } template - [[nodiscard]] static inline std::expected TupleFormatRec(FormatterExecutor& executor, const T& t, Args&&... args) - { + [[nodiscard]] static inline std::expected tuple_format_rec(FormatterExecutor& executor, const T& t, Args&&... args) { SF_TRY(executor.write_type(t)); SF_TRY(executor.ostream.pushback(',')); SF_TRY(executor.ostream.pushback(' ')); - return TupleFormatRec(context, args...); + return tuple_format_rec(context, args...); } -} +} // namespace stream::fmt::tuple_detail -namespace stream::fmt -{ +namespace stream::fmt { template - struct FormatterType, FormatterExecutor> - { - [[nodiscard]] static inline std::expected format(const std::tuple& t, FormatterExecutor& executor) - { + struct FormatterType, FormatterExecutor> { + [[nodiscard]] static inline std::expected format(const std::tuple& t, FormatterExecutor& executor) { SF_TRY(executor.ostream.pushback('<')); std::expected err = {}; - std::apply([&context, &err](auto&&... args) - { - auto&& res = TupleDetail::TupleFormatRec(context, args...); - if (not res) - { err = res.error(); } - }, t); + std::apply([&context, &err](auto&&... args) { + auto&& res = tuple_detail::tuple_format_rec(context, args...); + if (not res) { + err = res.error(); + } + }, t); SF_TRY(executor.ostream.pushback('>')); } }; template - struct FormatterType, FormatterExecutor> - { - [[nodiscard]] static inline std::expected format(const std::pair& t, FormatterExecutor& executor) - { + struct FormatterType, FormatterExecutor> { + [[nodiscard]] static inline std::expected format(const std::pair& t, FormatterExecutor& executor) { SF_TRY(executor.ostream.pushback('<')); SF_TRY(executor.write_type(t.first)); SF_TRY(executor.ostream.pushback(':')); @@ -71,4 +61,4 @@ namespace stream::fmt return {}; } }; -} +} // namespace stream::fmt diff --git a/src/stream/fmt/serializers/std_container/FMT_unordered_map.h b/src/stream/fmt/serializers/std_container/unordered_map.h similarity index 82% rename from src/stream/fmt/serializers/std_container/FMT_unordered_map.h rename to src/stream/fmt/serializers/std_container/unordered_map.h index 13928e6f..49ab72c3 100644 --- a/src/stream/fmt/serializers/std_container/FMT_unordered_map.h +++ b/src/stream/fmt/serializers/std_container/unordered_map.h @@ -1,27 +1,23 @@ #pragma once #include "stream/fmt/context/formatter_executor/formatter_type.h" +#include "stream/fmt/context/formatter_executor/std_enumerable.h" #include -#include "FMT_tuple.h" +#include "tuple.h" -namespace stream::fmt -{ +namespace stream::fmt { template - struct FormatterType, FormatterExecutor> - { - [[nodiscard]] static inline std::expected format(const std::unordered_map& t, FormatterExecutor& executor) - { + struct FormatterType, FormatterExecutor> { + [[nodiscard]] static inline std::expected format(const std::unordered_map& t, FormatterExecutor& executor) { return FormatterType>, FormatterExecutor>::format(t, executor); } }; template - struct FormatterType, FormatterExecutor> - { - [[nodiscard]] static inline std::expected format(const std::unordered_multimap& t, FormatterExecutor& executor) - { + struct FormatterType, FormatterExecutor> { + [[nodiscard]] static inline std::expected format(const std::unordered_multimap& t, FormatterExecutor& executor) { return FormatterType>, FormatterExecutor>::format(t, executor); } }; -} +} // namespace stream::fmt diff --git a/src/stream/fmt/serializers/std_container/FMT_unordered_set.h b/src/stream/fmt/serializers/std_container/unordered_set.h similarity index 61% rename from src/stream/fmt/serializers/std_container/FMT_unordered_set.h rename to src/stream/fmt/serializers/std_container/unordered_set.h index f74a6f0e..9aa223a3 100644 --- a/src/stream/fmt/serializers/std_container/FMT_unordered_set.h +++ b/src/stream/fmt/serializers/std_container/unordered_set.h @@ -1,25 +1,22 @@ #pragma once -#include #include "stream/fmt/context/formatter_executor/formatter_type.h" +#include "stream/fmt/context/formatter_executor/std_enumerable.h" + +#include -namespace stream::fmt -{ +namespace stream::fmt { template - struct FormatterType, FormatterExecutor> - { - [[nodiscard]] static inline std::expected format(const std::unordered_set& t, FormatterExecutor& executor) - { + struct FormatterType, FormatterExecutor> { + [[nodiscard]] static std::expected format(const std::unordered_set& t, FormatterExecutor& executor) { return FormatterType>, FormatterExecutor>::format(t, executor); } }; template - struct FormatterType, FormatterExecutor> - { - [[nodiscard]] static inline std::expected format(const std::unordered_multiset& t, FormatterExecutor& executor) - { + struct FormatterType, FormatterExecutor> { + [[nodiscard]] static std::expected format(const std::unordered_multiset& t, FormatterExecutor& executor) { return FormatterType>, FormatterExecutor>::format(t, executor); } }; -} +} // namespace stream::fmt diff --git a/src/stream/fmt/serializers/std_container/vector.h b/src/stream/fmt/serializers/std_container/vector.h new file mode 100644 index 00000000..a38ecc32 --- /dev/null +++ b/src/stream/fmt/serializers/std_container/vector.h @@ -0,0 +1,15 @@ +#pragma once + +#include "stream/fmt/context/formatter_executor/formatter_type.h" +#include "stream/fmt/context/formatter_executor/std_enumerable.h" + +#include + +namespace stream::fmt { + template + struct FormatterType, FormatterExecutor> { + [[nodiscard]] static inline std::expected format(const std::vector& t, FormatterExecutor& executor) { + return FormatterType>, FormatterExecutor>::format(t, executor); + } + }; +} // namespace stream::fmt diff --git a/src/stream/fmt/text_properties/base_text_properties.h b/src/stream/fmt/text_properties/base_text_properties.h index 2d6bf94c..37d47c82 100644 --- a/src/stream/fmt/text_properties/base_text_properties.h +++ b/src/stream/fmt/text_properties/base_text_properties.h @@ -4,13 +4,9 @@ // According to : https://en.wikipedia.org/wiki/ANSI_escape_code -namespace stream::fmt::detail -{ - struct TextProperties - { - struct ResetProperties - { - }; +namespace stream::fmt::detail { + struct TextProperties { + struct ResetProperties {}; struct TextColor; struct TextStyle; @@ -18,4 +14,4 @@ namespace stream::fmt::detail struct Properties; }; -} +} // namespace stream::fmt::detail diff --git a/src/stream/fmt/text_properties/text_properties.h b/src/stream/fmt/text_properties/text_properties.h index 9faeefc6..64da2cb3 100644 --- a/src/stream/fmt/text_properties/text_properties.h +++ b/src/stream/fmt/text_properties/text_properties.h @@ -4,17 +4,14 @@ #include "text_properties_front.h" #include "text_properties_style.h" -namespace stream::fmt::detail -{ - struct TextProperties::Properties - { +namespace stream::fmt::detail { + struct TextProperties::Properties { TextProperties::TextColor::Color color; TextProperties::TextStyle::Style style; TextProperties::TextFront::Front front; }; - inline bool operator==(const TextProperties::Properties& lhs, const TextProperties::Properties& rhs) - { + inline bool operator==(const TextProperties::Properties& lhs, const TextProperties::Properties& rhs) { return lhs.color == rhs.color && lhs.style == rhs.style && lhs.front == rhs.front; } -} +} // namespace stream::fmt::detail diff --git a/src/stream/fmt/text_properties/text_properties_color.h b/src/stream/fmt/text_properties/text_properties_color.h index dfea46e6..17be7d65 100644 --- a/src/stream/fmt/text_properties/text_properties_color.h +++ b/src/stream/fmt/text_properties/text_properties_color.h @@ -2,13 +2,9 @@ #include "base_text_properties.h" -namespace stream::fmt::detail -{ - struct TextProperties::TextColor - { - struct reset_color - { - }; +namespace stream::fmt::detail { + struct TextProperties::TextColor { + struct reset_color {}; enum class BasicColorFG : std::uint8_t; enum class BasicColorBG : std::uint8_t; @@ -34,8 +30,7 @@ namespace stream::fmt::detail struct Color; }; - enum class TextProperties::TextColor::BasicColorFG : std::uint8_t - { + enum class TextProperties::TextColor::BasicColorFG : std::uint8_t { Black = 30, Red, Green, @@ -60,8 +55,7 @@ namespace stream::fmt::detail BaseBStep = BrightBlack }; - enum class TextProperties::TextColor::BasicColorBG : std::uint8_t - { + enum class TextProperties::TextColor::BasicColorBG : std::uint8_t { Black = 40, Red, Green, @@ -86,19 +80,15 @@ namespace stream::fmt::detail BaseBStep = BrightBlack, }; - struct TextProperties::TextColor::BasicColor - { + struct TextProperties::TextColor::BasicColor { constexpr BasicColor(TextProperties::TextColor::BasicColorFG fg = TextProperties::TextColor::BasicColorFG::Default, TextProperties::TextColor::BasicColorBG bg = TextProperties::TextColor::BasicColorBG::Default) - : fg(fg) - , bg(bg) - {} + : fg(fg), bg(bg) {} TextProperties::TextColor::BasicColorFG fg; TextProperties::TextColor::BasicColorBG bg; }; - struct TextProperties::TextColor::BaseColorCube - { + struct TextProperties::TextColor::BaseColorCube { public: static inline constexpr std::uint8_t Black = 0; static inline constexpr std::uint8_t Red = 1; @@ -132,8 +122,7 @@ namespace stream::fmt::detail static inline constexpr std::uint8_t Default = 0; public: - enum class type : std::uint8_t - { + enum class type : std::uint8_t { Normal, Bright, Cube666, @@ -144,21 +133,22 @@ namespace stream::fmt::detail std::uint8_t color; public: - std::uint8_t get_color() const { return color; } - std::uint8_t get_color_ref() { return color; } - std::uint8_t get_color_ref() const { return color; } + std::uint8_t get_color() const { + return color; + } + std::uint8_t get_color_ref() { + return color; + } + std::uint8_t get_color_ref() const { + return color; + } public: - constexpr BaseColorCube(const std::uint8_t color) - : color(color) - {} + constexpr BaseColorCube(const std::uint8_t color) : color(color) {} - constexpr BaseColorCube() - : color(0) - {} + constexpr BaseColorCube() : color(0) {} - type GetType() - { + type GetType() { if (color >= MinNormalColor && color <= MaxNormalColor) return type::Normal; else if (color >= MinBrightColor && color <= MaxBrightColor) @@ -170,248 +160,187 @@ namespace stream::fmt::detail return type::Normal; } - static BaseColorCube MakeNormalColor(std::uint8_t value) - { + static BaseColorCube MakeNormalColor(std::uint8_t value) { if (value > MaxNormalColor) value -= MinBrightColor; if (value > MaxNormalColor) value = MaxNormalColor; return BaseColorCube(value); } - static BaseColorCube MakeBrightColor(std::uint8_t value) - { + static BaseColorCube MakeBrightColor(std::uint8_t value) { if (value < MinBrightColor) value += MinBrightColor; if (value > MaxBrightColor) value = MaxBrightColor; return BaseColorCube(value); } - static BaseColorCube Make666CubeColor255(const std::uint8_t r, const std::uint8_t g, const std::uint8_t b) - { + static BaseColorCube Make666CubeColor255(const std::uint8_t r, const std::uint8_t g, const std::uint8_t b) { return Make666CubeColor5(static_cast((static_cast(r) / 255) * 5), static_cast((static_cast(g) / 255) * 5), static_cast((static_cast(b) / 255) * 5)); } - static BaseColorCube Make666CubeColor5(std::uint8_t r, std::uint8_t g, std::uint8_t b) - { + static BaseColorCube Make666CubeColor5(std::uint8_t r, std::uint8_t g, std::uint8_t b) { if (r > 5) r = 5; if (g > 5) g = 5; if (b > 5) b = 5; return BaseColorCube(Min666CubeColor + 36 * r + 6 * g + b); } - static BaseColorCube MakeGrayscaleColor255(const std::uint8_t value) { return MakeGrayscaleColor24(static_cast(static_cast(value) / 255) * 24); } + static BaseColorCube MakeGrayscaleColor255(const std::uint8_t value) { + return MakeGrayscaleColor24(static_cast(static_cast(value) / 255) * 24); + } - static BaseColorCube MakeGrayscaleColor24(std::uint8_t value) - { + static BaseColorCube MakeGrayscaleColor24(std::uint8_t value) { if (value > 24) value = 24; return BaseColorCube(MinGrayscale + value); } }; // No need of virtual destructor since ColorCubeFG is purely a renaming of BaseColorCube - struct TextProperties::TextColor::ColorCubeFG : public TextProperties::TextColor::BaseColorCube - { + struct TextProperties::TextColor::ColorCubeFG : public TextProperties::TextColor::BaseColorCube { public: - constexpr explicit ColorCubeFG() - : TextProperties::TextColor::BaseColorCube() - {} - constexpr explicit ColorCubeFG(const std::uint8_t color) - : TextProperties::TextColor::BaseColorCube(color) - {} - constexpr ColorCubeFG(const TextProperties::TextColor::BaseColorCube& color) - : TextProperties::TextColor::BaseColorCube(color) - {} + constexpr explicit ColorCubeFG() : TextProperties::TextColor::BaseColorCube() {} + constexpr explicit ColorCubeFG(const std::uint8_t color) : TextProperties::TextColor::BaseColorCube(color) {} + constexpr ColorCubeFG(const TextProperties::TextColor::BaseColorCube& color) : TextProperties::TextColor::BaseColorCube(color) {} public: - static ColorCubeFG MakeNormalColor(const std::uint8_t value) { return static_cast(TextProperties::TextColor::BaseColorCube::MakeNormalColor(value)); } + static ColorCubeFG MakeNormalColor(const std::uint8_t value) { + return static_cast(TextProperties::TextColor::BaseColorCube::MakeNormalColor(value)); + } - static ColorCubeFG MakeBrightColor(const std::uint8_t value) { return static_cast(TextProperties::TextColor::BaseColorCube::MakeBrightColor(value)); } + static ColorCubeFG MakeBrightColor(const std::uint8_t value) { + return static_cast(TextProperties::TextColor::BaseColorCube::MakeBrightColor(value)); + } - static ColorCubeFG Make666CubeColor255(const std::uint8_t r, const std::uint8_t g, const std::uint8_t b) - { + static ColorCubeFG Make666CubeColor255(const std::uint8_t r, const std::uint8_t g, const std::uint8_t b) { return static_cast(TextProperties::TextColor::BaseColorCube::Make666CubeColor255(r, g, b)); } - static ColorCubeFG Make666CubeColor5(const std::uint8_t r, const std::uint8_t g, const std::uint8_t b) - { + static ColorCubeFG Make666CubeColor5(const std::uint8_t r, const std::uint8_t g, const std::uint8_t b) { return static_cast(TextProperties::TextColor::BaseColorCube::Make666CubeColor5(r, g, b)); } - static ColorCubeFG MakeGrayscaleColor255(const std::uint8_t value) - { + static ColorCubeFG MakeGrayscaleColor255(const std::uint8_t value) { return static_cast(TextProperties::TextColor::BaseColorCube::MakeGrayscaleColor255(value)); } - static ColorCubeFG MakeGrayscaleColor24(const std::uint8_t value) - { + static ColorCubeFG MakeGrayscaleColor24(const std::uint8_t value) { return static_cast(TextProperties::TextColor::BaseColorCube::MakeGrayscaleColor24(value)); } }; // No need of virtual destructor since ColorCubeBG is purely a renaming of BaseColorCube - struct TextProperties::TextColor::ColorCubeBG : public TextProperties::TextColor::BaseColorCube - { - constexpr explicit ColorCubeBG() - : TextProperties::TextColor::BaseColorCube() - {} - constexpr explicit ColorCubeBG(const std::uint8_t color) - : TextProperties::TextColor::BaseColorCube(color) - {} - constexpr ColorCubeBG(const TextProperties::TextColor::BaseColorCube& color) - : TextProperties::TextColor::BaseColorCube(color) - {} + struct TextProperties::TextColor::ColorCubeBG : public TextProperties::TextColor::BaseColorCube { + constexpr explicit ColorCubeBG() : TextProperties::TextColor::BaseColorCube() {} + constexpr explicit ColorCubeBG(const std::uint8_t color) : TextProperties::TextColor::BaseColorCube(color) {} + constexpr ColorCubeBG(const TextProperties::TextColor::BaseColorCube& color) : TextProperties::TextColor::BaseColorCube(color) {} public: - static TextProperties::TextColor::ColorCubeBG MakeNormalColor(const std::uint8_t value) - { + static TextProperties::TextColor::ColorCubeBG MakeNormalColor(const std::uint8_t value) { return static_cast(TextProperties::TextColor::BaseColorCube::MakeNormalColor(value)); } - static TextProperties::TextColor::ColorCubeBG MakeBrightColor(const std::uint8_t value) - { + static TextProperties::TextColor::ColorCubeBG MakeBrightColor(const std::uint8_t value) { return static_cast(TextProperties::TextColor::BaseColorCube::MakeBrightColor(value)); } - static TextProperties::TextColor::ColorCubeBG Make666CubeColor255(const std::uint8_t r, const std::uint8_t g, const std::uint8_t b) - { + static TextProperties::TextColor::ColorCubeBG Make666CubeColor255(const std::uint8_t r, const std::uint8_t g, const std::uint8_t b) { return static_cast(TextProperties::TextColor::BaseColorCube::Make666CubeColor255(r, g, b)); } - static TextProperties::TextColor::ColorCubeBG Make666CubeColor5(const std::uint8_t r, const std::uint8_t g, const std::uint8_t b) - { + static TextProperties::TextColor::ColorCubeBG Make666CubeColor5(const std::uint8_t r, const std::uint8_t g, const std::uint8_t b) { return static_cast(TextProperties::TextColor::BaseColorCube::Make666CubeColor5(r, g, b)); } - static TextProperties::TextColor::ColorCubeBG MakeGrayscaleColor255(const std::uint8_t value) - { + static TextProperties::TextColor::ColorCubeBG MakeGrayscaleColor255(const std::uint8_t value) { return static_cast(TextProperties::TextColor::BaseColorCube::MakeGrayscaleColor255(value)); } - static TextProperties::TextColor::ColorCubeBG MakeGrayscaleColor24(const std::uint8_t value) - { + static TextProperties::TextColor::ColorCubeBG MakeGrayscaleColor24(const std::uint8_t value) { return static_cast(TextProperties::TextColor::BaseColorCube::MakeGrayscaleColor24(value)); } }; - inline bool operator==(const TextProperties::TextColor::BaseColorCube& lhs, const TextProperties::TextColor::BaseColorCube& rhs) - { + inline bool operator==(const TextProperties::TextColor::BaseColorCube& lhs, const TextProperties::TextColor::BaseColorCube& rhs) { return lhs.color == rhs.color; } - struct TextProperties::TextColor::ColorCube - { - constexpr ColorCube() - : fg() - , bg() - {} + struct TextProperties::TextColor::ColorCube { + constexpr ColorCube() : fg(), bg() {} - constexpr ColorCube(const TextProperties::TextColor::ColorCubeFG& fg) - : fg(fg) - , bg() - {} + constexpr ColorCube(const TextProperties::TextColor::ColorCubeFG& fg) : fg(fg), bg() {} - constexpr ColorCube(const TextProperties::TextColor::ColorCubeFG& fg, const TextProperties::TextColor::ColorCubeBG& bg) - : fg(fg) - , bg(bg) - {} + constexpr ColorCube(const TextProperties::TextColor::ColorCubeFG& fg, const TextProperties::TextColor::ColorCubeBG& bg) : fg(fg), bg(bg) {} TextProperties::TextColor::ColorCubeFG fg; TextProperties::TextColor::ColorCubeBG bg; }; - struct TextProperties::TextColor::BaseColor24b - { - constexpr BaseColor24b(std::uint8_t r, std::uint8_t g, std::uint8_t b) - : r(r) - , g(g) - , b(b) - {} + struct TextProperties::TextColor::BaseColor24b { + constexpr BaseColor24b(std::uint8_t r, std::uint8_t g, std::uint8_t b) : r(r), g(g), b(b) {} std::uint8_t r, g, b; }; - inline bool operator==(const TextProperties::TextColor::BaseColor24b& lhs, const TextProperties::TextColor::BaseColor24b& rhs) - { + inline bool operator==(const TextProperties::TextColor::BaseColor24b& lhs, const TextProperties::TextColor::BaseColor24b& rhs) { return lhs.r == rhs.r && lhs.g == rhs.g && lhs.b == rhs.b; } // No need of virtual destructor since Color24bFG is purely a renaming of BaseColor24b - struct TextProperties::TextColor::Color24bFG : public TextProperties::TextColor::BaseColor24b - { - constexpr Color24bFG(std::uint8_t r = 255, std::uint8_t g = 255, std::uint8_t b = 255) - : TextProperties::TextColor::BaseColor24b(r, g, b) - {} + struct TextProperties::TextColor::Color24bFG : public TextProperties::TextColor::BaseColor24b { + constexpr Color24bFG(std::uint8_t r = 255, std::uint8_t g = 255, std::uint8_t b = 255) : TextProperties::TextColor::BaseColor24b(r, g, b) {} }; // No need of virtual destructor since Color24bBG is purely a renaming of BaseColor24b - struct TextProperties::TextColor::Color24bBG : public TextProperties::TextColor::BaseColor24b - { - constexpr Color24bBG(std::uint8_t r = 0, std::uint8_t g = 0, std::uint8_t b = 0) - : TextProperties::TextColor::BaseColor24b(r, g, b) - {} + struct TextProperties::TextColor::Color24bBG : public TextProperties::TextColor::BaseColor24b { + constexpr Color24bBG(std::uint8_t r = 0, std::uint8_t g = 0, std::uint8_t b = 0) : TextProperties::TextColor::BaseColor24b(r, g, b) {} }; - struct TextProperties::TextColor::Color24b - { + struct TextProperties::TextColor::Color24b { constexpr Color24b(const TextProperties::TextColor::Color24bFG&& fg_ = TextProperties::TextColor::Color24bFG(), const TextProperties::TextColor::Color24bBG&& bg_ = TextProperties::TextColor::Color24bBG()) - : fg(fg_) - , bg(bg_) - {} + : fg(fg_), bg(bg_) {} TextProperties::TextColor::Color24bFG fg; TextProperties::TextColor::Color24bBG bg; }; - inline bool operator==(const TextProperties::TextColor::Color24b& lhs, const TextProperties::TextColor::Color24b& rhs) - { + inline bool operator==(const TextProperties::TextColor::Color24b& lhs, const TextProperties::TextColor::Color24b& rhs) { return lhs.fg == rhs.fg && lhs.bg == rhs.bg; } - enum class TextProperties::TextColor::ColorType : std::uint8_t - { + enum class TextProperties::TextColor::ColorType : std::uint8_t { BasicColor, ColorCube, Color24b }; - union TextProperties::TextColor::ColorFGData - { - constexpr ColorFGData() - : basic_color{TextProperties::TextColor::BasicColorFG::Default} - {} + union TextProperties::TextColor::ColorFGData { + constexpr ColorFGData() : basic_color{TextProperties::TextColor::BasicColorFG::Default} {} TextProperties::TextColor::BasicColorFG basic_color; TextProperties::TextColor::ColorCubeFG color_cube; TextProperties::TextColor::Color24bFG color24b; }; - union TextProperties::TextColor::ColorBGData - { - constexpr ColorBGData() - : basic_color{TextProperties::TextColor::BasicColorBG::Default} - {} + union TextProperties::TextColor::ColorBGData { + constexpr ColorBGData() : basic_color{TextProperties::TextColor::BasicColorBG::Default} {} TextProperties::TextColor::BasicColorBG basic_color; TextProperties::TextColor::ColorCubeBG color_cube; TextProperties::TextColor::Color24bBG color24b; }; - struct TextProperties::TextColor::ColorFG - { + struct TextProperties::TextColor::ColorFG { TextProperties::TextColor::ColorFGData data; TextProperties::TextColor::ColorType type{TextProperties::TextColor::ColorType::BasicColor}; }; - struct TextProperties::TextColor::ColorBG - { + struct TextProperties::TextColor::ColorBG { TextProperties::TextColor::ColorBGData data; TextProperties::TextColor::ColorType type{TextProperties::TextColor::ColorType::BasicColor}; }; - inline bool operator==(const TextProperties::TextColor::ColorFG& lhs, const TextProperties::TextColor::ColorFG& rhs) - { + inline bool operator==(const TextProperties::TextColor::ColorFG& lhs, const TextProperties::TextColor::ColorFG& rhs) { if (lhs.type != rhs.type) return false; - switch (lhs.type) - { + switch (lhs.type) { case TextProperties::TextColor::ColorType::BasicColor: return lhs.data.basic_color == rhs.data.basic_color; case TextProperties::TextColor::ColorType::ColorCube: @@ -422,11 +351,9 @@ namespace stream::fmt::detail return false; } - inline bool operator==(const TextProperties::TextColor::ColorBG& lhs, const TextProperties::TextColor::ColorBG& rhs) - { + inline bool operator==(const TextProperties::TextColor::ColorBG& lhs, const TextProperties::TextColor::ColorBG& rhs) { if (lhs.type != rhs.type) return false; - switch (lhs.type) - { + switch (lhs.type) { case TextProperties::TextColor::ColorType::BasicColor: return lhs.data.basic_color == rhs.data.basic_color; case TextProperties::TextColor::ColorType::ColorCube: @@ -440,104 +367,111 @@ namespace stream::fmt::detail bool operator==(const TextProperties::TextColor::Color& lhs, const TextProperties::TextColor::Color& rhs); // Manage only the text color / the underline color will be manage by the TextProperties::TextStyle::UnderlineColor - struct TextProperties::TextColor::Color - { + struct TextProperties::TextColor::Color { public: - constexpr Color() - : fg() - , bg() - {} + constexpr Color() : fg(), bg() {} public: TextProperties::TextColor::ColorFG fg; TextProperties::TextColor::ColorBG bg; public: - void modify_reset() - { + void modify_reset() { fg = TextProperties::TextColor::ColorFG{}; bg = TextProperties::TextColor::ColorBG{}; } - void apply(const TextProperties::TextColor::Color& given) { *this = given; } + void apply(const TextProperties::TextColor::Color& given) { + *this = given; + } - void apply(const TextProperties::TextColor::reset_color&) { modify_reset(); } - void apply(const TextProperties::TextColor::BasicColorFG& given) - { - fg.type = TextProperties::TextColor::ColorType::BasicColor; + void apply(const TextProperties::TextColor::reset_color&) { + modify_reset(); + } + void apply(const TextProperties::TextColor::BasicColorFG& given) { + fg.type = TextProperties::TextColor::ColorType::BasicColor; fg.data.basic_color = given; } - void apply(const TextProperties::TextColor::BasicColorBG& given) - { - bg.type = TextProperties::TextColor::ColorType::BasicColor; + void apply(const TextProperties::TextColor::BasicColorBG& given) { + bg.type = TextProperties::TextColor::ColorType::BasicColor; bg.data.basic_color = given; } - void apply(const TextProperties::TextColor::BasicColor& given) - { + void apply(const TextProperties::TextColor::BasicColor& given) { apply(given.fg); apply(given.bg); } - void apply(const TextProperties::TextColor::ColorCubeFG& given) - { - fg.type = TextProperties::TextColor::ColorType::ColorCube; + void apply(const TextProperties::TextColor::ColorCubeFG& given) { + fg.type = TextProperties::TextColor::ColorType::ColorCube; fg.data.color_cube = given; } - void apply(const TextProperties::TextColor::ColorCubeBG& given) - { - bg.type = TextProperties::TextColor::ColorType::ColorCube; + void apply(const TextProperties::TextColor::ColorCubeBG& given) { + bg.type = TextProperties::TextColor::ColorType::ColorCube; bg.data.color_cube = given; } - void apply(const TextProperties::TextColor::ColorCube& given) - { + void apply(const TextProperties::TextColor::ColorCube& given) { apply(given.fg); apply(given.bg); } - void apply(const TextProperties::TextColor::Color24bFG& given) - { + void apply(const TextProperties::TextColor::Color24bFG& given) { fg.type = TextProperties::TextColor::ColorType::Color24b; fg.data.color24b = given; } - void apply(const TextProperties::TextColor::Color24bBG& given) - { + void apply(const TextProperties::TextColor::Color24bBG& given) { bg.type = TextProperties::TextColor::ColorType::Color24b; bg.data.color24b = given; } - void apply(const TextProperties::TextColor::Color24b& given) - { + void apply(const TextProperties::TextColor::Color24b& given) { apply(given.fg); apply(given.bg); } public: - bool need_modif(const TextProperties::TextColor::reset_color&) { return true; } - - bool need_modif(const TextProperties::TextColor::Color& given) { return *this != given; } - - bool need_modif(const TextProperties::TextColor::BasicColorFG& given) { return fg.type != TextProperties::TextColor::ColorType::BasicColor || fg.data.basic_color != given; } - bool need_modif(const TextProperties::TextColor::BasicColorBG& given) { return bg.type != TextProperties::TextColor::ColorType::BasicColor || bg.data.basic_color != given; } - bool need_modif(const TextProperties::TextColor::BasicColor& given) { return need_modif(given.fg) || need_modif(given.bg); } - bool need_modif(const TextProperties::TextColor::ColorCubeFG& given) { return fg.type != TextProperties::TextColor::ColorType::ColorCube || fg.data.color_cube != given; } - bool need_modif(const TextProperties::TextColor::ColorCubeBG& given) { return bg.type != TextProperties::TextColor::ColorType::ColorCube || bg.data.color_cube != given; } - bool need_modif(const TextProperties::TextColor::ColorCube& given) { return need_modif(given.fg) || need_modif(given.bg); } - bool need_modif(const TextProperties::TextColor::Color24bFG& given) { return fg.type != TextProperties::TextColor::ColorType::Color24b || fg.data.color24b != given; } - bool need_modif(const TextProperties::TextColor::Color24bBG& given) { return bg.type != TextProperties::TextColor::ColorType::Color24b || bg.data.color24b != given; } - bool need_modif(const TextProperties::TextColor::Color24b& given) { return need_modif(given.fg) || need_modif(given.bg); } + bool need_modif(const TextProperties::TextColor::reset_color&) { + return true; + } + + bool need_modif(const TextProperties::TextColor::Color& given) { + return *this != given; + } + + bool need_modif(const TextProperties::TextColor::BasicColorFG& given) { + return fg.type != TextProperties::TextColor::ColorType::BasicColor || fg.data.basic_color != given; + } + bool need_modif(const TextProperties::TextColor::BasicColorBG& given) { + return bg.type != TextProperties::TextColor::ColorType::BasicColor || bg.data.basic_color != given; + } + bool need_modif(const TextProperties::TextColor::BasicColor& given) { + return need_modif(given.fg) || need_modif(given.bg); + } + bool need_modif(const TextProperties::TextColor::ColorCubeFG& given) { + return fg.type != TextProperties::TextColor::ColorType::ColorCube || fg.data.color_cube != given; + } + bool need_modif(const TextProperties::TextColor::ColorCubeBG& given) { + return bg.type != TextProperties::TextColor::ColorType::ColorCube || bg.data.color_cube != given; + } + bool need_modif(const TextProperties::TextColor::ColorCube& given) { + return need_modif(given.fg) || need_modif(given.bg); + } + bool need_modif(const TextProperties::TextColor::Color24bFG& given) { + return fg.type != TextProperties::TextColor::ColorType::Color24b || fg.data.color24b != given; + } + bool need_modif(const TextProperties::TextColor::Color24bBG& given) { + return bg.type != TextProperties::TextColor::ColorType::Color24b || bg.data.color24b != given; + } + bool need_modif(const TextProperties::TextColor::Color24b& given) { + return need_modif(given.fg) || need_modif(given.bg); + } }; - inline bool operator==(const TextProperties::TextColor::Color& lhs, const TextProperties::TextColor::Color& rhs) - { + inline bool operator==(const TextProperties::TextColor::Color& lhs, const TextProperties::TextColor::Color& rhs) { return lhs.fg == rhs.fg && lhs.bg == rhs.bg; } template - concept text_properties_color_can_apply = requires(const T& value, TextProperties::TextColor::Color& data) - { - data.apply(value); - }; + concept text_properties_color_can_apply = requires(const T& value, TextProperties::TextColor::Color& data) { data.apply(value); }; template - struct TextPropertiesColorIsApplyType - { + struct TextPropertiesColorIsApplyType { using BaseType = get_base_type; static constexpr bool value = std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || @@ -549,4 +483,4 @@ namespace stream::fmt::detail template concept text_properties_color_is_apply = TextPropertiesColorIsApplyType::value; -} +} // namespace stream::fmt::detail diff --git a/src/stream/fmt/text_properties/text_properties_front.h b/src/stream/fmt/text_properties/text_properties_front.h index 60aed559..240d523b 100644 --- a/src/stream/fmt/text_properties/text_properties_front.h +++ b/src/stream/fmt/text_properties/text_properties_front.h @@ -2,20 +2,15 @@ #include "base_text_properties.h" -namespace stream::fmt::detail -{ - struct TextProperties::TextFront - { - struct reset_front - { - }; +namespace stream::fmt::detail { + struct TextProperties::TextFront { + struct reset_front {}; struct FrontID; struct Front; }; - struct TextProperties::TextFront::FrontID - { + struct TextProperties::TextFront::FrontID { public: static inline constexpr std::uint8_t DefaultFrontID = 10; static inline constexpr std::uint8_t MinFrontID = 10; @@ -24,57 +19,64 @@ namespace stream::fmt::detail public: std::uint8_t ID; - constexpr FrontID() - : ID(DefaultFrontID) - {} - constexpr FrontID(std::uint8_t id) - : ID(id) - {} + constexpr FrontID() : ID(DefaultFrontID) {} + constexpr FrontID(std::uint8_t id) : ID(id) {} public: - constexpr bool operator==(const TextProperties::TextFront::FrontID& other) const { return ID == other.ID; } - constexpr bool IsValid() const { return ID > MinFrontID && ID < MaxFrontID; } + constexpr bool operator==(const TextProperties::TextFront::FrontID& other) const { + return ID == other.ID; + } + constexpr bool IsValid() const { + return ID > MinFrontID && ID < MaxFrontID; + } }; bool operator==(const TextProperties::TextFront::Front& lhs, const TextProperties::TextFront::Front& rhs); - struct TextProperties::TextFront::Front - { + struct TextProperties::TextFront::Front { public: constexpr Front(const TextProperties::TextFront::FrontID frontId = TextProperties::TextFront::FrontID::DefaultFrontID) - : CurrentID(frontId.IsValid() ? frontId : TextProperties::TextFront::FrontID::DefaultFrontID) - {} + : CurrentID(frontId.IsValid() ? frontId : TextProperties::TextFront::FrontID::DefaultFrontID) {} public: FrontID CurrentID; public: - void modify_reset() { *this = Front{}; } - - void apply(const TextProperties::TextFront::reset_front&) { modify_reset(); } - void apply(const TextProperties::TextFront::Front& given) { *this = given; } - void apply(const TextProperties::TextFront::FrontID& given) { CurrentID = given; } + void modify_reset() { + *this = Front{}; + } + + void apply(const TextProperties::TextFront::reset_front&) { + modify_reset(); + } + void apply(const TextProperties::TextFront::Front& given) { + *this = given; + } + void apply(const TextProperties::TextFront::FrontID& given) { + CurrentID = given; + } public: - bool need_modif(const TextProperties::TextFront::reset_front&) { return true; } - bool need_modif(const TextProperties::TextFront::Front& given) { return *this != given; } - bool need_modif(const TextProperties::TextFront::FrontID& given) { return CurrentID != given; } + bool need_modif(const TextProperties::TextFront::reset_front&) { + return true; + } + bool need_modif(const TextProperties::TextFront::Front& given) { + return *this != given; + } + bool need_modif(const TextProperties::TextFront::FrontID& given) { + return CurrentID != given; + } }; - inline bool operator==(const TextProperties::TextFront::Front& lhs, const TextProperties::TextFront::Front& rhs) - { + inline bool operator==(const TextProperties::TextFront::Front& lhs, const TextProperties::TextFront::Front& rhs) { return lhs.CurrentID == rhs.CurrentID; } template - concept text_properties_front_can_apply = requires(const T& value, TextProperties::TextFront::Front& data) - { - data.apply(value); - }; + concept text_properties_front_can_apply = requires(const T& value, TextProperties::TextFront::Front& data) { data.apply(value); }; template - struct TextPropertiesFrontIsapplyType - { + struct TextPropertiesFrontIsapplyType { using BaseType = get_base_type; static constexpr bool value = std::is_same_v || std::is_same_v || std::is_same_v; @@ -82,4 +84,4 @@ namespace stream::fmt::detail template concept TextPropertiesFrontIsapply = TextPropertiesFrontIsapplyType::value; -} +} // namespace stream::fmt::detail diff --git a/src/stream/fmt/text_properties/text_properties_style.h b/src/stream/fmt/text_properties/text_properties_style.h index 7cd54bbb..f12133ed 100644 --- a/src/stream/fmt/text_properties/text_properties_style.h +++ b/src/stream/fmt/text_properties/text_properties_style.h @@ -3,13 +3,9 @@ #include "base_text_properties.h" #include "text_properties_color.h" -namespace stream::fmt::detail -{ - struct TextProperties::TextStyle - { - struct reset_style - { - }; +namespace stream::fmt::detail { + struct TextProperties::TextStyle { + struct reset_style {}; enum class Intensity : std::uint8_t; enum class Italic : std::uint8_t; @@ -23,21 +19,18 @@ namespace stream::fmt::detail struct Style; }; - enum class TextProperties::TextStyle::Intensity : std::uint8_t - { + enum class TextProperties::TextStyle::Intensity : std::uint8_t { Bold = 1, Dim = 2, Normal = 22 }; - enum class TextProperties::TextStyle::Italic : std::uint8_t - { + enum class TextProperties::TextStyle::Italic : std::uint8_t { enable = 3, Disable = 23 }; - enum class TextProperties::TextStyle::Underline : std::uint8_t - { + enum class TextProperties::TextStyle::Underline : std::uint8_t { Underlined = 4, DoubleUnerlined = 21, // may only disable bold Disable = 24, @@ -45,21 +38,18 @@ namespace stream::fmt::detail SelectUnderlinedColor = 254 }; - enum class TextProperties::TextStyle::Blink : std::uint8_t - { + enum class TextProperties::TextStyle::Blink : std::uint8_t { SlowBlink = 5, FastBlink = 6, Disable = 25 }; - enum class TextProperties::TextStyle::Inverted : std::uint8_t - { + enum class TextProperties::TextStyle::Inverted : std::uint8_t { enable = 7, Disable = 27 }; - enum class TextProperties::TextStyle::Ideogram : std::uint8_t - { + enum class TextProperties::TextStyle::Ideogram : std::uint8_t { Underlined = 60, DoubleUnderlined = 61, Overlined = 62, @@ -68,15 +58,13 @@ namespace stream::fmt::detail AllDisable = 65 }; - enum class TextProperties::TextStyle::Script : std::uint8_t - { + enum class TextProperties::TextStyle::Script : std::uint8_t { Superscript = 74, Subscript = 75, AllDisable = 76 }; - struct TextProperties::TextStyle::UnderlineColor - { + struct TextProperties::TextStyle::UnderlineColor { struct ColorCube; struct Color24b; enum class ColorType : std::uint8_t; @@ -85,74 +73,63 @@ namespace stream::fmt::detail }; // No need of virtual destructor since color24b is purely a renaming of BaseColor24b - struct TextProperties::TextStyle::UnderlineColor::Color24b : public TextProperties::TextColor::BaseColor24b - { - constexpr Color24b(std::uint8_t r = 0, std::uint8_t g = 0, std::uint8_t b = 0) - : TextProperties::TextColor::BaseColor24b(r, g, b) - {} + struct TextProperties::TextStyle::UnderlineColor::Color24b : public TextProperties::TextColor::BaseColor24b { + constexpr Color24b(std::uint8_t r = 0, std::uint8_t g = 0, std::uint8_t b = 0) : TextProperties::TextColor::BaseColor24b(r, g, b) {} }; // No need of virtual destructor since color_cube is purely a renaming of BaseColorCube - struct TextProperties::TextStyle::UnderlineColor::ColorCube : public TextProperties::TextColor::BaseColorCube - { - constexpr ColorCube() - : TextProperties::TextColor::BaseColorCube() - {} - constexpr ColorCube(const std::uint8_t color) - : TextProperties::TextColor::BaseColorCube(color) - {} - constexpr ColorCube(const TextProperties::TextColor::BaseColorCube& color) - : TextProperties::TextColor::BaseColorCube(color) - {} + struct TextProperties::TextStyle::UnderlineColor::ColorCube : public TextProperties::TextColor::BaseColorCube { + constexpr ColorCube() : TextProperties::TextColor::BaseColorCube() {} + constexpr ColorCube(const std::uint8_t color) : TextProperties::TextColor::BaseColorCube(color) {} + constexpr ColorCube(const TextProperties::TextColor::BaseColorCube& color) : TextProperties::TextColor::BaseColorCube(color) {} public: - static ColorCube MakeNormalColor(const std::uint8_t value) { return static_cast(TextProperties::TextColor::BaseColorCube::MakeNormalColor(value)); } + static ColorCube MakeNormalColor(const std::uint8_t value) { + return static_cast(TextProperties::TextColor::BaseColorCube::MakeNormalColor(value)); + } - static ColorCube MakeBrightColor(const std::uint8_t value) { return static_cast(TextProperties::TextColor::BaseColorCube::MakeBrightColor(value)); } + static ColorCube MakeBrightColor(const std::uint8_t value) { + return static_cast(TextProperties::TextColor::BaseColorCube::MakeBrightColor(value)); + } - static ColorCube Make666CubeColor255(const std::uint8_t r, const std::uint8_t g, const std::uint8_t b) - { + static ColorCube Make666CubeColor255(const std::uint8_t r, const std::uint8_t g, const std::uint8_t b) { return static_cast(TextProperties::TextColor::BaseColorCube::Make666CubeColor255(r, g, b)); } - static ColorCube Make666CubeColor5(const std::uint8_t r, const std::uint8_t g, const std::uint8_t b) - { + static ColorCube Make666CubeColor5(const std::uint8_t r, const std::uint8_t g, const std::uint8_t b) { return static_cast(TextProperties::TextColor::BaseColorCube::Make666CubeColor5(r, g, b)); } - static ColorCube MakeGrayscaleColor255(const std::uint8_t value) { return static_cast(TextProperties::TextColor::BaseColorCube::MakeGrayscaleColor255(value)); } + static ColorCube MakeGrayscaleColor255(const std::uint8_t value) { + return static_cast(TextProperties::TextColor::BaseColorCube::MakeGrayscaleColor255(value)); + } - static ColorCube MakeGrayscaleColor24(const std::uint8_t value) { return static_cast(TextProperties::TextColor::BaseColorCube::MakeGrayscaleColor24(value)); } + static ColorCube MakeGrayscaleColor24(const std::uint8_t value) { + return static_cast(TextProperties::TextColor::BaseColorCube::MakeGrayscaleColor24(value)); + } }; - enum class TextProperties::TextStyle::UnderlineColor::ColorType : std::uint8_t - { + enum class TextProperties::TextStyle::UnderlineColor::ColorType : std::uint8_t { Default, ColorCube, Color24b }; - union TextProperties::TextStyle::UnderlineColor::ColorData - { - constexpr ColorData() - : color_cube() - {} + union TextProperties::TextStyle::UnderlineColor::ColorData { + constexpr ColorData() : color_cube() {} TextProperties::TextStyle::UnderlineColor::ColorCube color_cube; TextProperties::TextStyle::UnderlineColor::Color24b color24b; }; - struct TextProperties::TextStyle::UnderlineColor::Color - { + struct TextProperties::TextStyle::UnderlineColor::Color { TextProperties::TextStyle::UnderlineColor::ColorData data; TextProperties::TextStyle::UnderlineColor::ColorType type = TextProperties::TextStyle::UnderlineColor::ColorType::Default; }; - inline bool operator==(const TextProperties::TextStyle::UnderlineColor::Color& lhs, const TextProperties::TextStyle::UnderlineColor::Color& rhs) - { + inline bool operator==(const TextProperties::TextStyle::UnderlineColor::Color& lhs, const TextProperties::TextStyle::UnderlineColor::Color& rhs) { if (lhs.type != rhs.type) return false; - switch (lhs.type) - { + switch (lhs.type) { case TextProperties::TextStyle::UnderlineColor::ColorType::Default: return true; case TextProperties::TextStyle::UnderlineColor::ColorType::ColorCube: @@ -165,8 +142,7 @@ namespace stream::fmt::detail bool operator==(const TextProperties::TextStyle::Style& lhs, const TextProperties::TextStyle::Style& rhs); - struct TextProperties::TextStyle::Style - { + struct TextProperties::TextStyle::Style { public: constexpr Style() {} @@ -181,67 +157,100 @@ namespace stream::fmt::detail TextProperties::TextStyle::UnderlineColor::Color underline_color; public: - void modify_reset() { *this = Style{}; } - - void apply(const TextProperties::TextStyle::reset_style&) { modify_reset(); } - void apply(const TextProperties::TextStyle::Style& given) { *this = given; } - void apply(const TextProperties::TextStyle::Intensity& given) { intensity = given; } - void apply(const TextProperties::TextStyle::Italic& given) { italic = given; } - void apply(const TextProperties::TextStyle::Underline& given) { underline = given; } - void apply(const TextProperties::TextStyle::Blink& given) { blink = given; } - void apply(const TextProperties::TextStyle::Inverted& given) { inverted = given; } - void apply(const TextProperties::TextStyle::Ideogram& given) { ideogram = given; } - void apply(const TextProperties::TextStyle::Script& given) { script = given; } - - void apply(const TextProperties::TextStyle::UnderlineColor::Color& given) { underline_color = given; } - void apply(const TextProperties::TextStyle::UnderlineColor::ColorCube& given) - { - underline_color.type = TextProperties::TextStyle::UnderlineColor::ColorType::ColorCube; + void modify_reset() { + *this = Style{}; + } + + void apply(const TextProperties::TextStyle::reset_style&) { + modify_reset(); + } + void apply(const TextProperties::TextStyle::Style& given) { + *this = given; + } + void apply(const TextProperties::TextStyle::Intensity& given) { + intensity = given; + } + void apply(const TextProperties::TextStyle::Italic& given) { + italic = given; + } + void apply(const TextProperties::TextStyle::Underline& given) { + underline = given; + } + void apply(const TextProperties::TextStyle::Blink& given) { + blink = given; + } + void apply(const TextProperties::TextStyle::Inverted& given) { + inverted = given; + } + void apply(const TextProperties::TextStyle::Ideogram& given) { + ideogram = given; + } + void apply(const TextProperties::TextStyle::Script& given) { + script = given; + } + + void apply(const TextProperties::TextStyle::UnderlineColor::Color& given) { + underline_color = given; + } + void apply(const TextProperties::TextStyle::UnderlineColor::ColorCube& given) { + underline_color.type = TextProperties::TextStyle::UnderlineColor::ColorType::ColorCube; underline_color.data.color_cube = given; } - void apply(const TextProperties::TextStyle::UnderlineColor::Color24b& given) - { + void apply(const TextProperties::TextStyle::UnderlineColor::Color24b& given) { underline_color.type = TextProperties::TextStyle::UnderlineColor::ColorType::Color24b; underline_color.data.color24b = given; } public: - bool need_modif(const TextProperties::TextStyle::reset_style&) { return true; } - bool need_modif(const TextProperties::TextStyle::Style& given) { return *this != given; } - bool need_modif(const TextProperties::TextStyle::Intensity& given) { return intensity != given; } - bool need_modif(const TextProperties::TextStyle::Italic& given) { return italic != given; } - bool need_modif(const TextProperties::TextStyle::Underline& given) { return underline != given; } - bool need_modif(const TextProperties::TextStyle::Blink& given) { return blink != given; } - bool need_modif(const TextProperties::TextStyle::Inverted& given) { return inverted != given; } - bool need_modif(const TextProperties::TextStyle::Ideogram& given) { return ideogram != given; } - bool need_modif(const TextProperties::TextStyle::Script& given) { return script != given; } - - bool need_modif(const TextProperties::TextStyle::UnderlineColor::Color& given) { return underline_color != given; } - bool need_modif(const TextProperties::TextStyle::UnderlineColor::ColorCube& given) - { + bool need_modif(const TextProperties::TextStyle::reset_style&) { + return true; + } + bool need_modif(const TextProperties::TextStyle::Style& given) { + return *this != given; + } + bool need_modif(const TextProperties::TextStyle::Intensity& given) { + return intensity != given; + } + bool need_modif(const TextProperties::TextStyle::Italic& given) { + return italic != given; + } + bool need_modif(const TextProperties::TextStyle::Underline& given) { + return underline != given; + } + bool need_modif(const TextProperties::TextStyle::Blink& given) { + return blink != given; + } + bool need_modif(const TextProperties::TextStyle::Inverted& given) { + return inverted != given; + } + bool need_modif(const TextProperties::TextStyle::Ideogram& given) { + return ideogram != given; + } + bool need_modif(const TextProperties::TextStyle::Script& given) { + return script != given; + } + + bool need_modif(const TextProperties::TextStyle::UnderlineColor::Color& given) { + return underline_color != given; + } + bool need_modif(const TextProperties::TextStyle::UnderlineColor::ColorCube& given) { return underline_color.type != TextProperties::TextStyle::UnderlineColor::ColorType::ColorCube || underline_color.data.color_cube != given; } - bool need_modif(const TextProperties::TextStyle::UnderlineColor::Color24b& given) - { + bool need_modif(const TextProperties::TextStyle::UnderlineColor::Color24b& given) { return underline_color.type != TextProperties::TextStyle::UnderlineColor::ColorType::Color24b || underline_color.data.color24b != given; } }; - inline bool operator==(const TextProperties::TextStyle::Style& lhs, const TextProperties::TextStyle::Style& rhs) - { + inline bool operator==(const TextProperties::TextStyle::Style& lhs, const TextProperties::TextStyle::Style& rhs) { return lhs.intensity == rhs.intensity && lhs.italic == rhs.italic && lhs.blink == rhs.blink && lhs.inverted == rhs.inverted && lhs.ideogram == rhs.ideogram && lhs.script == rhs.script && lhs.underline == rhs.underline && lhs.underline_color == rhs.underline_color; } template - concept text_properties_style_can_apply = requires(const T& value, TextProperties::TextStyle::Style& data) - { - data.apply(value); - }; + concept text_properties_style_can_apply = requires(const T& value, TextProperties::TextStyle::Style& data) { data.apply(value); }; template - struct TextPropertiesStyleIsapplyType - { + struct TextPropertiesStyleIsapplyType { using BaseType = get_base_type; static constexpr bool value = std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || @@ -254,12 +263,10 @@ namespace stream::fmt::detail template concept TextPropertiesStyleIsapply = TextPropertiesStyleIsapplyType::value; -} +} // namespace stream::fmt::detail -namespace stream::fmt::detail::OLD -{ - enum class BasicStyle : std::uint8_t - { +namespace stream::fmt::detail::OLD { + enum class BasicStyle : std::uint8_t { Intensity_Bold = static_cast(TextProperties::TextStyle::Intensity::Bold), Intensity_Dim = static_cast(TextProperties::TextStyle::Intensity::Dim), Intensity_Normal = static_cast(TextProperties::TextStyle::Intensity::Normal), @@ -290,4 +297,4 @@ namespace stream::fmt::detail::OLD Script_Subscript = static_cast(TextProperties::TextStyle::Script::Subscript), Script_AllDisable = static_cast(TextProperties::TextStyle::Script::AllDisable) }; -} +} // namespace stream::fmt::detail::OLD diff --git a/src/stream/json/detail.h b/src/stream/json/detail.h index f4c092e6..ce40ebeb 100644 --- a/src/stream/json/detail.h +++ b/src/stream/json/detail.h @@ -5,69 +5,44 @@ #include #include -namespace stream::json::detail -{ - class JsonError : public std::exception - { +namespace stream::json::detail { + class JsonError : public std::exception { public: - JsonError(std::string&& msg) - : m_What(std::move(msg)) - {} - JsonError(const std::string_view msg) - : m_What(msg) - {} - const char* what() const noexcept override { return m_What.c_str(); } + JsonError(std::string&& msg) : m_What(std::move(msg)) {} + JsonError(const std::string_view msg) : m_What(msg) {} + const char* what() const noexcept override { + return m_What.c_str(); + } protected: std::string m_What; }; - class JsonIndexingError : public JsonError - { + class JsonIndexingError : public JsonError { public: - JsonIndexingError(std::string&& msg = "") - : JsonError(std::string("JsonIndexingError") + std::move(msg)) - {} - JsonIndexingError(const std::string& msg) - : JsonError(std::string("JsonIndexingError") + msg) - {} + JsonIndexingError(std::string&& msg = "") : JsonError(std::string("JsonIndexingError") + std::move(msg)) {} + JsonIndexingError(const std::string& msg) : JsonError(std::string("JsonIndexingError") + msg) {} }; - class JsonTypeSerializerNotImpl : public JsonError - { + class JsonTypeSerializerNotImpl : public JsonError { public: - JsonTypeSerializerNotImpl(std::string&& msg = "") - : JsonError(std::string("JsonTypeSerializerNotImpl") + std::move(msg)) - {} - JsonTypeSerializerNotImpl(const std::string& msg) - : JsonError(std::string("JsonTypeSerializerNotImpl") + msg) - {} + JsonTypeSerializerNotImpl(std::string&& msg = "") : JsonError(std::string("JsonTypeSerializerNotImpl") + std::move(msg)) {} + JsonTypeSerializerNotImpl(const std::string& msg) : JsonError(std::string("JsonTypeSerializerNotImpl") + msg) {} }; - class JsonGivenTypeError : public JsonError - { + class JsonGivenTypeError : public JsonError { public: - JsonGivenTypeError(std::string&& msg = "") - : JsonError(std::string("JsonGivenTypeError") + std::move(msg)) - {} - JsonGivenTypeError(const std::string& msg) - : JsonError(std::string("JsonGivenTypeError") + msg) - {} + JsonGivenTypeError(std::string&& msg = "") : JsonError(std::string("JsonGivenTypeError") + std::move(msg)) {} + JsonGivenTypeError(const std::string& msg) : JsonError(std::string("JsonGivenTypeError") + msg) {} }; - class JsonCastError : public JsonError - { + class JsonCastError : public JsonError { public: - JsonCastError(std::string&& msg = "") - : JsonError(std::string("JsonCastError") + std::move(msg)) - {} - JsonCastError(const std::string& msg) - : JsonError(std::string("JsonCastError") + msg) - {} + JsonCastError(std::string&& msg = "") : JsonError(std::string("JsonCastError") + std::move(msg)) {} + JsonCastError(const std::string& msg) : JsonError(std::string("JsonCastError") + msg) {} }; -} +} // namespace stream::json::detail -namespace stream::json -{ +namespace stream::json { template struct JsonObjectSerializer; template struct JsonSerializer; -} +} // namespace stream::json diff --git a/src/stream/json/json_factory.h b/src/stream/json/json_factory.h index 6ccce9f0..52f8a81b 100644 --- a/src/stream/json/json_factory.h +++ b/src/stream/json/json_factory.h @@ -11,38 +11,33 @@ #include #include -namespace stream::json -{ - class JsonFactory - { +namespace stream::json { + class JsonFactory { public: template > static T FromPath(const std::filesystem::path& path); template static void SaveToPath(T& json, const std::filesystem::path& path, detail::JsonFormatter::FormatSettings settings); }; -} +} // namespace stream::json #include "stream/fmt.h" -namespace stream::fmt -{ +namespace stream::fmt { template - struct FormatterType - { - [[nodiscard]] static std::expected format(const json::JsonObject& object, FormatterExecutor& executor) - { return executor.write_type(json::FormatAsJson(object)); } + struct FormatterType { + [[nodiscard]] static std::expected format(const json::JsonObject& object, FormatterExecutor& executor) { + return executor.write_type(json::FormatAsJson(object)); + } }; -} +} // namespace stream::fmt #include #include #include "stream//fmt/buf/streamio_manager/dynamic_streamio_manager.h" #include "serializers/json_objects_serializer.h" -namespace stream::json -{ +namespace stream::json { template - T JsonFactory::FromPath(const std::filesystem::path& path) - { + T JsonFactory::FromPath(const std::filesystem::path& path) { std::ifstream file(path.string(), std::ios::in); if (file.is_open() == false) throw std::runtime_error("unable to open file"); @@ -57,26 +52,25 @@ namespace stream::json file.close(); fmt::buf::StreamView input(buffer.data(), buffer.size()); - detail::JsonParser parser(input); - T res; + detail::JsonParser parser(input); + T res; JsonSerializer::parse(res, parser); return res; } template - void JsonFactory::SaveToPath(T& json, const std::filesystem::path& path, detail::JsonFormatter::FormatSettings settings) - { + void JsonFactory::SaveToPath(T& json, const std::filesystem::path& path, detail::JsonFormatter::FormatSettings settings) { std::ofstream file(path.string(), std::ios::out); if (file.is_open() == false) throw std::runtime_error("unable to open file"); fmt::buf::DynamicStreamIOManager StreamIOManager(256); - fmt::buf::StreamIO ostream = fmt::buf::StreamIO::create(StreamIOManager).value(); - detail::JsonFormatter formatter(ostream, settings); + fmt::buf::StreamIO ostream = fmt::buf::StreamIO::create(StreamIOManager).value(); + detail::JsonFormatter formatter(ostream, settings); JsonSerializer::format(json, formatter); file.write(StreamIOManager.get_buffer(), static_cast(StreamIOManager.get_last_generated_data_size())); file.flush(); file.close(); } -} +} // namespace stream::json diff --git a/src/stream/json/json_formatter.h b/src/stream/json/json_formatter.h index 981271ba..6c06859a 100644 --- a/src/stream/json/json_formatter.h +++ b/src/stream/json/json_formatter.h @@ -4,31 +4,20 @@ #include "stream/fmt/buf/streamio.h" #include "stream/fmt/buf/manip_io.h" -namespace stream::json::detail -{ - class JsonFormatter - { +namespace stream::json::detail { + class JsonFormatter { public: - struct FormatSettings - { - std::size_t indent_size = 4; + struct FormatSettings { + std::size_t indent_size = 4; bool indent_with_spaces = true; - bool one_line = false; - bool ordered_struct = false; - std::int32_t float_precision = 7; + bool one_line = false; + bool ordered_struct = false; + std::int32_t float_precision = 7; }; public: - JsonFormatter(stream::fmt::buf::StreamIO& ostream_) - : ostream(ostream_) - , settings() - , indent_(0) - {} - JsonFormatter(stream::fmt::buf::StreamIO& ostream_, FormatSettings settings_) - : ostream(ostream_) - , settings(settings_) - , indent_(0) - {} + JsonFormatter(stream::fmt::buf::StreamIO& ostream_) : ostream(ostream_), settings(), indent_(0) {} + JsonFormatter(stream::fmt::buf::StreamIO& ostream_, FormatSettings settings_) : ostream(ostream_), settings(settings_), indent_(0) {} public: template @@ -40,8 +29,7 @@ namespace stream::json::detail ArrayIntermediate get_array_intermediate(); public: - void indent() - { + void indent() { if (settings.one_line) return; if (settings.indent_with_spaces) @@ -50,28 +38,29 @@ namespace stream::json::detail fmt::buf::ManipIO(ostream).pushback('\t', indent_ * settings.indent_size).value(); } - void NewLine() - { + void NewLine() { if (settings.one_line) return; fmt::buf::ManipIO(ostream).pushback('\n').value(); indent(); } - void begin_new_object() { ++indent_; } - void end_new_object() { --indent_; } + void begin_new_object() { + ++indent_; + } + void end_new_object() { + --indent_; + } public: fmt::buf::StreamIO& ostream; - FormatSettings settings; - + FormatSettings settings; + protected: std::size_t indent_; }; -} +} // namespace stream::json::detail -namespace stream::json::detail -{ - struct JsonFormatter::StructIntermediate - { +namespace stream::json::detail { + struct JsonFormatter::StructIntermediate { public: StructIntermediate(JsonFormatter& formatter); ~StructIntermediate(); @@ -85,8 +74,7 @@ namespace stream::json::detail std::uint32_t Idx; }; - struct JsonFormatter::ArrayIntermediate - { + struct JsonFormatter::ArrayIntermediate { public: ArrayIntermediate(JsonFormatter& formatter); ~ArrayIntermediate(); @@ -100,13 +88,11 @@ namespace stream::json::detail std::uint32_t Idx; }; - inline JsonFormatter::StructIntermediate JsonFormatter::get_struct_intermediate() - { + inline JsonFormatter::StructIntermediate JsonFormatter::get_struct_intermediate() { return JsonFormatter::StructIntermediate(*this); } - inline JsonFormatter::ArrayIntermediate JsonFormatter::get_array_intermediate() - { + inline JsonFormatter::ArrayIntermediate JsonFormatter::get_array_intermediate() { return JsonFormatter::ArrayIntermediate(*this); } -} +} // namespace stream::json::detail diff --git a/src/stream/json/json_formatter_impl.h b/src/stream/json/json_formatter_impl.h index 866eff5b..e8367489 100644 --- a/src/stream/json/json_formatter_impl.h +++ b/src/stream/json/json_formatter_impl.h @@ -2,37 +2,26 @@ #include "json_serializer.h" -namespace stream::json::detail -{ - inline JsonFormatter::StructIntermediate::StructIntermediate(JsonFormatter& formatter) - : Formatter(formatter) - , Idx(0) - { +namespace stream::json::detail { + inline JsonFormatter::StructIntermediate::StructIntermediate(JsonFormatter& formatter) : Formatter(formatter), Idx(0) { JsonStructSerializer::FormatBegin(Formatter); } - inline JsonFormatter::StructIntermediate::~StructIntermediate() - { + inline JsonFormatter::StructIntermediate::~StructIntermediate() { JsonStructSerializer::FormatEnd(Formatter); } template - inline void JsonFormatter::StructIntermediate::format(const std::string_view name, const T& t) - { + inline void JsonFormatter::StructIntermediate::format(const std::string_view name, const T& t) { JsonStructSerializer::FormatObject(name, t, Idx++, Formatter); } - inline JsonFormatter::ArrayIntermediate::ArrayIntermediate(JsonFormatter& formatter) - : Formatter(formatter) - , Idx(0) - { + inline JsonFormatter::ArrayIntermediate::ArrayIntermediate(JsonFormatter& formatter) : Formatter(formatter), Idx(0) { JsonArraySerializer::FormatBegin(Formatter); } - inline JsonFormatter::ArrayIntermediate::~ArrayIntermediate() - { + inline JsonFormatter::ArrayIntermediate::~ArrayIntermediate() { JsonArraySerializer::FormatEnd(Formatter); } template - inline void JsonFormatter::ArrayIntermediate::format(const T& t) - { + inline void JsonFormatter::ArrayIntermediate::format(const T& t) { JsonArraySerializer::FormatObject(t, Idx++, Formatter); } -} +} // namespace stream::json::detail diff --git a/src/stream/json/json_objects.cpp b/src/stream/json/json_objects.cpp index d64b1666..81586434 100644 --- a/src/stream/json/json_objects.cpp +++ b/src/stream/json/json_objects.cpp @@ -1,59 +1,46 @@ #include "json_objects.h" #include "serializers/json_objects_serializer.h" -namespace stream::json -{ - void JsonStringObject::ParserExecute(detail::JsonParser& parser) - { +namespace stream::json { + void JsonStringObject::ParserExecute(detail::JsonParser& parser) { JsonSerializer::parse(*this, parser); } - void JsonStringObject::FormatterExecute(detail::JsonFormatter& formatter) const - { + void JsonStringObject::FormatterExecute(detail::JsonFormatter& formatter) const { JsonSerializer::format(*this, formatter); } - void JsonNumberObject::ParserExecute(detail::JsonParser& parser) - { + void JsonNumberObject::ParserExecute(detail::JsonParser& parser) { JsonSerializer::parse(*this, parser); } - void JsonNumberObject::FormatterExecute(detail::JsonFormatter& formatter) const - { + void JsonNumberObject::FormatterExecute(detail::JsonFormatter& formatter) const { JsonSerializer::format(*this, formatter); } - void JsonBooleanObject::ParserExecute(detail::JsonParser& parser) - { + void JsonBooleanObject::ParserExecute(detail::JsonParser& parser) { JsonSerializer::parse(*this, parser); } - void JsonBooleanObject::FormatterExecute(detail::JsonFormatter& formatter) const - { + void JsonBooleanObject::FormatterExecute(detail::JsonFormatter& formatter) const { JsonSerializer::format(*this, formatter); } - void JsonStructObject::ParserExecute(detail::JsonParser& parser) - { + void JsonStructObject::ParserExecute(detail::JsonParser& parser) { JsonSerializer::parse(*this, parser); } - void JsonStructObject::FormatterExecute(detail::JsonFormatter& formatter) const - { + void JsonStructObject::FormatterExecute(detail::JsonFormatter& formatter) const { JsonSerializer::format(*this, formatter); } - void JsonArrayObject::ParserExecute(detail::JsonParser& parser) - { + void JsonArrayObject::ParserExecute(detail::JsonParser& parser) { JsonSerializer::parse(*this, parser); } - void JsonArrayObject::FormatterExecute(detail::JsonFormatter& formatter) const - { + void JsonArrayObject::FormatterExecute(detail::JsonFormatter& formatter) const { JsonSerializer::format(*this, formatter); } - void JsonNullObject::ParserExecute(detail::JsonParser& parser) - { + void JsonNullObject::ParserExecute(detail::JsonParser& parser) { JsonSerializer::parse(*this, parser); } - void JsonNullObject::FormatterExecute(detail::JsonFormatter& formatter) const - { + void JsonNullObject::FormatterExecute(detail::JsonFormatter& formatter) const { JsonSerializer::format(*this, formatter); } -} +} // namespace stream::json diff --git a/src/stream/json/json_objects.h b/src/stream/json/json_objects.h index cf8a3f1a..6ff68113 100644 --- a/src/stream/json/json_objects.h +++ b/src/stream/json/json_objects.h @@ -9,19 +9,15 @@ #include #include -namespace stream::json::detail -{ +namespace stream::json::detail { class JsonParser; class JsonFormatter; -} +} // namespace stream::json::detail -namespace stream::json -{ - struct JsonObject - { +namespace stream::json { + struct JsonObject { public: - enum class ObjectType - { + enum class ObjectType { String, Number, Boolean, @@ -33,9 +29,7 @@ namespace stream::json public: JsonObject() {} - JsonObject(ObjectType type) - : m_Type(type) - {} + JsonObject(ObjectType type) : m_Type(type) {} virtual ~JsonObject() = default; @@ -43,144 +37,145 @@ namespace stream::json ObjectType m_Type = ObjectType::Undefined; public: - ObjectType GetType() { return m_Type; } + ObjectType GetType() { + return m_Type; + } - JsonObject& operator[](const std::size_t index) { return get(index); } - JsonObject& operator[](const std::string_view subObject) { return get(subObject); } + JsonObject& operator[](const std::size_t index) { + return get(index); + } + JsonObject& operator[](const std::string_view subObject) { + return get(subObject); + } - virtual JsonObject& get(const std::size_t) { throw detail::JsonIndexingError{}; } - virtual JsonObject& get(const std::string_view) { throw detail::JsonIndexingError{}; } + virtual JsonObject& get(const std::size_t) { + throw detail::JsonIndexingError{}; + } + virtual JsonObject& get(const std::string_view) { + throw detail::JsonIndexingError{}; + } public: template - requires std::is_base_of_v T& As() - { + requires std::is_base_of_v + T& As() { T* t = dynamic_cast(this); if (t == nullptr) throw detail::JsonCastError{}; return *t; } template - requires std::is_base_of_v - const T& As() const - { + requires std::is_base_of_v + const T& As() const { const T* t = dynamic_cast(this); if (t == nullptr) throw detail::JsonCastError{}; return *t; } template - T Read() - { + T Read() { T value; JsonObjectSerializer::ReadObject(value, *this); return value; } template - void Write(const T& t) - { + void Write(const T& t) { JsonObjectSerializer::WriteObject(t, *this); } - std::string ToString() { return fmt::format_string(*this).value(); } + std::string ToString() { + return fmt::format_string(*this).value(); + } public: virtual void ParserExecute(detail::JsonParser& parser) = 0; virtual void FormatterExecute(detail::JsonFormatter& formatter) const = 0; }; - struct JsonStringObject final : public JsonObject - { - JsonStringObject() - : JsonObject(ObjectType::String) - {} - JsonStringObject(const std::string_view value) - : JsonObject(ObjectType::String) - , String(value) - {} - JsonStringObject(std::string&& value) - : JsonObject(ObjectType::String) - , String(std::move(value)) - {} + struct JsonStringObject final : public JsonObject { + JsonStringObject() : JsonObject(ObjectType::String) {} + JsonStringObject(const std::string_view value) : JsonObject(ObjectType::String), String(value) {} + JsonStringObject(std::string&& value) : JsonObject(ObjectType::String), String(std::move(value)) {} ~JsonStringObject() override = default; public: std::string String; public: - static std::unique_ptr create() { return std::make_unique(); } - static std::unique_ptr create(const std::string_view value) { return std::make_unique(value); } - static std::unique_ptr create(std::string&& value) { return std::make_unique(std::move(value)); } + static std::unique_ptr create() { + return std::make_unique(); + } + static std::unique_ptr create(const std::string_view value) { + return std::make_unique(value); + } + static std::unique_ptr create(std::string&& value) { + return std::make_unique(std::move(value)); + } public: void ParserExecute(detail::JsonParser& parser) override; void FormatterExecute(detail::JsonFormatter& formatter) const override; }; - struct JsonNumberObject final : public JsonObject - { - JsonNumberObject(double value = 0.0) - : JsonObject(ObjectType::Number) - , Number(value) - {} + struct JsonNumberObject final : public JsonObject { + JsonNumberObject(double value = 0.0) : JsonObject(ObjectType::Number), Number(value) {} ~JsonNumberObject() override = default; public: double Number; public: - static std::unique_ptr create(double value = 0.0) { return std::make_unique(value); } + static std::unique_ptr create(double value = 0.0) { + return std::make_unique(value); + } public: void ParserExecute(detail::JsonParser& parser) override; void FormatterExecute(detail::JsonFormatter& formatter) const override; }; - struct JsonBooleanObject final : public JsonObject - { - JsonBooleanObject(bool value = false) - : JsonObject(ObjectType::Boolean) - , Boolean(value) - {} + struct JsonBooleanObject final : public JsonObject { + JsonBooleanObject(bool value = false) : JsonObject(ObjectType::Boolean), Boolean(value) {} ~JsonBooleanObject() override = default; public: bool Boolean; public: - static std::unique_ptr create(bool value = false) { return std::make_unique(value); } + static std::unique_ptr create(bool value = false) { + return std::make_unique(value); + } public: void ParserExecute(detail::JsonParser& parser) override; void FormatterExecute(detail::JsonFormatter& formatter) const override; }; - struct JsonStructObject final : public JsonObject - { + struct JsonStructObject final : public JsonObject { public: - JsonStructObject() - : JsonObject(ObjectType::Struct) - {} + JsonStructObject() : JsonObject(ObjectType::Struct) {} ~JsonStructObject() override = default; public: - static std::unique_ptr create() { return std::make_unique(); } + static std::unique_ptr create() { + return std::make_unique(); + } public: std::unordered_map> Objects; public: - void add(const std::string& name, std::unique_ptr&& object) { Objects.insert({name, std::move(object)}); } - void add(std::string&& name, std::unique_ptr&& object) { Objects.insert({std::move(name), std::move(object)}); } - JsonObject& get(const std::string_view subObject) override - { - try - { + void add(const std::string& name, std::unique_ptr&& object) { + Objects.insert({name, std::move(object)}); + } + void add(std::string&& name, std::unique_ptr&& object) { + Objects.insert({std::move(name), std::move(object)}); + } + JsonObject& get(const std::string_view subObject) override { + try { return *Objects.at(std::string(subObject)); - } - catch (...) - { + } catch (...) { throw detail::JsonIndexingError{}; } } @@ -190,42 +185,44 @@ namespace stream::json void FormatterExecute(detail::JsonFormatter& formatter) const override; }; - struct JsonArrayObject final : public JsonObject - { + struct JsonArrayObject final : public JsonObject { public: - JsonArrayObject() - : JsonObject(ObjectType::Array) - {} + JsonArrayObject() : JsonObject(ObjectType::Array) {} ~JsonArrayObject() override = default; public: - static std::unique_ptr create() { return std::make_unique(); } + static std::unique_ptr create() { + return std::make_unique(); + } public: std::vector> Objects; public: - void add(std::unique_ptr&& object) { Objects.emplace_back(std::move(object)); } - JsonObject& get(const std::size_t index) override { return *Objects[index]; } + void add(std::unique_ptr&& object) { + Objects.emplace_back(std::move(object)); + } + JsonObject& get(const std::size_t index) override { + return *Objects[index]; + } public: void ParserExecute(detail::JsonParser& parser) override; void FormatterExecute(detail::JsonFormatter& formatter) const override; }; - struct JsonNullObject final : public JsonObject - { + struct JsonNullObject final : public JsonObject { public: - JsonNullObject() - : JsonObject(ObjectType::Null) - {} + JsonNullObject() : JsonObject(ObjectType::Null) {} ~JsonNullObject() override = default; public: - static std::unique_ptr create() { return std::make_unique(); } + static std::unique_ptr create() { + return std::make_unique(); + } public: void ParserExecute(detail::JsonParser& parser) override; void FormatterExecute(detail::JsonFormatter& formatter) const override; }; -} +} // namespace stream::json diff --git a/src/stream/json/json_parser.cpp b/src/stream/json/json_parser.cpp index 1731e1dd..1361ce5d 100644 --- a/src/stream/json/json_parser.cpp +++ b/src/stream/json/json_parser.cpp @@ -6,76 +6,59 @@ #include "json_serializer.h" -namespace stream::json::detail -{ - void JsonParser::Intermediate::parse(detail::JsonParser& parser) - { - fmt::buf::TestAccess access(parser.istream); - fmt::buf::TestManip manip(parser.istream); +namespace stream::json::detail { + void JsonParser::Intermediate::parse(detail::JsonParser& parser) { + const fmt::buf::TestAccess access(parser.istream); + fmt::buf::TestManip manip(parser.istream); manip.IgnoreEveryBlanks(); - const char* begin = parser.istream.current_pos; + const char* const begin = parser.istream.current_pos; - if (parser.is_json_string_begin()) - { + if (parser.is_json_string_begin()) { manip.skip_one_of('"').value(); - while (true) - { + while (true) { manip.GoTo('"'); - if (fmt::buf::Access(parser.istream).get_prev_force() != '\\') - break; + if (fmt::buf::Access(parser.istream).get_prev_force() != '\\') break; } manip.skip_one_of('"').value(); - } - else if (parser.is_json_number_begin()) - { + } else if (parser.is_json_number_begin()) { float k; JsonNumberSerializer::ParseFloat(k, parser); - } - else if (parser.is_json_boolean_begin()) - { + } else if (parser.is_json_boolean_begin()) { bool k; JsonBooleanSerializer::ParseBool(k, parser); - } - else if (parser.is_json_struct_begin()) - { - JsonStructSerializer::LoadAllSubObjects(*this, parser, [](JsonParser::Intermediate&, std::size_t, std::string&&, JsonParser& jsonParser) { + } else if (parser.is_json_struct_begin()) { + JsonStructSerializer::LoadAllSubObjects(*this, parser, [](JsonParser::Intermediate&, std::size_t, std::string&&, JsonParser& json_parser) { JsonParser::Intermediate intermediate; - intermediate.parse(jsonParser); + intermediate.parse(json_parser); }); - } - else if (parser.is_json_array_begin()) - { - JsonArraySerializer::LoadAllSubObjects(*this, parser, [](JsonParser::Intermediate&, std::size_t, JsonParser& jsonParser) { + } else if (parser.is_json_array_begin()) { + JsonArraySerializer::LoadAllSubObjects(*this, parser, [](JsonParser::Intermediate&, std::size_t, JsonParser& json_parser) { JsonParser::Intermediate intermediate; - intermediate.parse(jsonParser); + intermediate.parse(json_parser); }); - } - else if (parser.is_json_null_begin()) - { + } else if (parser.is_json_null_begin()) { JsonNullSerializer::ParseNull(parser); } - const char* end = parser.istream.current_pos; - data = std::string_view(begin, end); + const char* const end = parser.istream.current_pos; + data = std::string_view(begin, end); }; - void JsonParser::StructIntermediate::parse(detail::JsonParser& parser) - { + void JsonParser::StructIntermediate::parse(detail::JsonParser& parser) { JsonStructSerializer::LoadAllSubObjects(*this, parser, - [](JsonParser::StructIntermediate& t, std::size_t, std::string&& name, JsonParser& jsonParser) { - JsonParser::Intermediate intermediate; - intermediate.parse(jsonParser); - t.Objects.insert({std::move(name), std::move(intermediate)}); - }); + [](JsonParser::StructIntermediate& t, std::size_t, std::string&& name, JsonParser& json_parser) { + JsonParser::Intermediate intermediate; + intermediate.parse(json_parser); + t.Objects.insert({std::move(name), std::move(intermediate)}); + }); }; - void JsonParser::ArrayIntermediate::parse(detail::JsonParser& parser) - { - JsonArraySerializer::LoadAllSubObjects(*this, parser, [](JsonParser::ArrayIntermediate& t, std::size_t, JsonParser& jsonParser) { + void JsonParser::ArrayIntermediate::parse(detail::JsonParser& parser) { + JsonArraySerializer::LoadAllSubObjects(*this, parser, [](JsonParser::ArrayIntermediate& t, std::size_t, JsonParser& json_parser) { JsonParser::Intermediate intermediate; - intermediate.parse(jsonParser); + intermediate.parse(json_parser); t.Objects.emplace_back(std::move(intermediate)); }); }; -} +} // namespace stream::json::detail diff --git a/src/stream/json/json_parser.h b/src/stream/json/json_parser.h index 45d52f1c..8fd9a0de 100644 --- a/src/stream/json/json_parser.h +++ b/src/stream/json/json_parser.h @@ -4,26 +4,32 @@ #include "json_objects.h" -namespace stream::json::detail -{ - class JsonParser - { +namespace stream::json::detail { + class JsonParser { public: - JsonParser() - : istream() - {} + JsonParser() : istream() {} - JsonParser(fmt::buf::StreamView& input) - : istream(input) - {} + JsonParser(fmt::buf::StreamView& input) : istream(input) {} public: - inline bool is_json_string_begin() const { return fmt::buf::TestAccess(istream).is_equal_to('"'); } - inline bool is_json_number_begin() const { return fmt::buf::TestAccess(istream).is_a_digit() || fmt::buf::TestAccess(istream).is_equal_to('+', '-', '.'); } - inline bool is_json_boolean_begin() const { return fmt::buf::TestAccess(istream).is_equal_to('t', 'f'); } - inline bool is_json_struct_begin() const { return fmt::buf::TestAccess(istream).is_equal_to('{'); } - inline bool is_json_array_begin() const { return fmt::buf::TestAccess(istream).is_equal_to('['); } - inline bool is_json_null_begin() const { return fmt::buf::TestAccess(istream).is_equal_to('n'); } + inline bool is_json_string_begin() const { + return fmt::buf::TestAccess(istream).is_equal_to('"'); + } + inline bool is_json_number_begin() const { + return fmt::buf::TestAccess(istream).is_a_digit() || fmt::buf::TestAccess(istream).is_equal_to('+', '-', '.'); + } + inline bool is_json_boolean_begin() const { + return fmt::buf::TestAccess(istream).is_equal_to('t', 'f'); + } + inline bool is_json_struct_begin() const { + return fmt::buf::TestAccess(istream).is_equal_to('{'); + } + inline bool is_json_array_begin() const { + return fmt::buf::TestAccess(istream).is_equal_to('['); + } + inline bool is_json_null_begin() const { + return fmt::buf::TestAccess(istream).is_equal_to('n'); + } public: fmt::buf::Stream istream; @@ -40,26 +46,22 @@ namespace stream::json::detail StructIntermediate get_struct_intermediate(); ArrayIntermediate get_array_intermediate(); }; -} +} // namespace stream::json::detail -namespace stream::json::detail -{ - struct JsonParser::Intermediate - { +namespace stream::json::detail { + struct JsonParser::Intermediate { std::string_view data; void parse(detail::JsonParser& parser); template - void parse(T& t) - { + void parse(T& t) { JsonParser parser; parser.parse(t); } }; - struct JsonParser::StructIntermediate - { + struct JsonParser::StructIntermediate { public: friend JsonParser; @@ -70,15 +72,13 @@ namespace stream::json::detail public: template - void parse(const std::string& name, T& t) - { + void parse(const std::string& name, T& t) { if (Objects.contains(name) == false) throw detail::JsonGivenTypeError{}; Objects[name].parse(t); } }; - struct JsonParser::ArrayIntermediate - { + struct JsonParser::ArrayIntermediate { public: friend JsonParser; @@ -89,23 +89,20 @@ namespace stream::json::detail public: template - void parse(const std::size_t idx, T& t) - { + void parse(const std::size_t idx, T& t) { if (idx >= Objects.size()) throw detail::JsonGivenTypeError{}; Objects[idx].parse(t); } }; - inline JsonParser::StructIntermediate JsonParser::get_struct_intermediate() - { + inline JsonParser::StructIntermediate JsonParser::get_struct_intermediate() { JsonParser::StructIntermediate res; res.parse(*this); return res; } - inline JsonParser::ArrayIntermediate JsonParser::get_array_intermediate() - { + inline JsonParser::ArrayIntermediate JsonParser::get_array_intermediate() { JsonParser::ArrayIntermediate res; res.parse(*this); return res; } -} +} // namespace stream::json::detail diff --git a/src/stream/json/json_serializer.h b/src/stream/json/json_serializer.h index 8f377a5c..c759e757 100644 --- a/src/stream/json/json_serializer.h +++ b/src/stream/json/json_serializer.h @@ -11,13 +11,10 @@ #include #include -namespace stream::json -{ +namespace stream::json { template - struct JsonSerializer - { - static inline void parse(T&, detail::JsonParser&) - { + struct JsonSerializer { + static inline void parse(T&, detail::JsonParser&) { #ifdef UNKOWN_TYPE_MESSAGE fmt::file_print(std::cerr, "{C:red}JsonSerializer::Parse<{}> not impl", typeid(T).name()).value(); #endif @@ -33,8 +30,7 @@ namespace stream::json #endif } - static inline void format(const T&, detail::JsonFormatter& formatter) - { + static inline void format(const T&, detail::JsonFormatter& formatter) { fmt::buf::WriteManip(formatter.ostream).fast_write_string(std::string_view("Unknown JsonFormatter for type : ")).value(); fmt::buf::WriteManip(formatter.ostream).fast_write_string(std::string_view(typeid(T).name())).value(); @@ -55,10 +51,8 @@ namespace stream::json }; template - struct JsonObjectSerializer - { - static inline void ReadObject(T&, const JsonObject&) - { + struct JsonObjectSerializer { + static inline void ReadObject(T&, const JsonObject&) { #ifdef UNKOWN_TYPE_MESSAGE fmt::file_print(std::cerr, "{C:red}JsonObjectSerializer::ReadObject<{}> not impl", typeid(T).name()).value(); #endif @@ -74,8 +68,7 @@ namespace stream::json #endif } - static inline void WriteObject(const T&, JsonObject&) - { + static inline void WriteObject(const T&, JsonObject&) { #ifdef UNKOWN_TYPE_MESSAGE fmt::file_print(std::cerr, "{C:red}JsonObjectSerializer::WriteObject<{}> not impl", typeid(T).name()).value(); #endif @@ -92,37 +85,31 @@ namespace stream::json } }; - struct JsonStringSerializer - { - static inline void ParseSTDString(std::string& t, detail::JsonParser& parser) - { + struct JsonStringSerializer { + static inline void ParseSTDString(std::string& t, detail::JsonParser& parser) { fmt::buf::DynamicStreamIOManager bufferData; - fmt::buf::StreamIO buffer = fmt::buf::StreamIO::create(bufferData).value(); + fmt::buf::StreamIO buffer = fmt::buf::StreamIO::create(bufferData).value(); fmt::buf::utils::parse_escaped_quoted_string(parser.istream, buffer).value(); fmt::buf::ManipIO(buffer).compute_generated_size(); t = bufferData.get_last_generated_string_view(); } - static inline void FormatSTDString(const std::string_view t, detail::JsonFormatter& formatter) - { + static inline void FormatSTDString(const std::string_view t, detail::JsonFormatter& formatter) { fmt::buf::Stream buffer(t.data(), t.size()); fmt::buf::utils::format_escaped_quoted_string(formatter.ostream, buffer).value(); } }; - struct JsonNumberSerializer - { + struct JsonNumberSerializer { template - static inline void ParseFloat(FloatType& t, detail::JsonParser& parser) - { + static inline void ParseFloat(FloatType& t, detail::JsonParser& parser) { fmt::buf::ReadManip(parser.istream).fast_read_float(t).value(); } template - static inline void ParseInteger(IntType& t, detail::JsonParser& parser) - { + static inline void ParseInteger(IntType& t, detail::JsonParser& parser) { const char* begin = parser.istream.current_pos; - float tmp = 0; + float tmp = 0; fmt::buf::ReadManip(parser.istream).fast_read_float(tmp).value(); const char* end = parser.istream.current_pos; @@ -132,30 +119,25 @@ namespace stream::json } template - static inline void FormatFloat(const FloatType& t, detail::JsonFormatter& formatter) - { + static inline void FormatFloat(const FloatType& t, detail::JsonFormatter& formatter) { fmt::buf::WriteManip(formatter.ostream).fast_write_float(t, formatter.settings.float_precision).value(); } template - static inline void FormatInteger(const IntType& t, detail::JsonFormatter& formatter) - { + static inline void FormatInteger(const IntType& t, detail::JsonFormatter& formatter) { fmt::buf::WriteManip(formatter.ostream).fast_write_integer(t).value(); } }; - struct JsonBooleanSerializer - { - static inline void ParseBool(bool& t, detail::JsonParser& parser) - { + struct JsonBooleanSerializer { + static inline void ParseBool(bool& t, detail::JsonParser& parser) { if (fmt::buf::TestManip(parser.istream).is_same_forward("true", 5).value()) t = true; else if (fmt::buf::TestManip(parser.istream).is_same_forward("false", 5).value()) t = false; } - static inline void FormatBool(const bool& t, detail::JsonFormatter& formatter) - { + static inline void FormatBool(const bool& t, detail::JsonFormatter& formatter) { if (t) fmt::buf::WriteManip(formatter.ostream).fast_write_char_array("true", 5).value(); else @@ -163,19 +145,16 @@ namespace stream::json } }; - struct JsonStructSerializer - { + struct JsonStructSerializer { template - static inline void LoadAllSubObjects(T& t, detail::JsonParser& parser, std::function subObjectParsingFunction) - { + static inline void LoadAllSubObjects(T& t, detail::JsonParser& parser, std::function subObjectParsingFunction) { fmt::buf::TestAccess access(parser.istream); - fmt::buf::TestManip manip(parser.istream); + fmt::buf::TestManip manip(parser.istream); manip.skip_one_of('{').value(); std::size_t idx = 0; - while (fmt::buf::Access(parser.istream).is_end_of_string() == false) - { + while (fmt::buf::Access(parser.istream).is_end_of_string() == false) { manip.GoTo('"', '}'); if (access.is_equal_to('}')) break; @@ -196,26 +175,25 @@ namespace stream::json } template - static inline void LoadAllSubObjects(T& t, detail::JsonParser& parserObject) - { + static inline void LoadAllSubObjects(T& t, detail::JsonParser& parserObject) { LoadAllSubObjects(t, parserObject, [](T& mainObject, std::size_t idx, std::string&& name, detail::JsonParser& parser) { typename JsonSerializer::StructSubObjectType subObject; parser.parse(subObject); - JsonSerializer::AddStructSubObject(mainObject, idx, std::move(name), std::move(subObject)); + JsonSerializer::add_struct_sub_object(mainObject, idx, std::move(name), std::move(subObject)); }); } - static inline void FormatBegin(detail::JsonFormatter& formatter) { fmt::buf::ManipIO(formatter.ostream).pushback('{').value(); } + static inline void FormatBegin(detail::JsonFormatter& formatter) { + fmt::buf::ManipIO(formatter.ostream).pushback('{').value(); + } - static inline void FormatEnd(detail::JsonFormatter& formatter) - { + static inline void FormatEnd(detail::JsonFormatter& formatter) { formatter.NewLine(); fmt::buf::ManipIO(formatter.ostream).pushback('}').value(); } template - static inline void FormatObject(const std::string_view name, const SubObject& subObject, const std::size_t idx, detail::JsonFormatter& formatter) - { + static inline void FormatObject(const std::string_view name, const SubObject& subObject, const std::size_t idx, detail::JsonFormatter& formatter) { if (idx != 0) fmt::buf::ManipIO(formatter.ostream).pushback(',').value(); formatter.begin_new_object(); @@ -228,19 +206,16 @@ namespace stream::json } }; - struct JsonArraySerializer - { + struct JsonArraySerializer { template - static inline void LoadAllSubObjects(T& t, detail::JsonParser& parser, std::function subObjectParsingFunction) - { + static inline void LoadAllSubObjects(T& t, detail::JsonParser& parser, std::function subObjectParsingFunction) { fmt::buf::TestAccess access(parser.istream); - fmt::buf::TestManip manip(parser.istream); - + fmt::buf::TestManip manip(parser.istream); + manip.skip_one_of('[').value(); std::size_t idx = 0; - while (fmt::buf::Access(parser.istream).is_end_of_string() == false) - { + while (fmt::buf::Access(parser.istream).is_end_of_string() == false) { manip.IgnoreEveryBlanks(); if (access.is_equal_to(']')) break; @@ -255,26 +230,25 @@ namespace stream::json } template - static inline void LoadAllSubObjects(T& t, detail::JsonParser& parser) - { - LoadAllSubObjects(t, parser, [](T& mainObject, std::size_t idx, detail::JsonParser& jsonParser) { + static inline void LoadAllSubObjects(T& t, detail::JsonParser& parser) { + LoadAllSubObjects(t, parser, [](T& mainObject, std::size_t idx, detail::JsonParser& json_parser) { typename JsonSerializer::ArraySubObjectType subObject; - jsonParser.parse(subObject); + json_parser.parse(subObject); JsonSerializer::AddArraySubObject(mainObject, idx, std::move(subObject)); }); } - static inline void FormatBegin(detail::JsonFormatter& formatter) { fmt::buf::ManipIO(formatter.ostream).pushback('[').value(); } + static inline void FormatBegin(detail::JsonFormatter& formatter) { + fmt::buf::ManipIO(formatter.ostream).pushback('[').value(); + } - static inline void FormatEnd(detail::JsonFormatter& formatter) - { + static inline void FormatEnd(detail::JsonFormatter& formatter) { formatter.NewLine(); fmt::buf::ManipIO(formatter.ostream).pushback(']').value(); } template - static inline void FormatObject(const SubObject& subObject, const std::size_t idx, detail::JsonFormatter& formatter) - { + static inline void FormatObject(const SubObject& subObject, const std::size_t idx, detail::JsonFormatter& formatter) { if (idx != 0) fmt::buf::ManipIO(formatter.ostream).pushback(',').value(); formatter.begin_new_object(); @@ -284,56 +258,49 @@ namespace stream::json } }; - struct JsonNullSerializer - { - static inline void ParseNull(detail::JsonParser& parser) { fmt::buf::TestManip(parser.istream).is_same_forward("null", 4).value(); } + struct JsonNullSerializer { + static inline void ParseNull(detail::JsonParser& parser) { + fmt::buf::TestManip(parser.istream).is_same_forward("null", 4).value(); + } - static inline void FormatNull(detail::JsonFormatter& formatter) { fmt::buf::WriteManip(formatter.ostream).fast_write_char_array("null", 4).value(); } + static inline void FormatNull(detail::JsonFormatter& formatter) { + fmt::buf::WriteManip(formatter.ostream).fast_write_char_array("null", 4).value(); + } }; -} +} // namespace stream::json -namespace stream::json::detail -{ +namespace stream::json::detail { template - void JsonFormatter::format(const T& t) - { + void JsonFormatter::format(const T& t) { JsonSerializer::format(t, *this); } template - void JsonParser::parse(T& t) - { + void JsonParser::parse(T& t) { JsonSerializer::parse(t, *this); } -} +} // namespace stream::json::detail -namespace stream::json -{ +namespace stream::json { template - struct FormatAsJson - { + struct FormatAsJson { public: - FormatAsJson(const T& value) - : value(value) - {} + FormatAsJson(const T& value) : value(value) {} public: const T& value; }; -} +} // namespace stream::json #include "stream/fmt.h" -namespace stream::fmt -{ +namespace stream::fmt { #ifdef STREAMFORMAT_FORMATTER_DECLARED template - struct FormatterType, FormatterExecutor> - { - [[nodiscard]] static std::expected format(const json::FormatAsJson& json, FormatterExecutor& executor) - { - bool ordered_struct = executor.data.specifiers.has("ordered_struct"); + struct FormatterType, FormatterExecutor> { + [[nodiscard]] static std::expected format(const json::FormatAsJson& json, FormatterExecutor& executor) { + bool ordered_struct = executor.data.specifiers.has("ordered_struct"); json::detail::JsonFormatter::FormatSettings settings{.ordered_struct = ordered_struct, .float_precision = executor.data.float_precision}; - json::detail::JsonFormatter jsonFormatter(executor.ostream, settings); + json::detail::JsonFormatter jsonFormatter(executor.ostream, settings); json::JsonSerializer::format(json.value, jsonFormatter); return {}; } @@ -342,17 +309,15 @@ namespace stream::fmt #ifdef STREAMFORMAT_PARSER_DECLARED template - struct ParserType, ParserExecutor> - { - [[nodiscard]] static std::expected parse(T& json, ParserExecutor& executor) - { - json::detail::JsonParser jsonParser(*executor.istream.Manager); - jsonParser.istream.current_pos = executor.istream.current_pos; + struct ParserType, ParserExecutor> { + [[nodiscard]] static std::expected parse(T& json, ParserExecutor& executor) { + json::detail::JsonParser json_parser(*executor.istream.Manager); + json_parser.istream.current_pos = executor.istream.current_pos; // TODO: - // json::JsonSerializer::parse(json.value, jsonParser); - executor.istream.current_pos = jsonParser.istream.current_pos; + // json::JsonSerializer::parse(json.value, json_parser); + executor.istream.current_pos = json_parser.istream.current_pos; return {}; } }; #endif -} +} // namespace stream::fmt diff --git a/src/stream/json/serializers/base_serializers.h b/src/stream/json/serializers/base_serializers.h index 8f102401..8fe3c161 100644 --- a/src/stream/json/serializers/base_serializers.h +++ b/src/stream/json/serializers/base_serializers.h @@ -5,50 +5,48 @@ #include -namespace stream::json -{ +namespace stream::json { template - requires (std::is_integral_v && !std::is_floating_point_v) - struct JsonSerializer - { - static inline void parse(T& t, detail::JsonParser& parser) { JsonNumberSerializer::ParseInteger(t, parser); } - static inline void format(const T t, detail::JsonFormatter& formatter) { JsonNumberSerializer::FormatInteger(t, formatter); } + requires(std::is_integral_v && !std::is_floating_point_v) + struct JsonSerializer { + static inline void parse(T& t, detail::JsonParser& parser) { + JsonNumberSerializer::ParseInteger(t, parser); + } + static inline void format(const T t, detail::JsonFormatter& formatter) { + JsonNumberSerializer::FormatInteger(t, formatter); + } }; template - requires std::is_floating_point_v - struct JsonSerializer - { - static inline void parse(T& t, detail::JsonParser& parser) { JsonNumberSerializer::ParseFloat(t, parser); } - static inline void format(const T t, detail::JsonFormatter& formatter) { JsonNumberSerializer::FormatFloat(t, formatter); } + requires std::is_floating_point_v + struct JsonSerializer { + static inline void parse(T& t, detail::JsonParser& parser) { + JsonNumberSerializer::ParseFloat(t, parser); + } + static inline void format(const T t, detail::JsonFormatter& formatter) { + JsonNumberSerializer::FormatFloat(t, formatter); + } }; template - struct JsonSerializer - { + struct JsonSerializer { using ArraySubObjectType = T; - static inline void AddArraySubObject(T (&t)[SIZE], std::size_t idx, ArraySubObjectType&& subObject) { t[idx] = std::move(subObject); } + static inline void AddArraySubObject(T (&t)[SIZE], std::size_t idx, ArraySubObjectType&& subObject) { + t[idx] = std::move(subObject); + } - static inline void parse(T (&t)[SIZE], detail::JsonParser& parser) - { - if constexpr (fmt::detail::IsCharType::value) - { + static inline void parse(T (&t)[SIZE], detail::JsonParser& parser) { + if constexpr (fmt::detail::IsCharType::value) { // TODO - } - else - { + } else { JsonArraySerializer::LoadAllSubObjects(t, parser); } } - static inline void format(const T (&t)[SIZE], detail::JsonFormatter& formatter) - { - if constexpr (fmt::detail::IsCharType::value) - { + static inline void format(const T (&t)[SIZE], detail::JsonFormatter& formatter) { + if constexpr (fmt::detail::IsCharType::value) { // TODO - } - else - { + } else { JsonArraySerializer::FormatBegin(formatter); for (std::size_t idx = 0; idx < SIZE; ++idx) JsonArraySerializer::FormatObject(t[idx], idx, formatter); @@ -57,17 +55,14 @@ namespace stream::json } }; template - struct JsonSerializer - { - static inline void parse([[maybe_unused]] T* t, detail::JsonParser& parser) - { + struct JsonSerializer { + static inline void parse([[maybe_unused]] T* t, detail::JsonParser& parser) { if (t == nullptr) throw detail::JsonGivenTypeError{}; // TODO } - static inline void format([[maybe_unused]] const T* t, detail::JsonFormatter& formatter) - { + static inline void format([[maybe_unused]] const T* t, detail::JsonFormatter& formatter) { if (t == nullptr) throw detail::JsonGivenTypeError{}; // TODO } }; -} +} // namespace stream::json diff --git a/src/stream/json/serializers/json_objects_serializer.h b/src/stream/json/serializers/json_objects_serializer.h index d6eea785..69b65faf 100644 --- a/src/stream/json/serializers/json_objects_serializer.h +++ b/src/stream/json/serializers/json_objects_serializer.h @@ -8,13 +8,10 @@ #include -namespace stream::json -{ +namespace stream::json { template <> - struct JsonSerializer> - { - static inline void parse(std::unique_ptr& t, detail::JsonParser& parser) - { + struct JsonSerializer> { + static inline void parse(std::unique_ptr& t, detail::JsonParser& parser) { fmt::buf::TestManip(parser.istream).IgnoreEveryBlanks(); if (parser.is_json_string_begin()) t = std::make_unique(); @@ -32,59 +29,70 @@ namespace stream::json t->ParserExecute(parser); } - static inline void format(const std::unique_ptr& t, detail::JsonFormatter& formatter) { t->FormatterExecute(formatter); } + static inline void format(const std::unique_ptr& t, detail::JsonFormatter& formatter) { + t->FormatterExecute(formatter); + } }; template <> - struct JsonSerializer - { - static inline void format(const JsonObject& t, detail::JsonFormatter& formatter) { t.FormatterExecute(formatter); } + struct JsonSerializer { + static inline void format(const JsonObject& t, detail::JsonFormatter& formatter) { + t.FormatterExecute(formatter); + } }; template <> - struct JsonSerializer - { - static inline void parse(JsonStringObject& t, detail::JsonParser& parser) - { + struct JsonSerializer { + static inline void parse(JsonStringObject& t, detail::JsonParser& parser) { t.String.clear(); JsonStringSerializer::ParseSTDString(t.String, parser); } - static inline void format(const JsonStringObject& t, detail::JsonFormatter& formatter) { JsonStringSerializer::FormatSTDString(t.String, formatter); } + static inline void format(const JsonStringObject& t, detail::JsonFormatter& formatter) { + JsonStringSerializer::FormatSTDString(t.String, formatter); + } }; template <> - struct JsonSerializer - { - static inline void parse(JsonNumberObject& t, detail::JsonParser& parser) { JsonNumberSerializer::ParseFloat(t.Number, parser); } + struct JsonSerializer { + static inline void parse(JsonNumberObject& t, detail::JsonParser& parser) { + JsonNumberSerializer::ParseFloat(t.Number, parser); + } - static inline void format(const JsonNumberObject& t, detail::JsonFormatter& formatter) { JsonNumberSerializer::FormatFloat(t.Number, formatter); } + static inline void format(const JsonNumberObject& t, detail::JsonFormatter& formatter) { + JsonNumberSerializer::FormatFloat(t.Number, formatter); + } }; template <> - struct JsonSerializer - { - static inline void parse(JsonBooleanObject& t, detail::JsonParser& parser) { JsonBooleanSerializer::ParseBool(t.Boolean, parser); } + struct JsonSerializer { + static inline void parse(JsonBooleanObject& t, detail::JsonParser& parser) { + JsonBooleanSerializer::ParseBool(t.Boolean, parser); + } - static inline void format(const JsonBooleanObject& t, detail::JsonFormatter& formatter) { JsonBooleanSerializer::FormatBool(t.Boolean, formatter); } + static inline void format(const JsonBooleanObject& t, detail::JsonFormatter& formatter) { + JsonBooleanSerializer::FormatBool(t.Boolean, formatter); + } }; template <> - struct JsonSerializer - { - static inline void parse(JsonNullObject&, detail::JsonParser& parser) { JsonNullSerializer::ParseNull(parser); } + struct JsonSerializer { + static inline void parse(JsonNullObject&, detail::JsonParser& parser) { + JsonNullSerializer::ParseNull(parser); + } - static inline void format(const JsonNullObject&, detail::JsonFormatter& formatter) { JsonNullSerializer::FormatNull(formatter); } + static inline void format(const JsonNullObject&, detail::JsonFormatter& formatter) { + JsonNullSerializer::FormatNull(formatter); + } }; template <> - struct JsonSerializer - { - static inline void parse(JsonStructObject& t, detail::JsonParser& parser) { parser.parse(t.Objects); } - static inline void format(const JsonStructObject& t, detail::JsonFormatter& formatter) - { - if (formatter.settings.ordered_struct == false) - { + struct JsonSerializer { + static inline void parse(JsonStructObject& t, detail::JsonParser& parser) { + parser.parse(t.Objects); + } + static inline void format(const JsonStructObject& t, detail::JsonFormatter& formatter) { + if (formatter.settings.ordered_struct == false) { formatter.format(t.Objects); return; } @@ -97,9 +105,12 @@ namespace stream::json }; template <> - struct JsonSerializer - { - static inline void parse(JsonArrayObject& t, detail::JsonParser& parser) { parser.parse(t.Objects); } - static inline void format(const JsonArrayObject& t, detail::JsonFormatter& formatter) { formatter.format(t.Objects); } + struct JsonSerializer { + static inline void parse(JsonArrayObject& t, detail::JsonParser& parser) { + parser.parse(t.Objects); + } + static inline void format(const JsonArrayObject& t, detail::JsonFormatter& formatter) { + formatter.format(t.Objects); + } }; -} +} // namespace stream::json diff --git a/src/stream/json/serializers/std_serializers/basic_std_serializers.h b/src/stream/json/serializers/std_serializers/basic_std_serializers.h index 93a7c9d5..e6827444 100644 --- a/src/stream/json/serializers/std_serializers/basic_std_serializers.h +++ b/src/stream/json/serializers/std_serializers/basic_std_serializers.h @@ -4,22 +4,24 @@ #include -namespace stream::json -{ +namespace stream::json { template <> - struct JsonSerializer - { - static inline void parse(std::string& t, detail::JsonParser& parser) { JsonStringSerializer::ParseSTDString(t, parser); } - static inline void format(const std::string& t, detail::JsonFormatter& formatter) { JsonStringSerializer::FormatSTDString(t, formatter); } + struct JsonSerializer { + static inline void parse(std::string& t, detail::JsonParser& parser) { + JsonStringSerializer::ParseSTDString(t, parser); + } + static inline void format(const std::string& t, detail::JsonFormatter& formatter) { + JsonStringSerializer::FormatSTDString(t, formatter); + } }; template <> - struct JsonSerializer - { - static inline void parse(std::string_view& t, detail::JsonParser& parser) - { + struct JsonSerializer { + static inline void parse(std::string_view& t, detail::JsonParser& parser) { // TODO: } - static inline void format(const std::string_view& t, detail::JsonFormatter& formatter) { JsonStringSerializer::FormatSTDString(t, formatter); } + static inline void format(const std::string_view& t, detail::JsonFormatter& formatter) { + JsonStringSerializer::FormatSTDString(t, formatter); + } }; -} +} // namespace stream::json diff --git a/src/stream/json/serializers/std_serializers/json_map.h b/src/stream/json/serializers/std_serializers/json_map.h index 2c13f25c..8c436e76 100644 --- a/src/stream/json/serializers/std_serializers/json_map.h +++ b/src/stream/json/serializers/std_serializers/json_map.h @@ -4,22 +4,20 @@ #include -namespace stream::json -{ +namespace stream::json { template - struct JsonSerializer> - { + struct JsonSerializer> { using KeyType = K; using StructSubObjectType = T; - static inline void parse(std::map& t, detail::JsonParser& parser) { JsonStructSerializer::LoadAllSubObjects>(t, parser); } - static inline void AddStructSubObject(std::map& t, std::size_t, std::string&& name, StructSubObjectType&& subObject) - { - t.insert({std::move(name), std::move(subObject)}); + static void parse(std::map& t, detail::JsonParser& parser) { + JsonStructSerializer::LoadAllSubObjects>(t, parser); + } + static void add_struct_sub_object(std::map& t, std::size_t /*unused*/, std::string&& name, StructSubObjectType&& sub_object) { + t.insert({std::move(name), std::move(sub_object)}); } - static inline void format(const std::map& t, detail::JsonFormatter& formatter) - { + static void format(const std::map& t, detail::JsonFormatter& formatter) { JsonStructSerializer::FormatBegin(formatter); std::size_t idx = 0; for (const auto& [name, object] : t) @@ -29,19 +27,18 @@ namespace stream::json }; template - struct JsonSerializer> - { + struct JsonSerializer> { using KeyType = K; using StructSubObjectType = T; - static inline void parse(std::multimap& t, detail::JsonParser& parser) { JsonStructSerializer::LoadAllSubObjects>(t, parser); } - static inline void AddStructSubObject(std::multimap& t, std::size_t, std::string&& name, StructSubObjectType&& subObject) - { - t.insert({std::move(name), std::move(subObject)}); + static void parse(std::multimap& t, detail::JsonParser& parser) { + JsonStructSerializer::LoadAllSubObjects>(t, parser); + } + static void add_struct_sub_object(std::multimap& t, std::size_t /*unused*/, std::string&& name, StructSubObjectType&& sub_object) { + t.insert({std::move(name), std::move(sub_object)}); } - static inline void format(const std::multimap& t, detail::JsonFormatter& formatter) - { + static void format(const std::multimap& t, detail::JsonFormatter& formatter) { JsonStructSerializer::FormatBegin(formatter); std::size_t idx = 0; for (const auto& [name, object] : t) @@ -49,4 +46,4 @@ namespace stream::json JsonStructSerializer::FormatEnd(formatter); } }; -} +} // namespace stream::json diff --git a/src/stream/json/serializers/std_serializers/json_unordered_map.h b/src/stream/json/serializers/std_serializers/json_unordered_map.h index 69922eab..ce3ddeee 100644 --- a/src/stream/json/serializers/std_serializers/json_unordered_map.h +++ b/src/stream/json/serializers/std_serializers/json_unordered_map.h @@ -5,22 +5,20 @@ #include -namespace stream::json -{ +namespace stream::json { template - struct JsonSerializer> - { + struct JsonSerializer> { using KeyType = K; using StructSubObjectType = T; - static inline void parse(std::unordered_map& t, detail::JsonParser& parser) { JsonStructSerializer::LoadAllSubObjects>(t, parser); } - static inline void AddStructSubObject(std::unordered_map& t, std::size_t, std::string&& name, StructSubObjectType&& subObject) - { + static inline void parse(std::unordered_map& t, detail::JsonParser& parser) { + JsonStructSerializer::LoadAllSubObjects>(t, parser); + } + static inline void add_struct_sub_object(std::unordered_map& t, std::size_t, std::string&& name, StructSubObjectType&& subObject) { t.insert({std::move(name), std::move(subObject)}); } - static inline void format(const std::unordered_map& t, detail::JsonFormatter& formatter) - { + static inline void format(const std::unordered_map& t, detail::JsonFormatter& formatter) { JsonStructSerializer::FormatBegin(formatter); std::size_t idx = 0; for (const auto& [name, object] : t) @@ -30,22 +28,18 @@ namespace stream::json }; template - struct JsonSerializer> - { + struct JsonSerializer> { using KeyType = K; using StructSubObjectType = T; - static inline void parse(std::unordered_multimap& t, detail::JsonParser& parser) - { + static inline void parse(std::unordered_multimap& t, detail::JsonParser& parser) { JsonStructSerializer::LoadAllSubObjects>(t, parser); } - static inline void AddStructSubObject(std::unordered_multimap& t, std::size_t, std::string&& name, StructSubObjectType&& subObject) - { + static inline void add_struct_sub_object(std::unordered_multimap& t, std::size_t, std::string&& name, StructSubObjectType&& subObject) { t.insert({std::move(name), std::move(subObject)}); } - static inline void format(const std::unordered_multimap& t, detail::JsonFormatter& formatter) - { + static inline void format(const std::unordered_multimap& t, detail::JsonFormatter& formatter) { JsonStructSerializer::FormatBegin(formatter); std::size_t idx = 0; for (const auto& [name, object] : t) @@ -53,4 +47,4 @@ namespace stream::json JsonStructSerializer::FormatEnd(formatter); } }; -} +} // namespace stream::json diff --git a/src/stream/json/serializers/std_serializers/json_vector.h b/src/stream/json/serializers/std_serializers/json_vector.h index 710526b3..4ee5c363 100644 --- a/src/stream/json/serializers/std_serializers/json_vector.h +++ b/src/stream/json/serializers/std_serializers/json_vector.h @@ -5,18 +5,19 @@ #include -namespace stream::json -{ +namespace stream::json { template - struct JsonSerializer> - { + struct JsonSerializer> { using ArraySubObjectType = T; - static inline void parse(std::vector& t, detail::JsonParser& parser) { JsonArraySerializer::LoadAllSubObjects>(t, parser); } - static inline void AddArraySubObject(std::vector& t, std::size_t, ArraySubObjectType&& subObject) { t.emplace_back(std::move(subObject)); } + static inline void parse(std::vector& t, detail::JsonParser& parser) { + JsonArraySerializer::LoadAllSubObjects>(t, parser); + } + static inline void AddArraySubObject(std::vector& t, std::size_t, ArraySubObjectType&& subObject) { + t.emplace_back(std::move(subObject)); + } - static inline void format(const std::vector& t, detail::JsonFormatter& formatter) - { + static inline void format(const std::vector& t, detail::JsonFormatter& formatter) { JsonArraySerializer::FormatBegin(formatter); std::size_t idx = 0; for (const ArraySubObjectType& subObject : t) @@ -24,4 +25,4 @@ namespace stream::json JsonArraySerializer::FormatEnd(formatter); } }; -} +} // namespace stream::json diff --git a/src/stream/profiler/all_events.h b/src/stream/profiler/all_events.h index b315bf98..6a3386cd 100644 --- a/src/stream/profiler/all_events.h +++ b/src/stream/profiler/all_events.h @@ -2,37 +2,30 @@ #include "event.h" -namespace stream::profiler -{ - class DurationEvent : public Event - { +namespace stream::profiler { + class DurationEvent : public Event { public: - DurationEvent(const std::string& name, const std::string& category = "DurationEvent") - : Event(name, category, EventType::Complete) - {} + DurationEvent(const std::string& name, const std::string& category = "DurationEvent") : Event(name, category, EventType::Complete) {} - DurationEvent(std::string&& name, std::string&& category = "DurationEvent") - : Event(std::move(name), std::move(category), EventType::Complete) - {} + DurationEvent(std::string&& name, std::string&& category = "DurationEvent") : Event(std::move(name), std::move(category), EventType::Complete) {} ~DurationEvent() override = default; public: - void start() { trigger(); } - void stop() { info.Duration = profiler::get_microseconds() - info.TimeOfEvent; } + void start() { + trigger(); + } + void stop() { + info.duration = profiler::get_nanoseconds() - info.time_of_event; + } }; - class SampleEvent : public Event - { + class SampleEvent : public Event { public: - SampleEvent(const std::string& name, const std::string& category = "SampleEvent") - : Event(name, category, EventType::Sample) - {} + SampleEvent(const std::string& name, const std::string& category = "SampleEvent") : Event(name, category, EventType::Sample) {} - SampleEvent(std::string&& name, std::string&& category) - : Event(std::move(name), std::move(category), EventType::Sample) - {} + SampleEvent(std::string&& name, std::string&& category) : Event(std::move(name), std::move(category), EventType::Sample) {} ~SampleEvent() override = default; }; -} +} // namespace stream::profiler diff --git a/src/stream/profiler/detail.h b/src/stream/profiler/detail.h index 5ab5d3cc..d530e7d9 100644 --- a/src/stream/profiler/detail.h +++ b/src/stream/profiler/detail.h @@ -2,10 +2,8 @@ #include -namespace stream::profiler -{ - inline double get_microseconds() - { - return (double)std::chrono::time_point_cast(std::chrono::high_resolution_clock::now()).time_since_epoch().count() / 1000; +namespace stream::profiler { + inline std::chrono::nanoseconds get_nanoseconds() { + return std::chrono::time_point_cast(std::chrono::high_resolution_clock::now()).time_since_epoch(); } -}; +}; // namespace stream::profiler diff --git a/src/stream/profiler/event.h b/src/stream/profiler/event.h index 5564399b..a0fe3306 100644 --- a/src/stream/profiler/event.h +++ b/src/stream/profiler/event.h @@ -8,15 +8,14 @@ #include #include #include +#include // https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview -namespace stream::profiler -{ +namespace stream::profiler { int GetPid(); - enum class EventType : char - { + enum class EventType : char { Unknow = '.', DurationBegin = 'b', @@ -47,89 +46,78 @@ namespace stream::profiler Context = ',' // '(' ')' }; - struct EventInfo - { + struct EventInfo { public: EventInfo() - : name("Unknow") - , Category("Unknow") - , type(EventType::Unknow) - , Id(0) - , TimeOfEvent(profiler::get_microseconds()) - , ThreadTimeOfEvent(0) - , Duration(0) - , PID(GetPid()) - , TID(std::hash{}(std::this_thread::get_id())) - , data(nullptr) - {} + : name("Unknow"), + category("Unknow"), + type(EventType::Unknow), + id(0), + time_of_event(profiler::get_nanoseconds()), + duration(0), + pid(GetPid()), + tid(std::hash{}(std::this_thread::get_id())), + data(nullptr) {} EventInfo(const std::string& name, const std::string& category, EventType type, EventData* data = nullptr) - : name(name) - , Category(category) - , type(type) - , Id(0) - , TimeOfEvent(profiler::get_microseconds()) - , ThreadTimeOfEvent(0) - , Duration(0) - , PID(GetPid()) - , TID(std::hash{}(std::this_thread::get_id())) - , data(data) - {} + : name(name), + category(category), + type(type), + id(0), + time_of_event(profiler::get_nanoseconds()), + duration(0), + pid(GetPid()), + tid(std::hash{}(std::this_thread::get_id())), + data(data) {} EventInfo(std::string&& name, std::string&& category, EventType type, EventData* data = nullptr) - : name(std::move(name)) - , Category(std::move(category)) - , type(type) - , Id(0) - , TimeOfEvent(profiler::get_microseconds()) - , ThreadTimeOfEvent(0) - , Duration(0) - , PID(GetPid()) - , TID(std::hash{}(std::this_thread::get_id())) - , data(data) - {} + : name(std::move(name)), + category(std::move(category)), + type(type), + id(0), + time_of_event(profiler::get_nanoseconds()), + duration(0), + pid(GetPid()), + tid(std::hash{}(std::this_thread::get_id())), + data(data) {} public: std::string name; - std::string Category; + std::string category; EventType type; - std::size_t Id; - double TimeOfEvent, ThreadTimeOfEvent; - double Duration; - int PID; - std::size_t TID; + std::size_t id; + std::chrono::nanoseconds time_of_event; + std::chrono::nanoseconds duration; + int pid; + std::size_t tid; std::shared_ptr data; }; - struct Event - { + struct Event { public: Event() = default; - Event(const std::string& name, const std::string& category, EventType type, EventData* data = nullptr) - : info(name, category, type, data) - {} + Event(const std::string& name, const std::string& category, EventType type, EventData* data = nullptr) : info(name, category, type, data) {} - Event(std::string&& name, std::string&& category, EventType type, EventData* data = nullptr) - : info(std::move(name), std::move(category), type, data) - {} + Event(std::string&& name, std::string&& category, EventType type, EventData* data = nullptr) : info(std::move(name), std::move(category), type, data) {} virtual ~Event() = default; public: - void trigger() { info.TimeOfEvent = profiler::get_microseconds(); } + void trigger() { + info.time_of_event = profiler::get_nanoseconds(); + } public: EventInfo info; }; -} +} // namespace stream::profiler -namespace stream::fmt -{ +namespace stream::fmt { template - struct FormatterType - { - [[nodiscard]] static std::expected format(const stream::profiler::EventType& t, FormatterExecutor& executor) - { return executor.ostream.pushback(static_cast(t)); } + struct FormatterType { + [[nodiscard]] static std::expected format(const stream::profiler::EventType& t, FormatterExecutor& executor) { + return executor.ostream.pushback(static_cast(t)); + } }; -} +} // namespace stream::fmt diff --git a/src/stream/profiler/event_data.h b/src/stream/profiler/event_data.h index 6b357f34..96fc861b 100644 --- a/src/stream/profiler/event_data.h +++ b/src/stream/profiler/event_data.h @@ -2,26 +2,27 @@ #include "stream/json.h" -namespace stream::profiler -{ - class EventData - { +namespace stream::profiler { + class EventData { public: virtual ~EventData() = default; public: virtual void to_json(json::detail::JsonFormatter& formatter) const = 0; - virtual void FromJson(json::detail::JsonParser& parser) = 0; + virtual void FromJson(json::detail::JsonParser& parser) = 0; }; - class EventDataJsonObject final : public EventData - { + class EventDataJsonObject final : public EventData { public: ~EventDataJsonObject() override = default; public: - void to_json(json::detail::JsonFormatter& formatter) const override { json::JsonSerializer::format(data, formatter); } - void FromJson(json::detail::JsonParser& parser) override { json::JsonSerializer::parse(data, parser); } + void to_json(json::detail::JsonFormatter& formatter) const override { + json::JsonSerializer::format(data, formatter); + } + void FromJson(json::detail::JsonParser& parser) override { + json::JsonSerializer::parse(data, parser); + } json::JsonStructObject data; }; -} +} // namespace stream::profiler diff --git a/src/stream/profiler/get_pid.cpp b/src/stream/profiler/get_pid.cpp index eefd61ff..78ab09ab 100644 --- a/src/stream/profiler/get_pid.cpp +++ b/src/stream/profiler/get_pid.cpp @@ -9,10 +9,8 @@ #include #endif -namespace stream::profiler -{ - int GetPid() - { +namespace stream::profiler { + int get_pid() { #ifdef STREAMFORMAT_PLATFORM_LINUX return getpid(); #endif @@ -22,4 +20,4 @@ namespace stream::profiler #endif return 0; } -} \ No newline at end of file +} // namespace stream::profiler \ No newline at end of file diff --git a/src/stream/profiler/profiler.h b/src/stream/profiler/profiler.h index ffd8549a..20df09f8 100644 --- a/src/stream/profiler/profiler.h +++ b/src/stream/profiler/profiler.h @@ -7,16 +7,10 @@ #include "event.h" #include "profiler_event_creator.h" -namespace stream::profiler -{ - class Profiler - { +namespace stream::profiler { + class Profiler { public: - explicit Profiler(std::string&& name) - : name(name) - , logger(name) - , profiler_duration(name) - { + explicit Profiler(std::string&& name) : name(name), logger(name), profiler_duration(name) { events.clear(); events.push_back(EventInfo{}); profiler_duration.start(); @@ -25,13 +19,18 @@ namespace stream::profiler ~Profiler() {} public: - void add_event(const Event& event) { add_event_info(event.info); } - void add_event_info(const EventInfo& eventInfo) { events.push_back(eventInfo); } - inline stream::flog::BasicLogger& get_logger() { return logger; } + void add_event(const Event& event) { + add_event_info(event.info); + } + void add_event_info(const EventInfo& eventInfo) { + events.push_back(eventInfo); + } + inline stream::flog::BasicLogger& get_logger() { + return logger; + } public: - static Profiler& get_instance() - { + static Profiler& get_instance() { static Profiler profiler("profiler"); return profiler; } @@ -42,4 +41,4 @@ namespace stream::profiler DurationEvent profiler_duration; std::vector events; }; -} +} // namespace stream::profiler diff --git a/src/stream/profiler/profiler_event_creator.cpp b/src/stream/profiler/profiler_event_creator.cpp index 2cde9e34..f117168f 100644 --- a/src/stream/profiler/profiler_event_creator.cpp +++ b/src/stream/profiler/profiler_event_creator.cpp @@ -1,62 +1,50 @@ #include "profiler_event_creator.h" #include "profiler.h" -namespace stream::profiler -{ - ScopeProfile::~ScopeProfile() - { +namespace stream::profiler { + ScopeProfile::~ScopeProfile() { stop(); - double millis = info.Duration / 1000; - double sec = millis / 1000; + std::chrono::microseconds us = std::chrono::duration_cast(info.duration); + std::chrono::milliseconds const millis = std::chrono::duration_cast(info.duration); + std::chrono::seconds const seconds = std::chrono::duration_cast(info.duration); - if (sec > 1.5) - profiler_.get_logger().trace("{} : {} seconds", info.name, sec); - else if (millis > 5.0) - profiler_.get_logger().trace("{} : {} ms", info.name, millis); + if (seconds.count() > 1.5) + profiler_.get_logger().trace("{} : {} seconds", info.name, seconds.count()); + else if (millis.count() > 5.0) + profiler_.get_logger().trace("{} : {} ms", info.name, millis.count()); else - profiler_.get_logger().trace("{} : {} us", info.name, info.Duration); + profiler_.get_logger().trace("{} : {} us", info.name, us); profiler_.add_event(*this); } - ObjectTracker::ObjectTracker(Profiler& profiler, const std::string& name, const std::string& category) - : profiler_(profiler) - , name_(name) - , category_(category) - { - Event created(name_, category_, EventType::Objectcreated); + ObjectTracker::ObjectTracker(Profiler& profiler, const std::string& name, const std::string& category) : profiler_(profiler), name_(name), category_(category) { + Event const created(name_, category_, EventType::Objectcreated); profiler_.add_event(created); } - ObjectTracker::ObjectTracker(Profiler& profiler, std::string&& name, std::string&& category) - : profiler_(profiler) - , name_(std::move(name)) - , category_(std::move(category)) - { + ObjectTracker::ObjectTracker(Profiler& profiler, std::string&& name, std::string&& category) : profiler_(profiler), name_(std::move(name)), category_(std::move(category)) { Event created(name_, category_, EventType::Objectcreated); - created.info.Id = 10; + created.info.id = 10; profiler_.add_event(created); } - ObjectTracker::~ObjectTracker() - { + ObjectTracker::~ObjectTracker() { Event destroyed(name_, category_, EventType::ObjectDestroyed); - destroyed.info.Id = 10; + destroyed.info.id = 10; profiler_.add_event(destroyed); } - void ObjectTracker::snapshot() - { + void ObjectTracker::snapshot() { Event snapshot(name_, category_, EventType::Objectsnapshot); - snapshot.info.Id = 10; + snapshot.info.id = 10; profiler_.add_event(snapshot); } - void EventCounter::snapshot() - { + void EventCounter::snapshot() { idx_++; - Event snapshot(name_, category_, EventType::Counter); + Event const snapshot(name_, category_, EventType::Counter); profiler_.add_event(snapshot); } -} +} // namespace stream::profiler diff --git a/src/stream/profiler/profiler_event_creator.h b/src/stream/profiler/profiler_event_creator.h index 88d2575c..5799325f 100644 --- a/src/stream/profiler/profiler_event_creator.h +++ b/src/stream/profiler/profiler_event_creator.h @@ -2,24 +2,16 @@ #include "all_events.h" -namespace stream::profiler -{ +namespace stream::profiler { class Profiler; - class ScopeProfile : public DurationEvent - { + class ScopeProfile : public DurationEvent { public: - ScopeProfile(Profiler& profiler, const std::string& name, const std::string& category = "ScopeProfiler") - : DurationEvent(name, category) - , profiler_(profiler) - { + ScopeProfile(Profiler& profiler, const std::string& name, const std::string& category = "ScopeProfiler") : DurationEvent(name, category), profiler_(profiler) { start(); } - ScopeProfile(Profiler& profiler, std::string&& name, std::string&& category = "ScopeProfiler") - : DurationEvent(std::move(name), std::move(category)) - , profiler_(profiler) - { + ScopeProfile(Profiler& profiler, std::string&& name, std::string&& category = "ScopeProfiler") : DurationEvent(std::move(name), std::move(category)), profiler_(profiler) { start(); } @@ -29,8 +21,7 @@ namespace stream::profiler Profiler& profiler_; }; - class ObjectTracker - { + class ObjectTracker { public: ObjectTracker(Profiler& profiler, const std::string& name, const std::string& category = "Tracker"); ObjectTracker(Profiler& profiler, std::string&& name, std::string&& category = "Tracker"); @@ -45,22 +36,12 @@ namespace stream::profiler std::string category_; }; - class EventCounter - { + class EventCounter { public: - EventCounter(Profiler& profiler, const std::string& name, const std::string& category = "EventCounter") - : profiler_(profiler) - , name_(name) - , category_(category) - , idx_(0) - {} + EventCounter(Profiler& profiler, const std::string& name, const std::string& category = "EventCounter") : profiler_(profiler), name_(name), category_(category), idx_(0) {} EventCounter(Profiler& profiler, std::string&& name, std::string&& category = "EventCounter") - : profiler_(profiler) - , name_(std::move(name)) - , category_(std::move(category)) - , idx_(0) - {} + : profiler_(profiler), name_(std::move(name)), category_(std::move(category)), idx_(0) {} public: void snapshot(); @@ -71,4 +52,4 @@ namespace stream::profiler std::string category_; std::uint64_t idx_; }; -} +} // namespace stream::profiler diff --git a/src/stream/profiler/profiler_factory.cpp b/src/stream/profiler/profiler_factory.cpp index 728e4494..830d7792 100644 --- a/src/stream/profiler/profiler_factory.cpp +++ b/src/stream/profiler/profiler_factory.cpp @@ -3,18 +3,16 @@ #include -namespace stream::profiler -{ - void ProfilerFactory::to_json(Profiler& profiler, std::filesystem::path path) - { +namespace stream::profiler { + void ProfilerFactory::to_json(Profiler& profiler, std::filesystem::path path) { profiler.profiler_duration.stop(); profiler.events[0] = profiler.profiler_duration.info; if (path == "") path = std::string(profiler.name) + ".json"; - std::ofstream file(path.string(), std::ios::out); - json::FormatAsJson format_profiler(profiler); + std::ofstream file(path.string(), std::ios::out); + json::FormatAsJson const format_profiler(profiler); fmt::file_print(file, format_profiler).value(); file.close(); } -} +} // namespace stream::profiler diff --git a/src/stream/profiler/profiler_factory.h b/src/stream/profiler/profiler_factory.h index 504112e3..a58697d4 100644 --- a/src/stream/profiler/profiler_factory.h +++ b/src/stream/profiler/profiler_factory.h @@ -4,11 +4,9 @@ #include -namespace stream::profiler -{ - class ProfilerFactory - { +namespace stream::profiler { + class ProfilerFactory { public: static void to_json(Profiler& profiler, std::filesystem::path path = ""); }; -} +} // namespace stream::profiler diff --git a/src/stream/profiler/profiler_json_serializers.h b/src/stream/profiler/profiler_json_serializers.h index 88141bff..91de2082 100644 --- a/src/stream/profiler/profiler_json_serializers.h +++ b/src/stream/profiler/profiler_json_serializers.h @@ -3,81 +3,80 @@ #include "profiler_factory.h" #include "stream/json.h" -namespace stream::json -{ +namespace stream::json { template <> - struct JsonSerializer - { - static inline void format(const profiler::Profiler& t, detail::JsonFormatter& formatter) - { + struct JsonSerializer { + static inline void format(const profiler::Profiler& t, detail::JsonFormatter& formatter) { auto intermediate = formatter.get_struct_intermediate(); intermediate.format("displayTimeUnit", "us"); intermediate.format("traceEvents", t.events); } - static inline void parse(profiler::Profiler& t, detail::JsonParser& parser) - { + static inline void parse(profiler::Profiler& t, detail::JsonParser& parser) { auto intermediate = parser.get_struct_intermediate(); intermediate.parse("traceEvents", t.events); } }; template <> - struct JsonSerializer - { - static inline void format(const profiler::EventType& t, detail::JsonFormatter& formatter) { formatter.format(static_cast(t)); } + struct JsonSerializer { + static inline void format(const profiler::EventType& t, detail::JsonFormatter& formatter) { + formatter.format(static_cast(t)); + } - static inline void parse(profiler::EventType& t, detail::JsonParser& parser) { parser.parse(reinterpret_cast(t)); } + static inline void parse(profiler::EventType& t, detail::JsonParser& parser) { + parser.parse(reinterpret_cast(t)); + } }; template <> - struct JsonSerializer - { - static inline void format(const profiler::EventData& t, detail::JsonFormatter& formatter) { t.to_json(formatter); } + struct JsonSerializer { + static inline void format(const profiler::EventData& t, detail::JsonFormatter& formatter) { + t.to_json(formatter); + } - static inline void parse(profiler::EventData& t, detail::JsonParser& parser) { t.FromJson(parser); } + static inline void parse(profiler::EventData& t, detail::JsonParser& parser) { + t.FromJson(parser); + } }; template <> - struct JsonSerializer - { - static inline void format(const profiler::EventInfo& t, detail::JsonFormatter& formatter) - { + struct JsonSerializer { + static inline void format(const profiler::EventInfo& t, detail::JsonFormatter& formatter) { auto intermediate = formatter.get_struct_intermediate(); intermediate.format("name", t.name); - intermediate.format("cat", t.Category); + intermediate.format("cat", t.category); intermediate.format("ph", t.type); - intermediate.format("pid", t.PID); - intermediate.format("tid", t.TID); - intermediate.format("ts", t.TimeOfEvent); - intermediate.format("dur", t.Duration); - intermediate.format("id", t.Id); + intermediate.format("pid", t.pid); + intermediate.format("tid", t.tid); + intermediate.format("ts", t.time_of_event); + intermediate.format("dur", t.duration); + intermediate.format("id", t.id); if (t.data != nullptr) intermediate.format("args", *t.data); } - static inline void parse(profiler::EventInfo& t, detail::JsonParser& parser) - { + static inline void parse(profiler::EventInfo& t, detail::JsonParser& parser) { auto intermediate = parser.get_struct_intermediate(); intermediate.parse("name", t.name); - intermediate.parse("cat", t.Category); + intermediate.parse("cat", t.category); intermediate.parse("ph", t.type); - intermediate.parse("pid", t.PID); - intermediate.parse("tid", t.TID); - intermediate.parse("ts", t.TimeOfEvent); - intermediate.parse("dur", t.Duration); - intermediate.parse("id", t.Id); + intermediate.parse("pid", t.pid); + intermediate.parse("tid", t.tid); + intermediate.parse("ts", t.time_of_event); + intermediate.parse("dur", t.duration); + intermediate.parse("id", t.id); intermediate.parse("args", *t.data); } }; template <> - struct JsonSerializer - { - static inline void format(const profiler::Event& t, detail::JsonFormatter& formatter) - { + struct JsonSerializer { + static inline void format(const profiler::Event& t, detail::JsonFormatter& formatter) { return JsonSerializer::format(t.info, formatter); } - static inline void parse(profiler::Event& t, detail::JsonParser& parser) { return JsonSerializer::parse(t.info, parser); } + static inline void parse(profiler::Event& t, detail::JsonParser& parser) { + return JsonSerializer::parse(t.info, parser); + } }; -} +} // namespace stream::json diff --git a/src/stream/profiler/profiler_macros.h b/src/stream/profiler/profiler_macros.h index 041f096b..7805dc71 100644 --- a/src/stream/profiler/profiler_macros.h +++ b/src/stream/profiler/profiler_macros.h @@ -3,9 +3,8 @@ #ifdef STREAMFORMAT_PROFILING_ENABLE #define SFP_PROFILE_FUNCTION() stream::profiler::ScopeProfile profile##__LINE__(stream::profiler::Profiler::get_instance(), __FUNCSIG__, "Function") -#define SFP_PROFILE_FUNCTION_FMT(...) \ - stream::profiler::ScopeProfile profile##__LINE__(stream::profiler::Profiler::get_instance(), \ - stream::profiler::fmt::format_string(__VA_ARGS__), "Function") +#define SFP_PROFILE_FUNCTION_FMT(...) \ + stream::profiler::ScopeProfile profile##__LINE__(stream::profiler::Profiler::get_instance(), stream::profiler::fmt::format_string(__VA_ARGS__), "Function") #define SFP_SAVE_DEFAULT_PROFILER() stream::profiler::ProfilerFactory::to_json(stream::profiler::Profiler::get_instance()) #else // STREAMFORMAT_PROFILING_ENABLE diff --git a/src/stream/tester/copy_move_check.h b/src/stream/tester/copy_move_check.h index 1507e046..ee27c72d 100644 --- a/src/stream/tester/copy_move_check.h +++ b/src/stream/tester/copy_move_check.h @@ -2,76 +2,58 @@ #include "stream/flog.h" -namespace stream::tester -{ - class CopyMoveCheck - { +namespace stream::tester { + class CopyMoveCheck { public: static inline flog::BasicLogger logger; public: - CopyMoveCheck(const std::string& name) - : name_(name) - { + CopyMoveCheck(const std::string& name) : name_(name) { logger.info("CopyMoveCheck {} : {:C:red} ( {:C:red} )", name_, "Default (copy string) Constructor", "TestCopy(const std::string& name)"); } - CopyMoveCheck(std::string&& name) - : name_(std::move(name)) - { + CopyMoveCheck(std::string&& name) : name_(std::move(name)) { logger.info("CopyMoveCheck {} : {:C:red} ( {:C:red} )", name_, "Default (move string) Constructor", "TestCopy(std::string&& name)"); } - CopyMoveCheck(CopyMoveCheck& other) - : name_("Copy of " + other.name_) - { + CopyMoveCheck(CopyMoveCheck& other) : name_("Copy of " + other.name_) { logger.info("CopyMoveCheck {} : {:C:red} ( {:C:red} )", name_, "Copy Constructor", "TestCopy(TestCopy&)"); } - CopyMoveCheck(const CopyMoveCheck& other) - : name_("Copy of " + other.name_) - { + CopyMoveCheck(const CopyMoveCheck& other) : name_("Copy of " + other.name_) { logger.info("CopyMoveCheck {} : {:C:red} ( {:C:red} )", name_, "Const Copy Constructor", "TestCopy(const TestCopy&)"); } - CopyMoveCheck(CopyMoveCheck&& other) noexcept - : name_("Move of " + other.name_) - { + CopyMoveCheck(CopyMoveCheck&& other) noexcept : name_("Move of " + other.name_) { logger.info("CopyMoveCheck {} : {:C:red} ( {:C:red} )", name_, "Move Constructor", "TestCopy(TestCopy&&)"); } - CopyMoveCheck(const CopyMoveCheck&& other) noexcept - : name_("Move of " + other.name_) - { + CopyMoveCheck(const CopyMoveCheck&& other) noexcept : name_("Move of " + other.name_) { logger.info("CopyMoveCheck {} : {:C:red} ( {:C:red} )", name_, "Const Move Constructor", "TestCopy(const TestCopy&&)"); } - CopyMoveCheck& operator=(CopyMoveCheck& other) - { + CopyMoveCheck& operator=(CopyMoveCheck& other) { name_ = "Copy Of " + other.name_; logger.info("CopyMoveCheck {} : {:C:red} ( {:C:red} )", name_, "Copy Assignment", "TestCopy& operator=(TestCopy&)"); return *this; } - CopyMoveCheck& operator=(const CopyMoveCheck& other) - { + CopyMoveCheck& operator=(const CopyMoveCheck& other) { name_ = "Copy Of " + other.name_; logger.info("CopyMoveCheck {} : {:C:red} ( {:C:red} )", name_, "Const Copy Assignment", "TestCopy& operator=(const TestCopy&)"); return *this; } - CopyMoveCheck& operator=(CopyMoveCheck&& other) noexcept - { + CopyMoveCheck& operator=(CopyMoveCheck&& other) noexcept { name_ = "Move Of " + other.name_; logger.info("CopyMoveCheck {} : {:C:red} ( {:C:red} )", name_, "Move Assignment", "TestCopy& operator=(TestCopy&&)"); return *this; } - CopyMoveCheck& operator=(const CopyMoveCheck&& other) noexcept - { + CopyMoveCheck& operator=(const CopyMoveCheck&& other) noexcept { name_ = "Move Of " + other.name_; logger.info("CopyMoveCheck {} : {:C:red} ( {:C:red} )", name_, "Const Move Assignment", "TestCopy& operator=(const TestCopy&&)"); @@ -81,4 +63,4 @@ namespace stream::tester private: std::string name_; }; -} +} // namespace stream::tester diff --git a/src/stream/tester/test_suite/basic_test.h b/src/stream/tester/test_suite/basic_test.h index 0a72e22c..74aaf6d7 100644 --- a/src/stream/tester/test_suite/basic_test.h +++ b/src/stream/tester/test_suite/basic_test.h @@ -4,26 +4,20 @@ #include "stream/core/prelude.h" -namespace stream::tester::detail -{ - struct TestFunction : public Test - { +namespace stream::tester::detail { + struct TestFunction : public Test { public: using FuncType = std::function; public: - TestFunction(std::string_view name, TestSuite& link, FuncType func_, const fmt::detail::FileLocation& location) - : Test(name, link, location) - , func(func_) - { + TestFunction(std::string_view name, TestSuite& link, FuncType func_, const fmt::detail::FileLocation& location) : Test(name, link, location), func(func_) { link.tests.insert({std::string{name}, this}); } ~TestFunction() override = default; protected: - TestStatus run_impl() override - { + TestStatus run_impl() override { func(*this); return TestStatus::ok; } @@ -50,30 +44,24 @@ namespace stream::tester::detail }; template - void TestFunction::test_eq(T result, std::convertible_to auto expected, std::string_view testView, [[maybe_unused]] int line) - { + void TestFunction::test_eq(T result, std::convertible_to auto expected, std::string_view testView, [[maybe_unused]] int line) { T expected_as_T = static_cast(expected); - if (result != expected_as_T) - { + if (result != expected_as_T) { link.test_logger.error("{C:red}{} return {} instead of {}", testView, result, expected, FORMAT_SV("test_name", name)).value(); throw TestFailure{}; } link.test_logger.trace("{C:green}{} return {}", testView, result, FORMAT_SV("test_name", name)).value(); } template - void TestFunction::test_not_eq(T result, std::convertible_to auto notExpected, std::string_view testView, [[maybe_unused]] int line) - { - if (result == static_cast(notExpected)) - { + void TestFunction::test_not_eq(T result, std::convertible_to auto notExpected, std::string_view testView, [[maybe_unused]] int line) { + if (result == static_cast(notExpected)) { link.test_logger.error("{C:red}{} return {} but that result was prohibited", testView, result, FORMAT_SV("test_name", name)).value(); throw TestFailure{}; } link.test_logger.trace("{C:green}{} return {}", testView, result, FORMAT_SV("test_name", name)).value(); } - inline void TestFunction::test_assert(bool assert, std::string_view assertView, [[maybe_unused]] int line) - { - if (assert == false) - { + inline void TestFunction::test_assert(bool assert, std::string_view assertView, [[maybe_unused]] int line) { + if (assert == false) { link.test_logger.error("{C:red}ASSERT FAILED : {}", assertView, FORMAT_SV("test_name", name)).value(); throw TestFailure{}; } @@ -82,16 +70,14 @@ namespace stream::tester::detail template - void TestFunction::test_eq(std::expected result, std::convertible_to auto expected, std::string_view testView, [[maybe_unused]] int line) - { + void TestFunction::test_eq(std::expected result, std::convertible_to auto expected, std::string_view testView, [[maybe_unused]] int line) { if (result.has_value()) test_eq(result.value(), expected, testView, line); else assert_expected(result, testView, line); } template - void TestFunction::test_not_eq(std::expected result, std::convertible_to auto notExpected, std::string_view testView, [[maybe_unused]] int line) - { + void TestFunction::test_not_eq(std::expected result, std::convertible_to auto notExpected, std::string_view testView, [[maybe_unused]] int line) { if (result.has_value()) test_eq(result.value(), notExpected, testView, line); else @@ -100,38 +86,34 @@ namespace stream::tester::detail template - void TestFunction::assert_expected(std::expected result, std::string_view testView, int line) - { - if (result.has_value() == false) - { + void TestFunction::assert_expected(std::expected result, std::string_view testView, int line) { + if (result.has_value() == false) { link.test_logger.error("{C:red}{} return an error: {}", testView, result.error(), FORMAT_SV("test_name", name)).value(); throw TestFailure{}; } } template - void TestFunction::assert_optional(std::optional result, std::string_view testView, int line) - { - if (result.has_value() == false) - { + void TestFunction::assert_optional(std::optional result, std::string_view testView, int line) { + if (result.has_value() == false) { link.test_logger.error("{C:red}{} didn't return any value", testView, FORMAT_SV("test_name", name)).value(); throw TestFailure{}; } } -} +} // namespace stream::tester::detail #define STREAMFORMAT_TESTINTERNAL_FUNC_DECLARE_EXEC(TestSuiteName, TestName) \ void STREAMFORMAT_TESTINTERNAL_FUNC_EXEC_NAME(TestSuiteName, TestName)(stream::tester::detail::TestFunction & link); -#define STREAMFORMAT_TESTINTERNAL_FUNC_CREATE(TestSuiteName, TestName, ...) \ +#define STREAMFORMAT_TESTINTERNAL_FUNC_CREATE(TestSuiteName, TestName, ...) \ volatile stream::tester::detail::TestFunction STREAMFORMAT_TESTINTERNAL_FUNC_NAME(TestSuiteName, TestName)( \ #TestName, STREAMFORMAT_TESTINTERNAL_SUITE_NAME(TestSuiteName), STREAMFORMAT_TESTINTERNAL_FUNC_EXEC_NAME(TestSuiteName, TestName), STREAMFORMAT_FMT_FILE_LOCATION()) -#define SFT_TEST_FUNC(TestSuiteName, TestName) \ +#define SFT_TEST_FUNC(TestSuiteName, TestName) \ STREAMFORMAT_TESTINTERNAL_FUNC_DECLARE_EXEC(TestSuiteName, TestName) \ STREAMFORMAT_TESTINTERNAL_FUNC_CREATE(TestSuiteName, TestName); \ void STREAMFORMAT_TESTINTERNAL_FUNC_EXEC_NAME(TestSuiteName, TestName)(stream::tester::detail::TestFunction & link) -#define SFT_ASSERT(Test) link.test_assert(Test, #Test, __LINE__) -#define SFT_EQ(Test, Expected) link.test_eq(Test, Expected, #Test, __LINE__) +#define SFT_ASSERT(Test) link.test_assert(Test, #Test, __LINE__) +#define SFT_EQ(Test, Expected) link.test_eq(Test, Expected, #Test, __LINE__) #define SFT_NEQ(Test, NotExpected) link.test_not_eq(Test, NotExpected, #Test, __LINE__) -#define SFT_EXPECTED_VALUE(Test) link.assert_expected(Test, #Test, __LINE__) +#define SFT_EXPECTED_VALUE(Test) link.assert_expected(Test, #Test, __LINE__) diff --git a/src/stream/tester/test_suite/test_suite.cpp b/src/stream/tester/test_suite/test_suite.cpp index 5f94bede..fcbc09ab 100644 --- a/src/stream/tester/test_suite/test_suite.cpp +++ b/src/stream/tester/test_suite/test_suite.cpp @@ -1,11 +1,11 @@ #include "test_suite.h" +#include + #include "stream/profiler.h" -namespace stream::tester -{ - bool TestSuitesManager::exec_all_test_suites() - { +namespace stream::tester { + bool TestSuitesManager::exec_all_test_suites() { detail::TestStatusBank status; for (auto& [name, test_suite] : test_suites) @@ -17,14 +17,12 @@ namespace stream::tester else logger.error("{C:white}RESULT => {C:+black}{}", status); - return status.error_status(); + return status.error_status() != 0u; } -} +} // namespace stream::tester -namespace stream::tester::detail -{ - TestStatusBank TestSuite::exec_all_tests() - { +namespace stream::tester::detail { + TestStatusBank TestSuite::exec_all_tests() { if (parent == nullptr) profiler = new profiler::Profiler("TestSuite_" + name); else @@ -34,49 +32,45 @@ namespace stream::tester::detail logger.info("{C:+black}{}", "BEGIN"); profiler::DurationEvent test_suite_duration(get_full_name(), "Profile"); test_suite_duration.start(); - bool first_test_suite = true; - TestStatusBank test_suite_status; + bool first_test_suite = true; + TestStatusBank test_suite_status; profiler::DurationEvent tests_duration("tests", "Profile"); tests_duration.start(); - for (auto& [name, test] : tests) - { + for (auto& [name, test] : tests) { first_test_suite = false; profiler::DurationEvent current_test_duration(test->name, "Profile"); TestStatus test_status = TestStatus::fail; current_test_duration.start(); if (TestSuitesManager::performance_test.enable == false) test_status = test->run(); - else - { - for (std::uint32_t i = 0; i < TestSuitesManager::performance_test.nb_samples; ++i) - { + else { + for (std::uint32_t i = 0; i < TestSuitesManager::performance_test.nb_samples; ++i) { test_status = test->run(); if (test_status != TestStatus::ok) break; } } current_test_duration.stop(); - if (test_status != TestStatus::ok) - {} + if (test_status != TestStatus::ok) { + } test_suite_status.add_test_status(test_status); logger.debug("{} -> {}", test_status, name); profiler->add_event(current_test_duration); } tests_duration.stop(); - profiler::DurationEvent groupsDuration("Groups", "Profile"); - groupsDuration.start(); - for (auto& [name, test_suite] : test_suites_linked) - { + profiler::DurationEvent groups_duration("Groups", "Profile"); + groups_duration.start(); + for (auto& [name, test_suite] : test_suites_linked) { if (first_test_suite) first_test_suite = false; else std::cout << std::endl; test_suite_status.add(test_suite->exec_all_tests()); } - groupsDuration.stop(); + groups_duration.stop(); test_suite_duration.stop(); profiler->add_event(tests_duration); - profiler->add_event(groupsDuration); + profiler->add_event(groups_duration); profiler->add_event(test_suite_duration); if (test_suite_status.is_all_ok()) @@ -84,8 +78,7 @@ namespace stream::tester::detail else logger.error("{C:+black}{}", test_suite_status); - if (parent == nullptr) - { + if (parent == nullptr) { profiler::ProfilerFactory::to_json(*profiler); delete profiler; } @@ -93,53 +86,43 @@ namespace stream::tester::detail return test_suite_status; } - void TestSuite::init_logger() - { - if (TestSuitesManager::verbose == false) - { + void TestSuite::init_logger() { + if (TestSuitesManager::verbose == false) { logger.set_severity(flog::LogSeverity::Debug); test_logger.set_severity(flog::LogSeverity::Debug); - } - else - { + } else { logger.set_severity(flog::LogSeverity::Trace); test_logger.set_severity(flog::LogSeverity::Trace); } - std::string time_pattern = ""; + std::string time_pattern; if (TestSuitesManager::print_time) time_pattern = "[{T:pattern='%h:%m:%s:%ms'}] "; - if (parent == nullptr) - { + if (parent == nullptr) { logger.set_name(name); logger.SetRealPattern("{C:+black}" + time_pattern + "{name} >> {color}{data}"); test_logger.set_name(name + ".{test_name}"); test_logger.SetRealPattern("{C:+black}" + time_pattern + "{name} >> {color}{data}"); - } - else - { - std::string correctedName = get_corrected_size_name(); - logger.set_name(correctedName); + } else { + std::string const corrected_name = get_corrected_size_name(); + logger.set_name(corrected_name); logger.set_real_pattern_strmv("{C:+black}" + time_pattern + "{name} >> {color}{data}"); - test_logger.set_name(correctedName + ".{test_name}"); + test_logger.set_name(corrected_name + ".{test_name}"); test_logger.set_real_pattern_strmv("{C:+black}" + time_pattern + "{name} >> {color}{data}"); } } - std::string TestSuite::get_full_name() - { + std::string TestSuite::get_full_name() const { if (parent == nullptr) return name; return parent->get_full_name() + "::" + name; } - std::string TestSuite::get_corrected_size_name() - { + std::string TestSuite::get_corrected_size_name() { if (parent == nullptr) return name; std::size_t biggest_name = 0; - for (auto& [name, test_suite] : parent->test_suites_linked) - { - std::size_t tmp = test_suite->name.size(); - if (tmp > biggest_name) biggest_name = tmp; + for (auto& [name, test_suite] : parent->test_suites_linked) { + std::size_t const tmp = test_suite->name.size(); + biggest_name = std::max(tmp, biggest_name); } std::string res = get_full_name(); biggest_name -= name.size(); @@ -149,10 +132,8 @@ namespace stream::tester::detail return res; } - profiler::Profiler& TestSuite::get_profiler() - { - if (parent == nullptr) - return *profiler; + profiler::Profiler& TestSuite::get_profiler() const { + if (parent == nullptr) return *profiler; return parent->get_profiler(); } -} +} // namespace stream::tester::detail diff --git a/src/stream/tester/test_suite/test_suite.h b/src/stream/tester/test_suite/test_suite.h index 580fed55..f05a4a38 100644 --- a/src/stream/tester/test_suite/test_suite.h +++ b/src/stream/tester/test_suite/test_suite.h @@ -10,32 +10,21 @@ #include #include -namespace stream::tester -{ - class TestFailure - { - }; +namespace stream::tester { + class TestFailure {}; - enum class TestStatus : int - { + enum class TestStatus : int { ok, fail, Crash }; -} +} // namespace stream::tester -namespace stream::tester::detail -{ +namespace stream::tester::detail { class TestSuite; - class Test - { + class Test { public: - Test(std::string_view name_, TestSuite& link, const fmt::detail::FileLocation& location) - : name(name_) - , link(link) - , location(location) - , last_status(TestStatus::ok) - {} + Test(std::string_view name_, TestSuite& link, const fmt::detail::FileLocation& location) : name(name_), link(link), location(location), last_status(TestStatus::ok) {} virtual ~Test() = default; @@ -43,18 +32,12 @@ namespace stream::tester::detail virtual TestStatus run_impl() = 0; public: - TestStatus run() - { - try - { + TestStatus run() { + try { return last_status = run_impl(); - } - catch (const TestFailure&) - { + } catch (const TestFailure&) { return last_status = TestStatus::fail; - } - catch (...) - { + } catch (...) { return last_status = TestStatus::Crash; } } @@ -66,21 +49,17 @@ namespace stream::tester::detail TestStatus last_status; }; - struct TestStatusBank - { - void reset() - { - tests_done = 0; - tests_ok = 0; - tests_failed = 0; - tests_crash = 0; + struct TestStatusBank { + void reset() { + tests_done = 0; + tests_ok = 0; + tests_failed = 0; + tests_crash = 0; } - void add_test_status(TestStatus status) - { + void add_test_status(TestStatus status) { tests_done++; - switch (status) - { + switch (status) { case TestStatus::ok: tests_ok++; break; @@ -93,73 +72,62 @@ namespace stream::tester::detail } } - void add(TestStatusBank status) - { + void add(TestStatusBank status) { tests_done += status.tests_done; tests_ok += status.tests_ok; tests_failed += status.tests_failed; tests_crash += status.tests_crash; } - bool is_all_ok() { return tests_done == tests_ok && tests_crash == 0 && tests_failed == 0; } + bool is_all_ok() { + return tests_done == tests_ok && tests_crash == 0 && tests_failed == 0; + } - std::uint32_t error_status() { return tests_done - tests_ok; } + std::uint32_t error_status() { + return tests_done - tests_ok; + } - std::uint32_t tests_done = 0; - std::uint32_t tests_ok = 0; - std::uint32_t tests_failed = 0; - std::uint32_t tests_crash = 0; + std::uint32_t tests_done = 0; + std::uint32_t tests_ok = 0; + std::uint32_t tests_failed = 0; + std::uint32_t tests_crash = 0; }; class TestSuite; -} -namespace stream::tester -{ - struct performance_testData - { - bool enable = false; +} // namespace stream::tester::detail +namespace stream::tester { + struct performance_testData { + bool enable = false; std::uint32_t nb_samples = 10; }; - struct ConcurrencySpecificationData - { + struct ConcurrencySpecificationData { bool enable = false; }; - class TestSuitesManager - { + class TestSuitesManager { public: static bool exec_all_test_suites(); static inline std::unordered_map test_suites; public: - static inline bool verbose = false; - static inline bool print_time = false; - static inline performance_testData performance_test = performance_testData{}; + static inline bool verbose = false; + static inline bool print_time = false; + static inline performance_testData performance_test = performance_testData{}; static inline ConcurrencySpecificationData concurrency_specification = ConcurrencySpecificationData{}; }; -} -namespace stream::tester::detail -{ - struct TestSuiteData - { +} // namespace stream::tester +namespace stream::tester::detail { + struct TestSuiteData { bool redirect_stdout = false; bool redirect_stdin = false; bool redirect_stderr = false; }; - class TestSuite - { + class TestSuite { public: TestSuite(std::string_view name_, TestSuiteData extra_ = TestSuiteData{}, TestSuite* parent_ = nullptr) - : name(name_) - , tests() - , extra(extra_) - , logger() - , test_logger() - , profiler(nullptr) - , parent(parent_) - { + : name(name_), tests(), extra(extra_), logger(), test_logger(), profiler(nullptr), parent(parent_) { if (parent == nullptr) TestSuitesManager::test_suites.insert({name, this}); else @@ -170,10 +138,10 @@ namespace stream::tester::detail std::unordered_map tests; std::unordered_map test_suites_linked; - TestSuiteData extra; - flog::BasicLogger logger; - flog::BasicLogger test_logger; - profiler::Profiler* profiler; + TestSuiteData extra; + flog::BasicLogger logger; + flog::BasicLogger test_logger; + profiler::Profiler* profiler; TestSuite* parent; @@ -181,29 +149,26 @@ namespace stream::tester::detail void init_logger(); private: - std::string get_full_name(); + std::string get_full_name() const; std::string get_corrected_size_name(); - profiler::Profiler& get_profiler(); + profiler::Profiler& get_profiler() const; public: TestStatusBank exec_all_tests(); }; -} +} // namespace stream::tester::detail -namespace stream::fmt -{ +namespace stream::fmt { template - struct FormatterType - { - [[nodiscard]] static std::expected format(const stream::tester::detail::TestSuite& t, FormatterExecutor& executor) - { return executor.ostream.fast_write_string(t.name); } + struct FormatterType { + [[nodiscard]] static std::expected format(const stream::tester::detail::TestSuite& t, FormatterExecutor& executor) { + return executor.ostream.fast_write_string(t.name); + } }; template - struct FormatterType - { - [[nodiscard]] static std::expected format(const stream::tester::detail::Test& t, FormatterExecutor& executor) - { + struct FormatterType { + [[nodiscard]] static std::expected format(const stream::tester::detail::Test& t, FormatterExecutor& executor) { SF_TRY(buf::WriteManip(executor.ostream).fast_write_string(t.link.name)); SF_TRY(buf::WriteManip(executor.ostream).fast_write_string_literal("::")); SF_TRY(buf::WriteManip(executor.ostream).fast_write_string(t.name)); @@ -212,12 +177,9 @@ namespace stream::fmt }; template - struct FormatterType - { - [[nodiscard]] static std::expected format(const stream::tester::TestStatus& status, FormatterExecutor& executor) - { - switch (status) - { + struct FormatterType { + [[nodiscard]] static std::expected format(const stream::tester::TestStatus& status, FormatterExecutor& executor) { + switch (status) { case stream::tester::TestStatus::ok: return executor.run("[ {C:green}OK{C} ]"); case stream::tester::TestStatus::fail: @@ -230,52 +192,52 @@ namespace stream::fmt }; template - struct FormatterType - { - [[nodiscard]] static std::expected format(const stream::tester::detail::TestStatusBank& status_bank, FormatterExecutor& executor) - { + struct FormatterType { + [[nodiscard]] static std::expected format(const stream::tester::detail::TestStatusBank& status_bank, FormatterExecutor& executor) { SF_TRY(buf::WriteManip(executor.ostream).fast_write_string_literal("tests_done ")); SF_TRY(executor.run("{:C:white}", status_bank.tests_done)); SF_TRY(buf::WriteManip(executor.ostream).fast_write_string_literal(" | testsOK ")); - if (status_bank.tests_ok == status_bank.tests_done) - { SF_TRY(executor.run("{:C:green}", status_bank.tests_ok)); } - else - { SF_TRY(executor.run("{:C:yellow}", status_bank.tests_ok)); } + if (status_bank.tests_ok == status_bank.tests_done) { + SF_TRY(executor.run("{:C:green}", status_bank.tests_ok)); + } else { + SF_TRY(executor.run("{:C:yellow}", status_bank.tests_ok)); + } SF_TRY(buf::WriteManip(executor.ostream).fast_write_string_literal(" | testsFAIL ")); - if (status_bank.tests_failed == 0) - { SF_TRY(executor.run("{:C:green}", status_bank.tests_failed)); } - else - { SF_TRY(executor.run("{:C:red}", status_bank.tests_failed)); } + if (status_bank.tests_failed == 0) { + SF_TRY(executor.run("{:C:green}", status_bank.tests_failed)); + } else { + SF_TRY(executor.run("{:C:red}", status_bank.tests_failed)); + } SF_TRY(buf::WriteManip(executor.ostream).fast_write_string_literal(" | TestCrash ")); - if (status_bank.tests_crash == 0) - { SF_TRY(executor.run("{:C:green}", status_bank.tests_crash)); } - else - { SF_TRY(executor.run("{:C:magenta}", status_bank.tests_crash)); } + if (status_bank.tests_crash == 0) { + SF_TRY(executor.run("{:C:green}", status_bank.tests_crash)); + } else { + SF_TRY(executor.run("{:C:magenta}", status_bank.tests_crash)); + } return {}; } }; -} +} // namespace stream::fmt //-------------------- Base --------------------// -#define STREAMFORMAT_TESTINTERNAL_SUITE_NAME(TestSuiteName) TestSuite_##TestSuiteName -#define STREAMFORMAT_TESTINTERNAL_FUNC_NAME(TestSuiteName, TestName) TestSuite_##TestSuiteName##TestName +#define STREAMFORMAT_TESTINTERNAL_SUITE_NAME(TestSuiteName) TestSuite_##TestSuiteName +#define STREAMFORMAT_TESTINTERNAL_FUNC_NAME(TestSuiteName, TestName) TestSuite_##TestSuiteName##TestName #define STREAMFORMAT_TESTINTERNAL_FUNC_EXEC_NAME(TestSuiteName, TestName) TestSuite_##TestSuiteName##TestName##_ExecMethod #define STREAMFORMAT_TESTINTERNAL_SUITE_EXTRA(...) \ - stream::tester::detail::TestSuiteData \ - { \ - __VA_ARGS__ \ + stream::tester::detail::TestSuiteData { \ + __VA_ARGS__ \ } //-------------------- TestSuite --------------------// #define SFT_TEST_SUITE(TestSuiteName, ...) \ stream::tester::detail::TestSuite STREAMFORMAT_TESTINTERNAL_SUITE_NAME(TestSuiteName)(#TestSuiteName, STREAMFORMAT_TESTINTERNAL_SUITE_EXTRA(__VA_ARGS__)) -#define SFT_TEST_GROUP(TestSuiteName, GroupName, ...) \ +#define SFT_TEST_GROUP(TestSuiteName, GroupName, ...) \ stream::tester::detail::TestSuite STREAMFORMAT_TESTINTERNAL_SUITE_NAME(GroupName)(#GroupName, STREAMFORMAT_TESTINTERNAL_SUITE_EXTRA(__VA_ARGS__), \ - &STREAMFORMAT_TESTINTERNAL_SUITE_NAME(TestSuiteName)) + &STREAMFORMAT_TESTINTERNAL_SUITE_NAME(TestSuiteName)) -#define SFT_TEST_SUITE_DECLARATION(TestSuiteName, ...) stream::tester::detail::TestSuite STREAMFORMAT_TESTINTERNAL_SUITE_NAME(TestSuiteName) +#define SFT_TEST_SUITE_DECLARATION(TestSuiteName, ...) stream::tester::detail::TestSuite STREAMFORMAT_TESTINTERNAL_SUITE_NAME(TestSuiteName) #define SFT_TEST_GROUP_DECLARATION(TestSuiteName, GroupName, ...) stream::tester::detail::TestSuite STREAMFORMAT_TESTINTERNAL_SUITE_NAME(GroupName) diff --git a/src/stream/tester/tests_macros.h b/src/stream/tester/tests_macros.h index 3c004dcc..53e9102a 100644 --- a/src/stream/tester/tests_macros.h +++ b/src/stream/tester/tests_macros.h @@ -3,26 +3,23 @@ #include "stream/flog.h" #define STREAMFORMAT_TEST_TRACE(...) stream::Test::TestCore::get_logger().trace(__VA_ARGS__) -#define STREAMFORMAT_TEST_INFO(...) stream::Test::TestCore::get_logger().info(__VA_ARGS__) -#define STREAMFORMAT_TEST_WARN(...) stream::Test::TestCore::get_logger().warn(__VA_ARGS__) +#define STREAMFORMAT_TEST_INFO(...) stream::Test::TestCore::get_logger().info(__VA_ARGS__) +#define STREAMFORMAT_TEST_WARN(...) stream::Test::TestCore::get_logger().warn(__VA_ARGS__) #define STREAMFORMAT_TEST_ERROR(...) stream::Test::TestCore::get_logger().error(__VA_ARGS__) #define STREAMFORMAT_TEST_FATAL(...) stream::Test::TestCore::get_logger().fatal(__VA_ARGS__) -#define STREAMFORMAT_TEST_OK(...) stream::Test::TestCore::get_logger().ok(__VA_ARGS__) -#define STREAMFORMAT_TEST_FAIL(...) stream::Test::TestCore::get_logger().fail(__VA_ARGS__) +#define STREAMFORMAT_TEST_OK(...) stream::Test::TestCore::get_logger().ok(__VA_ARGS__) +#define STREAMFORMAT_TEST_FAIL(...) stream::Test::TestCore::get_logger().fail(__VA_ARGS__) #define STREAMFORMAT_TEST_BASIC(...) stream::Test::TestCore::get_logger().basic(__VA_ARGS__) -namespace stream::Test -{ - class TestCore - { +namespace stream::test { + class TestCore { public: - static flog::BasicLogger& get_logger() - { - static flog::BasicLogger instance("stream-Test", "{name} {color} -> {data}"); - return instance; + static flog::BasicLogger& get_logger() { + static flog::BasicLogger g_instance("stream-Test", "{name} {color} -> {data}"); + return g_instance; } }; -} +} // namespace stream::test // Assert log if false #define STREAMFORMAT_TEST_ASSERT(x) \ @@ -30,23 +27,23 @@ namespace stream::Test // Check if false #define STREAMFORMAT_TEST_TEST(x) \ - if (x) \ + if (x) \ STREAMFORMAT_TEST_OK("TEST OK : {:C:green}", #x); \ - else \ + else \ STREAMFORMAT_TEST_FAIL("TEST FAIL : {:C:red}", #x) // Check if equal with file printed #define STREAMFORMAT_TEST_EQ(x, y) \ - if (x == y) \ + if (x == y) \ STREAMFORMAT_TEST_OK("{C:green}{} == {}", #x, #y); \ - else \ + else \ STREAMFORMAT_TEST_FAIL("{C:red}{} == {}", #x, #y) // Check if not equal with file printed #define STREAMFORMAT_TEST_NEQ(x, y) \ - if (x != y) \ + if (x != y) \ STREAMFORMAT_TEST_OK("{C:green}{} != {}", #x, #y); \ - else \ + else \ STREAMFORMAT_TEST_FAIL("{C:red}{} != {}", #x, #y) #define STREAMFORMAT_TEST_FN(fn, resExpected) \ @@ -70,11 +67,11 @@ namespace stream::Test #ifdef STREAMFORMAT_SFTM_ENABLE -#define SFTM_ASSERT(x) STREAMFORMAT_TEST_ASSERT(x) -#define SFTM_TEST(x) STREAMFORMAT_TEST_TEST(x) -#define SFTM_EQ(x, y) STREAMFORMAT_TEST_EQ(x, y) -#define SFTM_NEQ(x, y) STREAMFORMAT_TEST_NEQ(x, y) -#define SFTM_FN(fn, resExpected) STREAMFORMAT_TEST_FN(fn, resExpected) +#define SFTM_ASSERT(x) STREAMFORMAT_TEST_ASSERT(x) +#define SFTM_TEST(x) STREAMFORMAT_TEST_TEST(x) +#define SFTM_EQ(x, y) STREAMFORMAT_TEST_EQ(x, y) +#define SFTM_NEQ(x, y) STREAMFORMAT_TEST_NEQ(x, y) +#define SFTM_FN(fn, resExpected) STREAMFORMAT_TEST_FN(fn, resExpected) #define SFTM_FNFMT(fn, resExpected, ...) STREAMFORMAT_TEST_FNFMT(fn, resExpected, __VA_ARGS__) #endif /* STREAMFORMAT_SFTM_ENABLE */ diff --git a/tests/fmt/complex_pattern.cpp b/tests/fmt/complex_pattern.cpp index 1a2fc0a3..267f6dd2 100644 --- a/tests/fmt/complex_pattern.cpp +++ b/tests/fmt/complex_pattern.cpp @@ -3,13 +3,16 @@ #include "base_fmt_tests.h" +// NOLINTBEGIN(misc-const-correctness) +// NOLINTBEGIN(readability-magic-numbers) SFT_TEST_GROUP(FMT, COMPLEX_PATTERN); #define TEST_FMT(fmt_test, expected, ...) SFT_EQ(stream::fmt::format_string(fmt_test, __VA_ARGS__).value(), std::string(expected)) -SFT_TEST_FUNC(COMPLEX_PATTERN, UNESCAPED_ESCAPE_PATTERN) -{ +SFT_TEST_FUNC(COMPLEX_PATTERN, UNESCAPED_ESCAPE_PATTERN) { TEST_FMT("{0}", "9", 9); TEST_FMT("{{0}|", "{9|", 9); TEST_FMT("{{0},", "{9,", 9); } +// NOLINTEND(readability-magic-numbers) +// NOLINTEND(misc-const-correctness) diff --git a/tests/fmt/globber.cpp b/tests/fmt/globber.cpp index a0c6c25c..cc2d675b 100644 --- a/tests/fmt/globber.cpp +++ b/tests/fmt/globber.cpp @@ -4,69 +4,68 @@ #include "stream/fmt/buf/utils/buffer_globber_manip.h" +// NOLINTBEGIN(misc-const-correctness) +// NOLINTBEGIN(readability-magic-numbers) SFT_TEST_GROUP(FMT, GLOBBER); -#define TEST_GLOBBER(data, glob) \ - { \ - stream::fmt::buf::StreamView p_buffer(data); \ - stream::fmt::buf::StreamView p_glob(glob); \ - stream::fmt::buf::Globber::buffer_exec_glob(p_buffer, \ - p_glob).value(); \ - SFT_ASSERT( \ - stream::fmt::buf::Access(p_buffer).is_end_of_string()); \ - } +#define TEST_GLOBBER(data, glob) \ + { \ + stream::fmt::buf::StreamView p_buffer(data); \ + stream::fmt::buf::StreamView p_glob(glob); \ + stream::fmt::buf::Globber::buffer_exec_glob(p_buffer, p_glob).value(); \ + SFT_ASSERT(stream::fmt::buf::Access(p_buffer).is_end_of_string()); \ + } -SFT_TEST_FUNC(GLOBBER, BASIC_WILDCARD){ - TEST_GLOBBER("qwerty", "qwerty") TEST_GLOBBER("qwerty", "q?erty") - TEST_GLOBBER("qwerty", "q?????") TEST_GLOBBER("qwerty", "qwer?y") - TEST_GLOBBER("qwerty", "qwert?") TEST_GLOBBER("qwerty", "??????") - TEST_GLOBBER("qwerty", "*") TEST_GLOBBER("qwerty", "******") - TEST_GLOBBER("qwerty", "*?**?*")} +SFT_TEST_FUNC(GLOBBER, BASIC_WILDCARD){TEST_GLOBBER("qwerty", "qwerty") TEST_GLOBBER("qwerty", "q?erty") TEST_GLOBBER("qwerty", "q?????") TEST_GLOBBER("qwerty", "qwer?y") + TEST_GLOBBER("qwerty", "qwert?") TEST_GLOBBER("qwerty", "??????") TEST_GLOBBER("qwerty", "*") TEST_GLOBBER("qwerty", "******") + TEST_GLOBBER("qwerty", "*?**?*")} SFT_TEST_GROUP(FMT, PARSE_GLOBBER); SFT_TEST_FUNC(PARSE_GLOBBER, PG_BASIC_WILDCARD) { - int k = 0; - stream::fmt::parse("|123|", "|{}|", k).value(); - SFT_EQ(k, 123); + int k = 0; + stream::fmt::parse("|123|", "|{}|", k).value(); + SFT_EQ(k, 123); - { - // char test[5]; - // stream::fmt::parse("|test|", "|{}|", test).value(); - // SFT_EQ(std::string(test), std::string("test")); - } + { + // char test[5]; + // stream::fmt::parse("|test|", "|{}|", test).value(); + // SFT_EQ(std::string(test), std::string("test")); + } - { - // char test[4]; - // stream::fmt::parse("|test|", "|{:no-zero-end}|", test).value(); - // SFT_EQ(std::string(test, 4), std::string("test")); - } + { + // char test[4]; + // stream::fmt::parse("|test|", "|{:no-zero-end}|", test).value(); + // SFT_EQ(std::string(test, 4), std::string("test")); + } - { - // char test[4]; - // stream::fmt::parse("|test|", "|{}t|", test).value(); - // SFT_EQ(std::string(test), std::string("tes")); - } + { + // char test[4]; + // stream::fmt::parse("|test|", "|{}t|", test).value(); + // SFT_EQ(std::string(test), std::string("tes")); + } - { - // char test[11]; - // stream::fmt::parse("|test123456|", "|{}|", test).value(); - // SFT_EQ(std::string(test), std::string("test123456")); - } + { + // char test[11]; + // stream::fmt::parse("|test123456|", "|{}|", test).value(); + // SFT_EQ(std::string(test), std::string("test123456")); + } - { - // char test[11]; - // stream::fmt::parse("|test123456|", "|{:glob='*1'}23456|", test).value(); - // SFT_EQ(std::string(test), std::string("test1")); - } + { + // char test[11]; + // stream::fmt::parse("|test123456|", "|{:glob='*1'}23456|", test).value(); + // SFT_EQ(std::string(test), std::string("test1")); + } - { - // char test[11]; - // just glob = '????' but compiler are anrgy about trigraph on '??' - // stream::fmt::parse("|test123456|", - // "|{:glob='?" - // "?" - // "?" - // "?'}123456|", - // test).value(); - // SFT_EQ(std::string(test), std::string("test")); - } + { + // char test[11]; + // just glob = '????' but compiler are anrgy about trigraph on '??' + // stream::fmt::parse("|test123456|", + // "|{:glob='?" + // "?" + // "?" + // "?'}123456|", + // test).value(); + // SFT_EQ(std::string(test), std::string("test")); + } } +// NOLINTEND(readability-magic-numbers) +// NOLINTEND(misc-const-correctness) diff --git a/tests/fmt/index.cpp b/tests/fmt/index.cpp index de2ce128..612e657b 100644 --- a/tests/fmt/index.cpp +++ b/tests/fmt/index.cpp @@ -3,6 +3,8 @@ #include "base_fmt_tests.h" +// NOLINTBEGIN(misc-const-correctness) +// NOLINTBEGIN(readability-magic-numbers) /* SFT_TEST_GROUP(FMT, INDEX); @@ -10,3 +12,5 @@ SFT_TEST_FUNC(INDEX, ReIndexing) { } */ +// NOLINTEND(readability-magic-numbers) +// NOLINTEND(misc-const-correctness) diff --git a/tests/fmt/limits.cpp b/tests/fmt/limits.cpp index c004e5bd..cbe7f07b 100644 --- a/tests/fmt/limits.cpp +++ b/tests/fmt/limits.cpp @@ -3,16 +3,18 @@ #include "base_fmt_tests.h" +// NOLINTBEGIN(misc-const-correctness) +// NOLINTBEGIN(readability-magic-numbers) SFT_TEST_GROUP(FMT, LIMITS); -#define SFT_TEST_FUNC_LowBufferSize(k) \ - SFT_TEST_FUNC(LIMITS, LowBufferSize##k) { \ - char buffer[k] = {0}; \ - auto res = stream::fmt::format_in_char(buffer, "0123456789"); \ - SFT_EXPECTED_VALUE(res); \ - for (int i = 0; i < k; ++i) \ - SFT_EQ(buffer[i] - '0', i); \ - } +#define SFT_TEST_FUNC_LowBufferSize(k) \ + SFT_TEST_FUNC(LIMITS, LowBufferSize##k) { \ + char buffer[k] = {0}; \ + auto res = stream::fmt::format_in_char(buffer, "0123456789"); \ + SFT_EXPECTED_VALUE(res); \ + for (int i = 0; i < k; ++i) \ + SFT_EQ(buffer[i] - '0', i); \ + } SFT_TEST_FUNC_LowBufferSize(10); SFT_TEST_FUNC_LowBufferSize(9); @@ -26,33 +28,32 @@ SFT_TEST_FUNC_LowBufferSize(2); SFT_TEST_FUNC_LowBufferSize(1); SFT_TEST_FUNC(LIMITS, PlainLowBufferSize10) { - char buffer[10] = {0}; - auto res = stream::fmt::format_in_char(buffer, "0123456789"); - SFT_EXPECTED_VALUE(res); - for (int i = 0; i < 10; ++i) - SFT_EQ(buffer[i] - '0', i); + char buffer[10] = {0}; + auto res = stream::fmt::format_in_char(buffer, "0123456789"); + SFT_EXPECTED_VALUE(res); + for (int i = 0; i < 10; ++i) + SFT_EQ(buffer[i] - '0', i); } SFT_TEST_FUNC(LIMITS, PlainLowBufferSize1) { - char buffer[1] = {0}; - auto res = stream::fmt::format_in_char(buffer, "0"); - SFT_EXPECTED_VALUE(res); - for (int i = 0; i < 1; ++i) - SFT_EQ(buffer[i] - '0', i); + char buffer[1] = {0}; + auto res = stream::fmt::format_in_char(buffer, "0"); + SFT_EXPECTED_VALUE(res); + for (int i = 0; i < 1; ++i) + SFT_EQ(buffer[i] - '0', i); } -#define SFT_TEST_FUNC_LowBufferSizeArray(k) \ - SFT_TEST_FUNC(LIMITS, LowBufferSizeArray##k) { \ - char buffer[k] = {0}; \ - const char fmtBuffer[] = { \ - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; \ - stream::fmt::buf::StreamView format(fmtBuffer, k); \ - stream::fmt::buf::GivenStreamIOManager manager(buffer, k); \ - auto res = stream::fmt::detail::format_in_manager(manager, false, format); \ - SFT_EXPECTED_VALUE(res); \ - for (int i = 0; i < k; ++i) \ - SFT_EQ(buffer[i] - '0', i); \ - } +#define SFT_TEST_FUNC_LowBufferSizeArray(k) \ + SFT_TEST_FUNC(LIMITS, LowBufferSizeArray##k) { \ + char buffer[k] = {0}; \ + const char fmt_buffer[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; \ + stream::fmt::buf::StreamView format(fmt_buffer, k); \ + stream::fmt::buf::GivenStreamIOManager manager(buffer, k); \ + auto res = stream::fmt::detail::format_in_manager(manager, false, format); \ + SFT_EXPECTED_VALUE(res); \ + for (int i = 0; i < k; ++i) \ + SFT_EQ(buffer[i] - '0', i); \ + } SFT_TEST_FUNC_LowBufferSizeArray(10); SFT_TEST_FUNC_LowBufferSizeArray(9); @@ -66,47 +67,48 @@ SFT_TEST_FUNC_LowBufferSizeArray(2); SFT_TEST_FUNC_LowBufferSizeArray(1); SFT_TEST_FUNC(LIMITS, PlainLowBufferSizeArray10) { - char buffer[10] = {0}; - const char fmtBuffer[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; - stream::fmt::buf::StreamView fmt(fmtBuffer, 10); - stream::fmt::buf::GivenStreamIOManager manager(buffer, 10); - auto res = stream::fmt::detail::format_in_manager(manager, false, fmt); - SFT_EXPECTED_VALUE(res); - for (int i = 0; i < 10; ++i) - SFT_EQ(buffer[i] - '0', i); + char buffer[10] = {0}; + const char fmt_buffer[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; + stream::fmt::buf::StreamView const fmt(fmt_buffer, 10); + stream::fmt::buf::GivenStreamIOManager manager(buffer, 10); + auto res = stream::fmt::detail::format_in_manager(manager, false, fmt); + SFT_EXPECTED_VALUE(res); + for (int i = 0; i < 10; ++i) + SFT_EQ(buffer[i] - '0', i); } SFT_TEST_FUNC(LIMITS, PlainLowBufferSizeArray1) { - char buffer[1] = {0}; - const char fmtBuffer[] = {'0'}; - stream::fmt::buf::StreamView fmt(fmtBuffer, 1); - stream::fmt::buf::GivenStreamIOManager manager(buffer, 1); - auto res = stream::fmt::detail::format_in_manager(manager, false, fmt); - SFT_EXPECTED_VALUE(res); - for (int i = 0; i < 1; ++i) - SFT_EQ(buffer[i] - '0', i); + char buffer[1] = {0}; + const char fmt_buffer[] = {'0'}; + stream::fmt::buf::StreamView const fmt(fmt_buffer, 1); + stream::fmt::buf::GivenStreamIOManager manager(buffer, 1); + auto res = stream::fmt::detail::format_in_manager(manager, false, fmt); + SFT_EXPECTED_VALUE(res); + for (int i = 0; i < 1; ++i) + SFT_EQ(buffer[i] - '0', i); } SFT_TEST_FUNC(LIMITS, LowBufferSizeArray10FMT30) { - char buffer[10] = {0}; - const char fmtBuffer[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; - stream::fmt::buf::StreamView fmt(fmtBuffer, 30); - stream::fmt::buf::GivenStreamIOManager manager(buffer, 10); - auto res = stream::fmt::detail::format_in_manager(manager, false, fmt); - SFT_EXPECTED_VALUE(res); - for (int k = 0; k < 10; ++k) - SFT_EQ(buffer[k] - '0', k); + char buffer[10] = {0}; + const char fmt_buffer[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', + '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; + stream::fmt::buf::StreamView const fmt(fmt_buffer, 30); + stream::fmt::buf::GivenStreamIOManager manager(buffer, 10); + auto res = stream::fmt::detail::format_in_manager(manager, false, fmt); + SFT_EXPECTED_VALUE(res); + for (int k = 0; k < 10; ++k) + SFT_EQ(buffer[k] - '0', k); } SFT_TEST_FUNC(LIMITS, LowBufferSizeArray5Number9) { - char buffer[10] = {0}; - stream::fmt::buf::StreamView fmt("{}"); - stream::fmt::buf::GivenStreamIOManager manager(buffer, 10); - std::uint64_t i = 9'876'543'210; - auto res = stream::fmt::detail::format_in_manager(manager, false, fmt, i); - SFT_EXPECTED_VALUE(res); - for (int k = 0; k < 10; ++k) - SFT_EQ(buffer[k] - '0', 9 - k); + char buffer[10] = {0}; + stream::fmt::buf::StreamView const fmt("{}"); + stream::fmt::buf::GivenStreamIOManager manager(buffer, 10); + std::uint64_t i = 9'876'543'210; + auto res = stream::fmt::detail::format_in_manager(manager, false, fmt, i); + SFT_EXPECTED_VALUE(res); + for (int k = 0; k < 10; ++k) + SFT_EQ(buffer[k] - '0', 9 - k); } +// NOLINTEND(readability-magic-numbers) +// NOLINTEND(misc-const-correctness) diff --git a/tests/fmt/shift.cpp b/tests/fmt/shift.cpp index 74306891..c0237021 100644 --- a/tests/fmt/shift.cpp +++ b/tests/fmt/shift.cpp @@ -3,28 +3,27 @@ #include "base_fmt_tests.h" +// NOLINTBEGIN(misc-const-correctness) +// NOLINTBEGIN(readability-magic-numbers) SFT_TEST_GROUP(FMT, SHIFT); #define TEST_FMT(fmt_test, expected, ...) SFT_EQ(stream::fmt::format_string(fmt_test, __VA_ARGS__), expected) SFT_TEST_GROUP(SHIFT, NUMBER_SHIFT); SFT_TEST_GROUP(NUMBER_SHIFT, ONE_DIGIT); -SFT_TEST_FUNC(ONE_DIGIT, Right) -{ +SFT_TEST_FUNC(ONE_DIGIT, Right) { TEST_FMT("|{:>9 }|", "| 7|", 7); TEST_FMT("|{:>9: }|", "| 7|", 7); TEST_FMT("|{:>9:0}|", "|000000007|", 7); TEST_FMT("|{:>9:*}|", "|********7|", 7); } -SFT_TEST_FUNC(ONE_DIGIT, Left) -{ +SFT_TEST_FUNC(ONE_DIGIT, Left) { TEST_FMT("|{:<9 }|", "|7 |", 7); TEST_FMT("|{:<9: }|", "|7 |", 7); TEST_FMT("|{:<9:0}|", "|7 |", 7); TEST_FMT("|{:<9:*}|", "|7********|", 7); } -SFT_TEST_FUNC(ONE_DIGIT, Center) -{ +SFT_TEST_FUNC(ONE_DIGIT, Center) { TEST_FMT("|{:^10 }|", "| 7 |", 7); TEST_FMT("|{:^10:-|-}|", "|-----7----|", 7); TEST_FMT("|{:^10:*|*}|", "|*****7****|", 7); @@ -36,8 +35,7 @@ SFT_TEST_FUNC(ONE_DIGIT, Center) TEST_FMT("|{:^11:<|>}|", "|<<<<<7>>>>>|", 7); TEST_FMT("|{:^11:>|<}|", "|>>>>>7<<<<<|", 7); } -SFT_TEST_FUNC(ONE_DIGIT, CenterRight) -{ +SFT_TEST_FUNC(ONE_DIGIT, CenterRight) { TEST_FMT("|{:^>10:-|-}|", "|-----7----|", 7); TEST_FMT("|{:^>10:*|*}|", "|*****7****|", 7); TEST_FMT("|{:^>10:<|>}|", "|<<<<<7>>>>|", 7); @@ -48,8 +46,7 @@ SFT_TEST_FUNC(ONE_DIGIT, CenterRight) TEST_FMT("|{:^>11:<|>}|", "|<<<<<7>>>>>|", 7); TEST_FMT("|{:^>11:>|<}|", "|>>>>>7<<<<<|", 7); } -SFT_TEST_FUNC(ONE_DIGIT, CenterLeft) -{ +SFT_TEST_FUNC(ONE_DIGIT, CenterLeft) { TEST_FMT("|{:^<10:-|-}|", "|----7-----|", 7); TEST_FMT("|{:^<10:*|*}|", "|****7*****|", 7); TEST_FMT("|{:^<10:<|>}|", "|<<<<7>>>>>|", 7); @@ -62,22 +59,19 @@ SFT_TEST_FUNC(ONE_DIGIT, CenterLeft) } SFT_TEST_GROUP(NUMBER_SHIFT, TWO_DIGIT); -SFT_TEST_FUNC(TWO_DIGIT, Right) -{ +SFT_TEST_FUNC(TWO_DIGIT, Right) { TEST_FMT("|{:>10 }|", "| 14|", 14); TEST_FMT("|{:>10: }|", "| 14|", 14); TEST_FMT("|{:>10:0}|", "|0000000014|", 14); TEST_FMT("|{:>10:*}|", "|********14|", 14); } -SFT_TEST_FUNC(TWO_DIGIT, Left) -{ +SFT_TEST_FUNC(TWO_DIGIT, Left) { TEST_FMT("|{:<10 }|", "|14 |", 14); TEST_FMT("|{:<10: }|", "|14 |", 14); TEST_FMT("|{:<10:0}|", "|14 |", 14); TEST_FMT("|{:<10:*}|", "|14********|", 14); } -SFT_TEST_FUNC(TWO_DIGIT, Center) -{ +SFT_TEST_FUNC(TWO_DIGIT, Center) { TEST_FMT("|{:^10 }|", "| 14 |", 14); TEST_FMT("|{:^10:-|-}|", "|----14----|", 14); TEST_FMT("|{:^10:*|*}|", "|****14****|", 14); @@ -89,8 +83,7 @@ SFT_TEST_FUNC(TWO_DIGIT, Center) TEST_FMT("|{:^11:<|>}|", "|<<<<<14>>>>|", 14); TEST_FMT("|{:^11:>|<}|", "|>>>>>14<<<<|", 14); } -SFT_TEST_FUNC(TWO_DIGIT, CenterRight) -{ +SFT_TEST_FUNC(TWO_DIGIT, CenterRight) { TEST_FMT("|{:^>10:-|-}|", "|----14----|", 14); TEST_FMT("|{:^>10:*|*}|", "|****14****|", 14); TEST_FMT("|{:^>10:<|>}|", "|<<<<14>>>>|", 14); @@ -101,8 +94,7 @@ SFT_TEST_FUNC(TWO_DIGIT, CenterRight) TEST_FMT("|{:^>11:<|>}|", "|<<<<<14>>>>|", 14); TEST_FMT("|{:^>11:>|<}|", "|>>>>>14<<<<|", 14); } -SFT_TEST_FUNC(TWO_DIGIT, CenterLeft) -{ +SFT_TEST_FUNC(TWO_DIGIT, CenterLeft) { TEST_FMT("|{:^<10:-|-}|", "|----14----|", 14); TEST_FMT("|{:^<10:*|*}|", "|****14****|", 14); TEST_FMT("|{:^<10:<|>}|", "|<<<<14>>>>|", 14); @@ -115,22 +107,19 @@ SFT_TEST_FUNC(TWO_DIGIT, CenterLeft) } SFT_TEST_GROUP(NUMBER_SHIFT, THREE_DIGIT); -SFT_TEST_FUNC(THREE_DIGIT, Right) -{ +SFT_TEST_FUNC(THREE_DIGIT, Right) { TEST_FMT("|{:>11 }|", "| 105|", 105); TEST_FMT("|{:>11: }|", "| 105|", 105); TEST_FMT("|{:>11:0}|", "|00000000105|", 105); TEST_FMT("|{:>11:*}|", "|********105|", 105); } -SFT_TEST_FUNC(THREE_DIGIT, Left) -{ +SFT_TEST_FUNC(THREE_DIGIT, Left) { TEST_FMT("|{:<11 }|", "|105 |", 105); TEST_FMT("|{:<11: }|", "|105 |", 105); TEST_FMT("|{:<11:0}|", "|105 |", 105); TEST_FMT("|{:<11:*}|", "|105********|", 105); } -SFT_TEST_FUNC(THREE_DIGIT, Center) -{ +SFT_TEST_FUNC(THREE_DIGIT, Center) { TEST_FMT("|{:^10 }|", "| 105 |", 105); TEST_FMT("|{:^10:-|-}|", "|----105---|", 105); TEST_FMT("|{:^10:*|*}|", "|****105***|", 105); @@ -142,8 +131,7 @@ SFT_TEST_FUNC(THREE_DIGIT, Center) TEST_FMT("|{:^11:<|>}|", "|<<<<105>>>>|", 105); TEST_FMT("|{:^11:>|<}|", "|>>>>105<<<<|", 105); } -SFT_TEST_FUNC(THREE_DIGIT, CenterRight) -{ +SFT_TEST_FUNC(THREE_DIGIT, CenterRight) { TEST_FMT("|{:^>10:-|-}|", "|----105---|", 105); TEST_FMT("|{:^>10:*|*}|", "|****105***|", 105); TEST_FMT("|{:^>10:<|>}|", "|<<<<105>>>|", 105); @@ -154,8 +142,7 @@ SFT_TEST_FUNC(THREE_DIGIT, CenterRight) TEST_FMT("|{:^>11:<|>}|", "|<<<<105>>>>|", 105); TEST_FMT("|{:^>11:>|<}|", "|>>>>105<<<<|", 105); } -SFT_TEST_FUNC(THREE_DIGIT, CenterLeft) -{ +SFT_TEST_FUNC(THREE_DIGIT, CenterLeft) { TEST_FMT("|{:^<10:-|-}|", "|---105----|", 105); TEST_FMT("|{:^<10:*|*}|", "|***105****|", 105); TEST_FMT("|{:^<10:<|>}|", "|<<<105>>>>|", 105); @@ -169,22 +156,19 @@ SFT_TEST_FUNC(THREE_DIGIT, CenterLeft) SFT_TEST_GROUP(SHIFT, STRING_SHIFT); SFT_TEST_GROUP(STRING_SHIFT, ARRAY); -SFT_TEST_FUNC(ARRAY, Right) -{ +SFT_TEST_FUNC(ARRAY, Right) { TEST_FMT("|{:>10 }|", "| test|", "test"); TEST_FMT("|{:>10: }|", "| test|", "test"); TEST_FMT("|{:>10:0}|", "|000000test|", "test"); TEST_FMT("|{:>10:*}|", "|******test|", "test"); } -SFT_TEST_FUNC(ARRAY, Left) -{ +SFT_TEST_FUNC(ARRAY, Left) { TEST_FMT("|{:<10 }|", "|test |", "test"); TEST_FMT("|{:<10: }|", "|test |", "test"); TEST_FMT("|{:<10:0}|", "|test000000|", "test"); TEST_FMT("|{:<10:*}|", "|test******|", "test"); } -SFT_TEST_FUNC(ARRAY, Center) -{ +SFT_TEST_FUNC(ARRAY, Center) { TEST_FMT("|{:^10 }|", "| test |", "test"); TEST_FMT("|{:^10:-|-}|", "|---test---|", "test"); TEST_FMT("|{:^10:*|*}|", "|***test***|", "test"); @@ -196,8 +180,7 @@ SFT_TEST_FUNC(ARRAY, Center) TEST_FMT("|{:^11:<|>}|", "|<<<>>|", "test"); TEST_FMT("|{:^11:>|<}|", "|>>>>test<<<|", "test"); } -SFT_TEST_FUNC(ARRAY, CenterRight) -{ +SFT_TEST_FUNC(ARRAY, CenterRight) { TEST_FMT("|{:^>10:-|-}|", "|---test---|", "test"); TEST_FMT("|{:^>10:*|*}|", "|***test***|", "test"); TEST_FMT("|{:^>10:<|>}|", "|<<>>|", "test"); @@ -208,8 +191,7 @@ SFT_TEST_FUNC(ARRAY, CenterRight) TEST_FMT("|{:^>11:<|>}|", "|<<<>>|", "test"); TEST_FMT("|{:^>11:>|<}|", "|>>>>test<<<|", "test"); } -SFT_TEST_FUNC(ARRAY, CenterLeft) -{ +SFT_TEST_FUNC(ARRAY, CenterLeft) { TEST_FMT("|{:^<10:-|-}|", "|---test---|", "test"); TEST_FMT("|{:^<10:*|*}|", "|***test***|", "test"); TEST_FMT("|{:^<10:<|>}|", "|<<>>|", "test"); @@ -222,8 +204,7 @@ SFT_TEST_FUNC(ARRAY, CenterLeft) } SFT_TEST_GROUP(STRING_SHIFT, POINTER); -SFT_TEST_FUNC(POINTER, Right) -{ +SFT_TEST_FUNC(POINTER, Right) { const char* test = "test"; TEST_FMT("|{:>10 }|", "| test|", test); TEST_FMT("|{:>10: }|", "| test|", test); @@ -236,8 +217,7 @@ SFT_TEST_FUNC(POINTER, Right) TEST_FMT("|{:>10:0, size=4}|", "|000000test|", test_with_size); TEST_FMT("|{:>10:*, size=4}|", "|******test|", test_with_size); } -SFT_TEST_FUNC(POINTER, Left) -{ +SFT_TEST_FUNC(POINTER, Left) { const char* test = "test"; TEST_FMT("|{:<10 }|", "|test |", test); TEST_FMT("|{:<10: }|", "|test |", test); @@ -250,8 +230,7 @@ SFT_TEST_FUNC(POINTER, Left) TEST_FMT("|{:<10:0, size=4}|", "|test000000|", test_with_size); TEST_FMT("|{:<10:*, size=4}|", "|test******|", test_with_size); } -SFT_TEST_FUNC(POINTER, Center) -{ +SFT_TEST_FUNC(POINTER, Center) { const char* test = "test"; TEST_FMT("|{:^10 }|", "| test |", test); TEST_FMT("|{:^10:-|-}|", "|---test---|", test); @@ -276,8 +255,7 @@ SFT_TEST_FUNC(POINTER, Center) TEST_FMT("|{:^11:<|>, size=4}|", "|<<<>>|", test_with_size); TEST_FMT("|{:^11:>|<, size=4}|", "|>>>>test<<<|", test_with_size); } -SFT_TEST_FUNC(POINTER, CenterRight) -{ +SFT_TEST_FUNC(POINTER, CenterRight) { const char* test = "test"; TEST_FMT("|{:^>10:-|-}|", "|---test---|", test); TEST_FMT("|{:^>10:*|*}|", "|***test***|", test); @@ -300,8 +278,7 @@ SFT_TEST_FUNC(POINTER, CenterRight) TEST_FMT("|{:^>11:<|>, size=4}|", "|<<<>>|", test_with_size); TEST_FMT("|{:^>11:>|<, size=4}|", "|>>>>test<<<|", test_with_size); } -SFT_TEST_FUNC(POINTER, CenterLeft) -{ +SFT_TEST_FUNC(POINTER, CenterLeft) { const char* test = "test"; TEST_FMT("|{:^<10:-|-}|", "|---test---|", test); TEST_FMT("|{:^<10:*|*}|", "|***test***|", test); @@ -324,3 +301,5 @@ SFT_TEST_FUNC(POINTER, CenterLeft) TEST_FMT("|{:^<11:<|>, size=4}|", "|<<>>>|", test_with_size); TEST_FMT("|{:^<11:>|<, size=4}|", "|>>>test<<<<|", test_with_size); } +// NOLINTEND(readability-magic-numbers) +// NOLINTEND(misc-const-correctness) diff --git a/tests/fmt/specifier.cpp b/tests/fmt/specifier.cpp index 5907eeed..ce3083f1 100644 --- a/tests/fmt/specifier.cpp +++ b/tests/fmt/specifier.cpp @@ -3,12 +3,13 @@ #include "base_fmt_tests.h" +// NOLINTBEGIN(misc-const-correctness) +// NOLINTBEGIN(readability-magic-numbers) SFT_TEST_GROUP(FMT, SPECIFIER); #define TEST_FMT_ARRAY_SPECIFIERS(fmt_test, test_data, expected) SFT_EQ(stream::fmt::format_string(fmt_test, test_data), expected) -SFT_TEST_FUNC(SPECIFIER, BEGIN_END) -{ +SFT_TEST_FUNC(SPECIFIER, BEGIN_END) { int data[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; TEST_FMT_ARRAY_SPECIFIERS("{}", data, "{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }"); @@ -26,3 +27,5 @@ SFT_TEST_FUNC(SPECIFIER, BEGIN_END) TEST_FMT_ARRAY_SPECIFIERS("{:join=' | ', begin='[', end=']', begin=3, size=5}", data, "[3 | 4 | 5 | 6 | 7]"); } +// NOLINTEND(readability-magic-numbers) +// NOLINTEND(misc-const-correctness) diff --git a/tests/fmt/text_properties.cpp b/tests/fmt/text_properties.cpp index 4939ed86..cd22f769 100644 --- a/tests/fmt/text_properties.cpp +++ b/tests/fmt/text_properties.cpp @@ -3,17 +3,16 @@ #include "base_fmt_tests.h" +// NOLINTBEGIN(misc-const-correctness) +// NOLINTBEGIN(readability-magic-numbers) SFT_TEST_GROUP(FMT, TEXT_PROPERTIES); -#define TEST_FMT(fmt_test, expected) SFT_EQ(Escaper(stream::fmt::format_string(fmt_test, 0).value()), Escaper(expected)) +#define TEST_FMT(fmt_test, expected) SFT_EQ(escaper(stream::fmt::format_string(fmt_test, 0).value()), escaper(expected)) -static std::string Escaper(const std::string& str) -{ +static std::string escaper(const std::string& str) { std::string res; - for (char c : str) - { - if (c != '\033') - { + for (char const c : str) { + if (c != '\033') { res.push_back(c); continue; } @@ -25,15 +24,13 @@ static std::string Escaper(const std::string& str) } SFT_TEST_GROUP(TEXT_PROPERTIES, ESCAPER_VALIDATING); -#define TEST_ESCAPER(str, str_res) SFT_EQ(Escaper(str), str_res) -SFT_TEST_FUNC(ESCAPER_VALIDATING, BasicTest) -{ +#define TEST_ESCAPER(str, str_res) SFT_EQ(escaper(str), str_res) +SFT_TEST_FUNC(ESCAPER_VALIDATING, BasicTest) { TEST_ESCAPER("\033", "\\e"); TEST_ESCAPER("\033k", "\\ek"); } -SFT_TEST_FUNC(TEXT_PROPERTIES, basic_color) -{ +SFT_TEST_FUNC(TEXT_PROPERTIES, basic_color) { TEST_FMT("123", "123"); TEST_FMT("{C:black} 123 ", "\033[30m 123 \033[39m"); @@ -55,8 +52,7 @@ SFT_TEST_FUNC(TEXT_PROPERTIES, basic_color) TEST_FMT("{C:+white} 123 ", "\033[97m 123 \033[39m"); } -SFT_TEST_FUNC(TEXT_PROPERTIES, DoubleBasicColor) -{ +SFT_TEST_FUNC(TEXT_PROPERTIES, DoubleBasicColor) { TEST_FMT("123", "123"); TEST_FMT("{C:black} 1 {C:white} 23 ", "\033[30m 1 \033[37m 23 \033[39m"); @@ -78,15 +74,12 @@ SFT_TEST_FUNC(TEXT_PROPERTIES, DoubleBasicColor) TEST_FMT("{C:+white} 1 {C:+cyan} 23 ", "\033[97m 1 \033[96m 23 \033[39m"); } -class TEST_FMT_ContextOut -{ -}; -STREAMFORMAT_AUTO_FORMATTER_T(TEST_FMT_ContextOut, "{C:red} TEST_FMT_ContextOut {} ", 0); +class TestFmtContextOut {}; +STREAMFORMAT_AUTO_FORMATTER_T(TestFmtContextOut, "{C:red} TEST_FMT_ContextOut {} ", 0); -#define TEST_FMT_CONTEXT(fmt_test, expected) SFT_EQ(Escaper(stream::fmt::format_string(fmt_test, TEST_FMT_ContextOut{}).value()), Escaper(expected)) +#define TEST_FMT_CONTEXT(fmt_test, expected) SFT_EQ(escaper(stream::fmt::format_string(fmt_test, TestFmtContextOut{}).value()), escaper(expected)) -SFT_TEST_FUNC(TEXT_PROPERTIES, ContextOut) -{ +SFT_TEST_FUNC(TEXT_PROPERTIES, ContextOut) { TEST_FMT_CONTEXT("{}", "\033[31m TEST_FMT_ContextOut 0 \033[39m"); TEST_FMT_CONTEXT("{} 123 ", "\033[31m TEST_FMT_ContextOut 0 \033[39m 123 "); @@ -96,3 +89,5 @@ SFT_TEST_FUNC(TEXT_PROPERTIES, ContextOut) TEST_FMT_CONTEXT("{C:+red}{} 123 ", "\033[91m\033[31m TEST_FMT_ContextOut 0 \033[91m 123 \033[39m"); } +// NOLINTEND(readability-magic-numbers) +// NOLINTEND(misc-const-correctness) diff --git a/tests/tests.cpp b/tests/tests.cpp index 71fc519e..f146fcc5 100644 --- a/tests/tests.cpp +++ b/tests/tests.cpp @@ -2,8 +2,7 @@ #include "stream/tester/test_suite/all_test_suite.h" #include "stream/default_logger.h" -int main() -{ +int main() { stream::tester::TestSuitesManager::verbose = false; - return stream::tester::TestSuitesManager::exec_all_test_suites(); + return static_cast(stream::tester::TestSuitesManager::exec_all_test_suites()); } From 2bfd8c3cd53734cbb457a2e3d65a7a37c8ea7188 Mon Sep 17 00:00:00 2001 From: BELLIER Sacha Date: Sun, 23 Mar 2025 18:57:14 +0100 Subject: [PATCH 22/42] wip: from cpp to cxx --- examples/hello/{main.cpp => main.cxx} | 0 src/stream/core/{prelude.h => prelude.hxx} | 0 src/stream/{default_logger.h => default_logger.hxx} | 0 src/stream/{flog.h => flog.hxx} | 0 src/stream/flog/backends/{basic_logger.h => basic_logger.hxx} | 0 .../flog/backends/{logger_multi_sink.h => logger_multi_sink.hxx} | 0 .../{logger_multi_sink_fast.h => logger_multi_sink_fast.hxx} | 0 .../{logger_multi_sink_safe.h => logger_multi_sink_safe.hxx} | 0 src/stream/flog/detail/{detail.h => detail.hxx} | 0 src/stream/flog/frontends/{xlogger.cpp => xlogger.cxx} | 0 src/stream/flog/frontends/{xlogger.h => xlogger.hxx} | 0 src/stream/flog/{logger_factory.h => logger_factory.hxx} | 0 src/stream/flog/sinks/{file_sink.h => file_sink.hxx} | 0 src/stream/flog/sinks/{logger_sink.h => logger_sink.hxx} | 0 src/stream/{fmt.h => fmt.hxx} | 0 src/stream/fmt/buf/{fmt_manip_io.h => fmt_manip_io.hxx} | 0 src/stream/fmt/buf/{fmt_read_manip.h => fmt_read_manip.hxx} | 0 src/stream/fmt/buf/{fmt_write_manip.h => fmt_write_manip.hxx} | 0 src/stream/fmt/buf/{manip.h => manip.hxx} | 0 src/stream/fmt/buf/{manip_io.h => manip_io.hxx} | 0 src/stream/fmt/buf/{read_manip.h => read_manip.hxx} | 0 src/stream/fmt/buf/{stream.h => stream.hxx} | 0 src/stream/fmt/buf/{streamio.h => streamio.hxx} | 0 .../{basic_streamio_manager.h => basic_streamio_manager.hxx} | 0 .../{dynamic_streamio_manager.h => dynamic_streamio_manager.hxx} | 0 .../{given_streamio_manager.h => given_streamio_manager.hxx} | 0 .../{static_streamio_manager.h => static_streamio_manager.hxx} | 0 src/stream/fmt/buf/{test_manip.h => test_manip.hxx} | 0 .../utils/{buffer_globber_manip.h => buffer_globber_manip.hxx} | 0 .../buf/utils/{buffer_shift_manip.h => buffer_shift_manip.hxx} | 0 src/stream/fmt/buf/utils/{buffer_utils.h => buffer_utils.hxx} | 0 src/stream/fmt/buf/{write_manip.h => write_manip.hxx} | 0 .../{basic_args_interface.h => basic_args_interface.hxx} | 0 .../context/basic_context/{basic_context.h => basic_context.hxx} | 0 .../{basic_context_parse_impl.h => basic_context_parse_impl.hxx} | 0 .../{text_properties_executor.h => text_properties_executor.hxx} | 0 .../{text_properties_manager.cpp => text_properties_manager.cxx} | 0 .../{text_properties_manager.h => text_properties_manager.hxx} | 0 ...properties_manager_impl.h => text_properties_manager_impl.hxx} | 0 .../{basic_formatter_executor.h => basic_formatter_executor.hxx} | 0 .../{format_basics_impl.h => format_basics_impl.hxx} | 0 ...mat_text_properties_impl.h => format_text_properties_impl.hxx} | 0 .../formatter_executor/{formatter_args.h => formatter_args.hxx} | 0 ...operties_executor.h => formatter_text_properties_executor.hxx} | 0 ...xecutor_ansi.h => formatter_text_properties_executor_ansi.hxx} | 0 .../formatter_executor/{formatter_type.h => formatter_type.hxx} | 0 .../context/formatter_executor/{index_args.h => index_args.hxx} | 0 .../context/formatter_executor/{named_args.h => named_args.hxx} | 0 .../formatter_executor/{std_enumerable.h => std_enumerable.hxx} | 0 .../{utility_functions.h => utility_functions.hxx} | 0 .../{basic_parser_executor.h => basic_parser_executor.hxx} | 0 .../{parse_basics_impl.h => parse_basics_impl.hxx} | 0 ...arse_text_properties_impl.h => parse_text_properties_impl.hxx} | 0 .../context/parser_executor/{parser_args.h => parser_args.hxx} | 0 ..._properties_executor.h => parser_text_properties_executor.hxx} | 0 ...s_executor_ansi.h => parser_text_properties_executor_ansi.hxx} | 0 .../context/parser_executor/{parser_type.h => parser_type.hxx} | 0 .../{utility_functions.h => utility_functions.hxx} | 0 .../context/utils/{context_functions.h => context_functions.hxx} | 0 src/stream/fmt/detail/{convert_traits.h => convert_traits.hxx} | 0 src/stream/fmt/detail/{fmt_result.h => fmt_result.hxx} | 0 src/stream/fmt/detail/{indent_handlers.h => indent_handlers.hxx} | 0 src/stream/fmt/detail/{prelude.h => prelude.hxx} | 0 src/stream/fmt/detail/{specifiers.h => specifiers.hxx} | 0 src/stream/fmt/detail/{types_traits.h => types_traits.hxx} | 0 .../fmt/serializers/{compilation_data.h => compilation_data.hxx} | 0 src/stream/fmt/serializers/{format_chrono.h => format_chrono.hxx} | 0 src/stream/fmt/serializers/{format_stdlib.h => format_stdlib.hxx} | 0 src/stream/fmt/serializers/{parse_chrono.h => parse_chrono.hxx} | 0 src/stream/fmt/serializers/{parse_stdlib.h => parse_stdlib.hxx} | 0 src/stream/fmt/serializers/std_container/{array.h => array.hxx} | 0 src/stream/fmt/serializers/std_container/{deque.h => deque.hxx} | 0 .../std_container/{forward_list.h => forward_list.hxx} | 0 src/stream/fmt/serializers/std_container/{list.h => list.hxx} | 0 src/stream/fmt/serializers/std_container/{map.h => map.hxx} | 0 src/stream/fmt/serializers/std_container/{queue.h => queue.hxx} | 0 src/stream/fmt/serializers/std_container/{set.h => set.hxx} | 0 src/stream/fmt/serializers/std_container/{stack.h => stack.hxx} | 0 src/stream/fmt/serializers/std_container/{tuple.h => tuple.hxx} | 0 .../std_container/{unordered_map.h => unordered_map.hxx} | 0 .../std_container/{unordered_set.h => unordered_set.hxx} | 0 src/stream/fmt/serializers/std_container/{vector.h => vector.hxx} | 0 .../{base_text_properties.h => base_text_properties.hxx} | 0 .../text_properties/{text_properties.h => text_properties.hxx} | 0 .../{text_properties_color.h => text_properties_color.hxx} | 0 .../{text_properties_front.h => text_properties_front.hxx} | 0 .../{text_properties_style.h => text_properties_style.hxx} | 0 src/stream/{json.h => json.hxx} | 0 src/stream/json/{detail.h => detail.hxx} | 0 src/stream/json/{json_factory.h => json_factory.hxx} | 0 src/stream/json/{json_formatter.h => json_formatter.hxx} | 0 .../json/{json_formatter_impl.h => json_formatter_impl.hxx} | 0 src/stream/json/{json_objects.cpp => json_objects.cxx} | 0 src/stream/json/{json_objects.h => json_objects.hxx} | 0 src/stream/json/{json_parser.cpp => json_parser.cxx} | 0 src/stream/json/{json_parser.h => json_parser.hxx} | 0 src/stream/json/{json_serializer.h => json_serializer.hxx} | 0 .../json/serializers/{base_serializers.h => base_serializers.hxx} | 0 .../{json_objects_serializer.h => json_objects_serializer.hxx} | 0 src/stream/json/serializers/{serializers.h => serializers.hxx} | 0 .../{basic_std_serializers.h => basic_std_serializers.hxx} | 0 .../json/serializers/std_serializers/{json_map.h => json_map.hxx} | 0 .../{json_unordered_map.h => json_unordered_map.hxx} | 0 .../std_serializers/{json_vector.h => json_vector.hxx} | 0 src/stream/{profiler.h => profiler.hxx} | 0 src/stream/profiler/{all_events.h => all_events.hxx} | 0 src/stream/profiler/{detail.h => detail.hxx} | 0 src/stream/profiler/{event.h => event.hxx} | 0 src/stream/profiler/{event_data.h => event_data.hxx} | 0 src/stream/profiler/{get_pid.cpp => get_pid.cxx} | 0 src/stream/profiler/{profiler.h => profiler.hxx} | 0 .../{profiler_event_creator.cpp => profiler_event_creator.cxx} | 0 .../{profiler_event_creator.h => profiler_event_creator.hxx} | 0 .../profiler/{profiler_factory.cpp => profiler_factory.cxx} | 0 src/stream/profiler/{profiler_factory.h => profiler_factory.hxx} | 0 ...{profiler_json_serializers.h => profiler_json_serializers.hxx} | 0 src/stream/profiler/{profiler_macros.h => profiler_macros.hxx} | 0 src/stream/tester/{copy_move_check.h => copy_move_check.hxx} | 0 .../tester/test_suite/{all_test_suite.h => all_test_suite.hxx} | 0 src/stream/tester/test_suite/{basic_test.h => basic_test.hxx} | 0 src/stream/tester/test_suite/{test_suite.cpp => test_suite.cxx} | 0 src/stream/tester/test_suite/{test_suite.h => test_suite.hxx} | 0 src/stream/tester/{tests_macros.h => tests_macros.hxx} | 0 tests/fmt/{shift.cpp => .hxxift.cxx} | 0 tests/fmt/{base_fmt_tests.h => base_fmt_tests.hxx} | 0 tests/fmt/{complex_pattern.cpp => complex_pattern.cxx} | 0 tests/fmt/{globber.cpp => globber.cxx} | 0 tests/fmt/{index.cpp => index.cxx} | 0 tests/fmt/{limits.cpp => limits.cxx} | 0 tests/fmt/{specifier.cpp => specifier.cxx} | 0 tests/fmt/{text_properties.cpp => text_properties.cxx} | 0 tests/{tests.cpp => tests.cxx} | 0 132 files changed, 0 insertions(+), 0 deletions(-) rename examples/hello/{main.cpp => main.cxx} (100%) rename src/stream/core/{prelude.h => prelude.hxx} (100%) rename src/stream/{default_logger.h => default_logger.hxx} (100%) rename src/stream/{flog.h => flog.hxx} (100%) rename src/stream/flog/backends/{basic_logger.h => basic_logger.hxx} (100%) rename src/stream/flog/backends/{logger_multi_sink.h => logger_multi_sink.hxx} (100%) rename src/stream/flog/backends/{logger_multi_sink_fast.h => logger_multi_sink_fast.hxx} (100%) rename src/stream/flog/backends/{logger_multi_sink_safe.h => logger_multi_sink_safe.hxx} (100%) rename src/stream/flog/detail/{detail.h => detail.hxx} (100%) rename src/stream/flog/frontends/{xlogger.cpp => xlogger.cxx} (100%) rename src/stream/flog/frontends/{xlogger.h => xlogger.hxx} (100%) rename src/stream/flog/{logger_factory.h => logger_factory.hxx} (100%) rename src/stream/flog/sinks/{file_sink.h => file_sink.hxx} (100%) rename src/stream/flog/sinks/{logger_sink.h => logger_sink.hxx} (100%) rename src/stream/{fmt.h => fmt.hxx} (100%) rename src/stream/fmt/buf/{fmt_manip_io.h => fmt_manip_io.hxx} (100%) rename src/stream/fmt/buf/{fmt_read_manip.h => fmt_read_manip.hxx} (100%) rename src/stream/fmt/buf/{fmt_write_manip.h => fmt_write_manip.hxx} (100%) rename src/stream/fmt/buf/{manip.h => manip.hxx} (100%) rename src/stream/fmt/buf/{manip_io.h => manip_io.hxx} (100%) rename src/stream/fmt/buf/{read_manip.h => read_manip.hxx} (100%) rename src/stream/fmt/buf/{stream.h => stream.hxx} (100%) rename src/stream/fmt/buf/{streamio.h => streamio.hxx} (100%) rename src/stream/fmt/buf/streamio_manager/{basic_streamio_manager.h => basic_streamio_manager.hxx} (100%) rename src/stream/fmt/buf/streamio_manager/{dynamic_streamio_manager.h => dynamic_streamio_manager.hxx} (100%) rename src/stream/fmt/buf/streamio_manager/{given_streamio_manager.h => given_streamio_manager.hxx} (100%) rename src/stream/fmt/buf/streamio_manager/{static_streamio_manager.h => static_streamio_manager.hxx} (100%) rename src/stream/fmt/buf/{test_manip.h => test_manip.hxx} (100%) rename src/stream/fmt/buf/utils/{buffer_globber_manip.h => buffer_globber_manip.hxx} (100%) rename src/stream/fmt/buf/utils/{buffer_shift_manip.h => buffer_shift_manip.hxx} (100%) rename src/stream/fmt/buf/utils/{buffer_utils.h => buffer_utils.hxx} (100%) rename src/stream/fmt/buf/{write_manip.h => write_manip.hxx} (100%) rename src/stream/fmt/context/basic_context/{basic_args_interface.h => basic_args_interface.hxx} (100%) rename src/stream/fmt/context/basic_context/{basic_context.h => basic_context.hxx} (100%) rename src/stream/fmt/context/basic_context/{basic_context_parse_impl.h => basic_context_parse_impl.hxx} (100%) rename src/stream/fmt/context/basic_context/{text_properties_executor.h => text_properties_executor.hxx} (100%) rename src/stream/fmt/context/basic_context/{text_properties_manager.cpp => text_properties_manager.cxx} (100%) rename src/stream/fmt/context/basic_context/{text_properties_manager.h => text_properties_manager.hxx} (100%) rename src/stream/fmt/context/basic_context/{text_properties_manager_impl.h => text_properties_manager_impl.hxx} (100%) rename src/stream/fmt/context/formatter_executor/{basic_formatter_executor.h => basic_formatter_executor.hxx} (100%) rename src/stream/fmt/context/formatter_executor/{format_basics_impl.h => format_basics_impl.hxx} (100%) rename src/stream/fmt/context/formatter_executor/{format_text_properties_impl.h => format_text_properties_impl.hxx} (100%) rename src/stream/fmt/context/formatter_executor/{formatter_args.h => formatter_args.hxx} (100%) rename src/stream/fmt/context/formatter_executor/formatter_text_properties_executor/{formatter_text_properties_executor.h => formatter_text_properties_executor.hxx} (100%) rename src/stream/fmt/context/formatter_executor/formatter_text_properties_executor/{formatter_text_properties_executor_ansi.h => formatter_text_properties_executor_ansi.hxx} (100%) rename src/stream/fmt/context/formatter_executor/{formatter_type.h => formatter_type.hxx} (100%) rename src/stream/fmt/context/formatter_executor/{index_args.h => index_args.hxx} (100%) rename src/stream/fmt/context/formatter_executor/{named_args.h => named_args.hxx} (100%) rename src/stream/fmt/context/formatter_executor/{std_enumerable.h => std_enumerable.hxx} (100%) rename src/stream/fmt/context/formatter_executor/{utility_functions.h => utility_functions.hxx} (100%) rename src/stream/fmt/context/parser_executor/{basic_parser_executor.h => basic_parser_executor.hxx} (100%) rename src/stream/fmt/context/parser_executor/{parse_basics_impl.h => parse_basics_impl.hxx} (100%) rename src/stream/fmt/context/parser_executor/{parse_text_properties_impl.h => parse_text_properties_impl.hxx} (100%) rename src/stream/fmt/context/parser_executor/{parser_args.h => parser_args.hxx} (100%) rename src/stream/fmt/context/parser_executor/parser_text_properties_executor/{parser_text_properties_executor.h => parser_text_properties_executor.hxx} (100%) rename src/stream/fmt/context/parser_executor/parser_text_properties_executor/{parser_text_properties_executor_ansi.h => parser_text_properties_executor_ansi.hxx} (100%) rename src/stream/fmt/context/parser_executor/{parser_type.h => parser_type.hxx} (100%) rename src/stream/fmt/context/parser_executor/{utility_functions.h => utility_functions.hxx} (100%) rename src/stream/fmt/context/utils/{context_functions.h => context_functions.hxx} (100%) rename src/stream/fmt/detail/{convert_traits.h => convert_traits.hxx} (100%) rename src/stream/fmt/detail/{fmt_result.h => fmt_result.hxx} (100%) rename src/stream/fmt/detail/{indent_handlers.h => indent_handlers.hxx} (100%) rename src/stream/fmt/detail/{prelude.h => prelude.hxx} (100%) rename src/stream/fmt/detail/{specifiers.h => specifiers.hxx} (100%) rename src/stream/fmt/detail/{types_traits.h => types_traits.hxx} (100%) rename src/stream/fmt/serializers/{compilation_data.h => compilation_data.hxx} (100%) rename src/stream/fmt/serializers/{format_chrono.h => format_chrono.hxx} (100%) rename src/stream/fmt/serializers/{format_stdlib.h => format_stdlib.hxx} (100%) rename src/stream/fmt/serializers/{parse_chrono.h => parse_chrono.hxx} (100%) rename src/stream/fmt/serializers/{parse_stdlib.h => parse_stdlib.hxx} (100%) rename src/stream/fmt/serializers/std_container/{array.h => array.hxx} (100%) rename src/stream/fmt/serializers/std_container/{deque.h => deque.hxx} (100%) rename src/stream/fmt/serializers/std_container/{forward_list.h => forward_list.hxx} (100%) rename src/stream/fmt/serializers/std_container/{list.h => list.hxx} (100%) rename src/stream/fmt/serializers/std_container/{map.h => map.hxx} (100%) rename src/stream/fmt/serializers/std_container/{queue.h => queue.hxx} (100%) rename src/stream/fmt/serializers/std_container/{set.h => set.hxx} (100%) rename src/stream/fmt/serializers/std_container/{stack.h => stack.hxx} (100%) rename src/stream/fmt/serializers/std_container/{tuple.h => tuple.hxx} (100%) rename src/stream/fmt/serializers/std_container/{unordered_map.h => unordered_map.hxx} (100%) rename src/stream/fmt/serializers/std_container/{unordered_set.h => unordered_set.hxx} (100%) rename src/stream/fmt/serializers/std_container/{vector.h => vector.hxx} (100%) rename src/stream/fmt/text_properties/{base_text_properties.h => base_text_properties.hxx} (100%) rename src/stream/fmt/text_properties/{text_properties.h => text_properties.hxx} (100%) rename src/stream/fmt/text_properties/{text_properties_color.h => text_properties_color.hxx} (100%) rename src/stream/fmt/text_properties/{text_properties_front.h => text_properties_front.hxx} (100%) rename src/stream/fmt/text_properties/{text_properties_style.h => text_properties_style.hxx} (100%) rename src/stream/{json.h => json.hxx} (100%) rename src/stream/json/{detail.h => detail.hxx} (100%) rename src/stream/json/{json_factory.h => json_factory.hxx} (100%) rename src/stream/json/{json_formatter.h => json_formatter.hxx} (100%) rename src/stream/json/{json_formatter_impl.h => json_formatter_impl.hxx} (100%) rename src/stream/json/{json_objects.cpp => json_objects.cxx} (100%) rename src/stream/json/{json_objects.h => json_objects.hxx} (100%) rename src/stream/json/{json_parser.cpp => json_parser.cxx} (100%) rename src/stream/json/{json_parser.h => json_parser.hxx} (100%) rename src/stream/json/{json_serializer.h => json_serializer.hxx} (100%) rename src/stream/json/serializers/{base_serializers.h => base_serializers.hxx} (100%) rename src/stream/json/serializers/{json_objects_serializer.h => json_objects_serializer.hxx} (100%) rename src/stream/json/serializers/{serializers.h => serializers.hxx} (100%) rename src/stream/json/serializers/std_serializers/{basic_std_serializers.h => basic_std_serializers.hxx} (100%) rename src/stream/json/serializers/std_serializers/{json_map.h => json_map.hxx} (100%) rename src/stream/json/serializers/std_serializers/{json_unordered_map.h => json_unordered_map.hxx} (100%) rename src/stream/json/serializers/std_serializers/{json_vector.h => json_vector.hxx} (100%) rename src/stream/{profiler.h => profiler.hxx} (100%) rename src/stream/profiler/{all_events.h => all_events.hxx} (100%) rename src/stream/profiler/{detail.h => detail.hxx} (100%) rename src/stream/profiler/{event.h => event.hxx} (100%) rename src/stream/profiler/{event_data.h => event_data.hxx} (100%) rename src/stream/profiler/{get_pid.cpp => get_pid.cxx} (100%) rename src/stream/profiler/{profiler.h => profiler.hxx} (100%) rename src/stream/profiler/{profiler_event_creator.cpp => profiler_event_creator.cxx} (100%) rename src/stream/profiler/{profiler_event_creator.h => profiler_event_creator.hxx} (100%) rename src/stream/profiler/{profiler_factory.cpp => profiler_factory.cxx} (100%) rename src/stream/profiler/{profiler_factory.h => profiler_factory.hxx} (100%) rename src/stream/profiler/{profiler_json_serializers.h => profiler_json_serializers.hxx} (100%) rename src/stream/profiler/{profiler_macros.h => profiler_macros.hxx} (100%) rename src/stream/tester/{copy_move_check.h => copy_move_check.hxx} (100%) rename src/stream/tester/test_suite/{all_test_suite.h => all_test_suite.hxx} (100%) rename src/stream/tester/test_suite/{basic_test.h => basic_test.hxx} (100%) rename src/stream/tester/test_suite/{test_suite.cpp => test_suite.cxx} (100%) rename src/stream/tester/test_suite/{test_suite.h => test_suite.hxx} (100%) rename src/stream/tester/{tests_macros.h => tests_macros.hxx} (100%) rename tests/fmt/{shift.cpp => .hxxift.cxx} (100%) rename tests/fmt/{base_fmt_tests.h => base_fmt_tests.hxx} (100%) rename tests/fmt/{complex_pattern.cpp => complex_pattern.cxx} (100%) rename tests/fmt/{globber.cpp => globber.cxx} (100%) rename tests/fmt/{index.cpp => index.cxx} (100%) rename tests/fmt/{limits.cpp => limits.cxx} (100%) rename tests/fmt/{specifier.cpp => specifier.cxx} (100%) rename tests/fmt/{text_properties.cpp => text_properties.cxx} (100%) rename tests/{tests.cpp => tests.cxx} (100%) diff --git a/examples/hello/main.cpp b/examples/hello/main.cxx similarity index 100% rename from examples/hello/main.cpp rename to examples/hello/main.cxx diff --git a/src/stream/core/prelude.h b/src/stream/core/prelude.hxx similarity index 100% rename from src/stream/core/prelude.h rename to src/stream/core/prelude.hxx diff --git a/src/stream/default_logger.h b/src/stream/default_logger.hxx similarity index 100% rename from src/stream/default_logger.h rename to src/stream/default_logger.hxx diff --git a/src/stream/flog.h b/src/stream/flog.hxx similarity index 100% rename from src/stream/flog.h rename to src/stream/flog.hxx diff --git a/src/stream/flog/backends/basic_logger.h b/src/stream/flog/backends/basic_logger.hxx similarity index 100% rename from src/stream/flog/backends/basic_logger.h rename to src/stream/flog/backends/basic_logger.hxx diff --git a/src/stream/flog/backends/logger_multi_sink.h b/src/stream/flog/backends/logger_multi_sink.hxx similarity index 100% rename from src/stream/flog/backends/logger_multi_sink.h rename to src/stream/flog/backends/logger_multi_sink.hxx diff --git a/src/stream/flog/backends/logger_multi_sink_fast.h b/src/stream/flog/backends/logger_multi_sink_fast.hxx similarity index 100% rename from src/stream/flog/backends/logger_multi_sink_fast.h rename to src/stream/flog/backends/logger_multi_sink_fast.hxx diff --git a/src/stream/flog/backends/logger_multi_sink_safe.h b/src/stream/flog/backends/logger_multi_sink_safe.hxx similarity index 100% rename from src/stream/flog/backends/logger_multi_sink_safe.h rename to src/stream/flog/backends/logger_multi_sink_safe.hxx diff --git a/src/stream/flog/detail/detail.h b/src/stream/flog/detail/detail.hxx similarity index 100% rename from src/stream/flog/detail/detail.h rename to src/stream/flog/detail/detail.hxx diff --git a/src/stream/flog/frontends/xlogger.cpp b/src/stream/flog/frontends/xlogger.cxx similarity index 100% rename from src/stream/flog/frontends/xlogger.cpp rename to src/stream/flog/frontends/xlogger.cxx diff --git a/src/stream/flog/frontends/xlogger.h b/src/stream/flog/frontends/xlogger.hxx similarity index 100% rename from src/stream/flog/frontends/xlogger.h rename to src/stream/flog/frontends/xlogger.hxx diff --git a/src/stream/flog/logger_factory.h b/src/stream/flog/logger_factory.hxx similarity index 100% rename from src/stream/flog/logger_factory.h rename to src/stream/flog/logger_factory.hxx diff --git a/src/stream/flog/sinks/file_sink.h b/src/stream/flog/sinks/file_sink.hxx similarity index 100% rename from src/stream/flog/sinks/file_sink.h rename to src/stream/flog/sinks/file_sink.hxx diff --git a/src/stream/flog/sinks/logger_sink.h b/src/stream/flog/sinks/logger_sink.hxx similarity index 100% rename from src/stream/flog/sinks/logger_sink.h rename to src/stream/flog/sinks/logger_sink.hxx diff --git a/src/stream/fmt.h b/src/stream/fmt.hxx similarity index 100% rename from src/stream/fmt.h rename to src/stream/fmt.hxx diff --git a/src/stream/fmt/buf/fmt_manip_io.h b/src/stream/fmt/buf/fmt_manip_io.hxx similarity index 100% rename from src/stream/fmt/buf/fmt_manip_io.h rename to src/stream/fmt/buf/fmt_manip_io.hxx diff --git a/src/stream/fmt/buf/fmt_read_manip.h b/src/stream/fmt/buf/fmt_read_manip.hxx similarity index 100% rename from src/stream/fmt/buf/fmt_read_manip.h rename to src/stream/fmt/buf/fmt_read_manip.hxx diff --git a/src/stream/fmt/buf/fmt_write_manip.h b/src/stream/fmt/buf/fmt_write_manip.hxx similarity index 100% rename from src/stream/fmt/buf/fmt_write_manip.h rename to src/stream/fmt/buf/fmt_write_manip.hxx diff --git a/src/stream/fmt/buf/manip.h b/src/stream/fmt/buf/manip.hxx similarity index 100% rename from src/stream/fmt/buf/manip.h rename to src/stream/fmt/buf/manip.hxx diff --git a/src/stream/fmt/buf/manip_io.h b/src/stream/fmt/buf/manip_io.hxx similarity index 100% rename from src/stream/fmt/buf/manip_io.h rename to src/stream/fmt/buf/manip_io.hxx diff --git a/src/stream/fmt/buf/read_manip.h b/src/stream/fmt/buf/read_manip.hxx similarity index 100% rename from src/stream/fmt/buf/read_manip.h rename to src/stream/fmt/buf/read_manip.hxx diff --git a/src/stream/fmt/buf/stream.h b/src/stream/fmt/buf/stream.hxx similarity index 100% rename from src/stream/fmt/buf/stream.h rename to src/stream/fmt/buf/stream.hxx diff --git a/src/stream/fmt/buf/streamio.h b/src/stream/fmt/buf/streamio.hxx similarity index 100% rename from src/stream/fmt/buf/streamio.h rename to src/stream/fmt/buf/streamio.hxx diff --git a/src/stream/fmt/buf/streamio_manager/basic_streamio_manager.h b/src/stream/fmt/buf/streamio_manager/basic_streamio_manager.hxx similarity index 100% rename from src/stream/fmt/buf/streamio_manager/basic_streamio_manager.h rename to src/stream/fmt/buf/streamio_manager/basic_streamio_manager.hxx diff --git a/src/stream/fmt/buf/streamio_manager/dynamic_streamio_manager.h b/src/stream/fmt/buf/streamio_manager/dynamic_streamio_manager.hxx similarity index 100% rename from src/stream/fmt/buf/streamio_manager/dynamic_streamio_manager.h rename to src/stream/fmt/buf/streamio_manager/dynamic_streamio_manager.hxx diff --git a/src/stream/fmt/buf/streamio_manager/given_streamio_manager.h b/src/stream/fmt/buf/streamio_manager/given_streamio_manager.hxx similarity index 100% rename from src/stream/fmt/buf/streamio_manager/given_streamio_manager.h rename to src/stream/fmt/buf/streamio_manager/given_streamio_manager.hxx diff --git a/src/stream/fmt/buf/streamio_manager/static_streamio_manager.h b/src/stream/fmt/buf/streamio_manager/static_streamio_manager.hxx similarity index 100% rename from src/stream/fmt/buf/streamio_manager/static_streamio_manager.h rename to src/stream/fmt/buf/streamio_manager/static_streamio_manager.hxx diff --git a/src/stream/fmt/buf/test_manip.h b/src/stream/fmt/buf/test_manip.hxx similarity index 100% rename from src/stream/fmt/buf/test_manip.h rename to src/stream/fmt/buf/test_manip.hxx diff --git a/src/stream/fmt/buf/utils/buffer_globber_manip.h b/src/stream/fmt/buf/utils/buffer_globber_manip.hxx similarity index 100% rename from src/stream/fmt/buf/utils/buffer_globber_manip.h rename to src/stream/fmt/buf/utils/buffer_globber_manip.hxx diff --git a/src/stream/fmt/buf/utils/buffer_shift_manip.h b/src/stream/fmt/buf/utils/buffer_shift_manip.hxx similarity index 100% rename from src/stream/fmt/buf/utils/buffer_shift_manip.h rename to src/stream/fmt/buf/utils/buffer_shift_manip.hxx diff --git a/src/stream/fmt/buf/utils/buffer_utils.h b/src/stream/fmt/buf/utils/buffer_utils.hxx similarity index 100% rename from src/stream/fmt/buf/utils/buffer_utils.h rename to src/stream/fmt/buf/utils/buffer_utils.hxx diff --git a/src/stream/fmt/buf/write_manip.h b/src/stream/fmt/buf/write_manip.hxx similarity index 100% rename from src/stream/fmt/buf/write_manip.h rename to src/stream/fmt/buf/write_manip.hxx diff --git a/src/stream/fmt/context/basic_context/basic_args_interface.h b/src/stream/fmt/context/basic_context/basic_args_interface.hxx similarity index 100% rename from src/stream/fmt/context/basic_context/basic_args_interface.h rename to src/stream/fmt/context/basic_context/basic_args_interface.hxx diff --git a/src/stream/fmt/context/basic_context/basic_context.h b/src/stream/fmt/context/basic_context/basic_context.hxx similarity index 100% rename from src/stream/fmt/context/basic_context/basic_context.h rename to src/stream/fmt/context/basic_context/basic_context.hxx diff --git a/src/stream/fmt/context/basic_context/basic_context_parse_impl.h b/src/stream/fmt/context/basic_context/basic_context_parse_impl.hxx similarity index 100% rename from src/stream/fmt/context/basic_context/basic_context_parse_impl.h rename to src/stream/fmt/context/basic_context/basic_context_parse_impl.hxx diff --git a/src/stream/fmt/context/basic_context/text_properties_executor.h b/src/stream/fmt/context/basic_context/text_properties_executor.hxx similarity index 100% rename from src/stream/fmt/context/basic_context/text_properties_executor.h rename to src/stream/fmt/context/basic_context/text_properties_executor.hxx diff --git a/src/stream/fmt/context/basic_context/text_properties_manager.cpp b/src/stream/fmt/context/basic_context/text_properties_manager.cxx similarity index 100% rename from src/stream/fmt/context/basic_context/text_properties_manager.cpp rename to src/stream/fmt/context/basic_context/text_properties_manager.cxx diff --git a/src/stream/fmt/context/basic_context/text_properties_manager.h b/src/stream/fmt/context/basic_context/text_properties_manager.hxx similarity index 100% rename from src/stream/fmt/context/basic_context/text_properties_manager.h rename to src/stream/fmt/context/basic_context/text_properties_manager.hxx diff --git a/src/stream/fmt/context/basic_context/text_properties_manager_impl.h b/src/stream/fmt/context/basic_context/text_properties_manager_impl.hxx similarity index 100% rename from src/stream/fmt/context/basic_context/text_properties_manager_impl.h rename to src/stream/fmt/context/basic_context/text_properties_manager_impl.hxx diff --git a/src/stream/fmt/context/formatter_executor/basic_formatter_executor.h b/src/stream/fmt/context/formatter_executor/basic_formatter_executor.hxx similarity index 100% rename from src/stream/fmt/context/formatter_executor/basic_formatter_executor.h rename to src/stream/fmt/context/formatter_executor/basic_formatter_executor.hxx diff --git a/src/stream/fmt/context/formatter_executor/format_basics_impl.h b/src/stream/fmt/context/formatter_executor/format_basics_impl.hxx similarity index 100% rename from src/stream/fmt/context/formatter_executor/format_basics_impl.h rename to src/stream/fmt/context/formatter_executor/format_basics_impl.hxx diff --git a/src/stream/fmt/context/formatter_executor/format_text_properties_impl.h b/src/stream/fmt/context/formatter_executor/format_text_properties_impl.hxx similarity index 100% rename from src/stream/fmt/context/formatter_executor/format_text_properties_impl.h rename to src/stream/fmt/context/formatter_executor/format_text_properties_impl.hxx diff --git a/src/stream/fmt/context/formatter_executor/formatter_args.h b/src/stream/fmt/context/formatter_executor/formatter_args.hxx similarity index 100% rename from src/stream/fmt/context/formatter_executor/formatter_args.h rename to src/stream/fmt/context/formatter_executor/formatter_args.hxx diff --git a/src/stream/fmt/context/formatter_executor/formatter_text_properties_executor/formatter_text_properties_executor.h b/src/stream/fmt/context/formatter_executor/formatter_text_properties_executor/formatter_text_properties_executor.hxx similarity index 100% rename from src/stream/fmt/context/formatter_executor/formatter_text_properties_executor/formatter_text_properties_executor.h rename to src/stream/fmt/context/formatter_executor/formatter_text_properties_executor/formatter_text_properties_executor.hxx diff --git a/src/stream/fmt/context/formatter_executor/formatter_text_properties_executor/formatter_text_properties_executor_ansi.h b/src/stream/fmt/context/formatter_executor/formatter_text_properties_executor/formatter_text_properties_executor_ansi.hxx similarity index 100% rename from src/stream/fmt/context/formatter_executor/formatter_text_properties_executor/formatter_text_properties_executor_ansi.h rename to src/stream/fmt/context/formatter_executor/formatter_text_properties_executor/formatter_text_properties_executor_ansi.hxx diff --git a/src/stream/fmt/context/formatter_executor/formatter_type.h b/src/stream/fmt/context/formatter_executor/formatter_type.hxx similarity index 100% rename from src/stream/fmt/context/formatter_executor/formatter_type.h rename to src/stream/fmt/context/formatter_executor/formatter_type.hxx diff --git a/src/stream/fmt/context/formatter_executor/index_args.h b/src/stream/fmt/context/formatter_executor/index_args.hxx similarity index 100% rename from src/stream/fmt/context/formatter_executor/index_args.h rename to src/stream/fmt/context/formatter_executor/index_args.hxx diff --git a/src/stream/fmt/context/formatter_executor/named_args.h b/src/stream/fmt/context/formatter_executor/named_args.hxx similarity index 100% rename from src/stream/fmt/context/formatter_executor/named_args.h rename to src/stream/fmt/context/formatter_executor/named_args.hxx diff --git a/src/stream/fmt/context/formatter_executor/std_enumerable.h b/src/stream/fmt/context/formatter_executor/std_enumerable.hxx similarity index 100% rename from src/stream/fmt/context/formatter_executor/std_enumerable.h rename to src/stream/fmt/context/formatter_executor/std_enumerable.hxx diff --git a/src/stream/fmt/context/formatter_executor/utility_functions.h b/src/stream/fmt/context/formatter_executor/utility_functions.hxx similarity index 100% rename from src/stream/fmt/context/formatter_executor/utility_functions.h rename to src/stream/fmt/context/formatter_executor/utility_functions.hxx diff --git a/src/stream/fmt/context/parser_executor/basic_parser_executor.h b/src/stream/fmt/context/parser_executor/basic_parser_executor.hxx similarity index 100% rename from src/stream/fmt/context/parser_executor/basic_parser_executor.h rename to src/stream/fmt/context/parser_executor/basic_parser_executor.hxx diff --git a/src/stream/fmt/context/parser_executor/parse_basics_impl.h b/src/stream/fmt/context/parser_executor/parse_basics_impl.hxx similarity index 100% rename from src/stream/fmt/context/parser_executor/parse_basics_impl.h rename to src/stream/fmt/context/parser_executor/parse_basics_impl.hxx diff --git a/src/stream/fmt/context/parser_executor/parse_text_properties_impl.h b/src/stream/fmt/context/parser_executor/parse_text_properties_impl.hxx similarity index 100% rename from src/stream/fmt/context/parser_executor/parse_text_properties_impl.h rename to src/stream/fmt/context/parser_executor/parse_text_properties_impl.hxx diff --git a/src/stream/fmt/context/parser_executor/parser_args.h b/src/stream/fmt/context/parser_executor/parser_args.hxx similarity index 100% rename from src/stream/fmt/context/parser_executor/parser_args.h rename to src/stream/fmt/context/parser_executor/parser_args.hxx diff --git a/src/stream/fmt/context/parser_executor/parser_text_properties_executor/parser_text_properties_executor.h b/src/stream/fmt/context/parser_executor/parser_text_properties_executor/parser_text_properties_executor.hxx similarity index 100% rename from src/stream/fmt/context/parser_executor/parser_text_properties_executor/parser_text_properties_executor.h rename to src/stream/fmt/context/parser_executor/parser_text_properties_executor/parser_text_properties_executor.hxx diff --git a/src/stream/fmt/context/parser_executor/parser_text_properties_executor/parser_text_properties_executor_ansi.h b/src/stream/fmt/context/parser_executor/parser_text_properties_executor/parser_text_properties_executor_ansi.hxx similarity index 100% rename from src/stream/fmt/context/parser_executor/parser_text_properties_executor/parser_text_properties_executor_ansi.h rename to src/stream/fmt/context/parser_executor/parser_text_properties_executor/parser_text_properties_executor_ansi.hxx diff --git a/src/stream/fmt/context/parser_executor/parser_type.h b/src/stream/fmt/context/parser_executor/parser_type.hxx similarity index 100% rename from src/stream/fmt/context/parser_executor/parser_type.h rename to src/stream/fmt/context/parser_executor/parser_type.hxx diff --git a/src/stream/fmt/context/parser_executor/utility_functions.h b/src/stream/fmt/context/parser_executor/utility_functions.hxx similarity index 100% rename from src/stream/fmt/context/parser_executor/utility_functions.h rename to src/stream/fmt/context/parser_executor/utility_functions.hxx diff --git a/src/stream/fmt/context/utils/context_functions.h b/src/stream/fmt/context/utils/context_functions.hxx similarity index 100% rename from src/stream/fmt/context/utils/context_functions.h rename to src/stream/fmt/context/utils/context_functions.hxx diff --git a/src/stream/fmt/detail/convert_traits.h b/src/stream/fmt/detail/convert_traits.hxx similarity index 100% rename from src/stream/fmt/detail/convert_traits.h rename to src/stream/fmt/detail/convert_traits.hxx diff --git a/src/stream/fmt/detail/fmt_result.h b/src/stream/fmt/detail/fmt_result.hxx similarity index 100% rename from src/stream/fmt/detail/fmt_result.h rename to src/stream/fmt/detail/fmt_result.hxx diff --git a/src/stream/fmt/detail/indent_handlers.h b/src/stream/fmt/detail/indent_handlers.hxx similarity index 100% rename from src/stream/fmt/detail/indent_handlers.h rename to src/stream/fmt/detail/indent_handlers.hxx diff --git a/src/stream/fmt/detail/prelude.h b/src/stream/fmt/detail/prelude.hxx similarity index 100% rename from src/stream/fmt/detail/prelude.h rename to src/stream/fmt/detail/prelude.hxx diff --git a/src/stream/fmt/detail/specifiers.h b/src/stream/fmt/detail/specifiers.hxx similarity index 100% rename from src/stream/fmt/detail/specifiers.h rename to src/stream/fmt/detail/specifiers.hxx diff --git a/src/stream/fmt/detail/types_traits.h b/src/stream/fmt/detail/types_traits.hxx similarity index 100% rename from src/stream/fmt/detail/types_traits.h rename to src/stream/fmt/detail/types_traits.hxx diff --git a/src/stream/fmt/serializers/compilation_data.h b/src/stream/fmt/serializers/compilation_data.hxx similarity index 100% rename from src/stream/fmt/serializers/compilation_data.h rename to src/stream/fmt/serializers/compilation_data.hxx diff --git a/src/stream/fmt/serializers/format_chrono.h b/src/stream/fmt/serializers/format_chrono.hxx similarity index 100% rename from src/stream/fmt/serializers/format_chrono.h rename to src/stream/fmt/serializers/format_chrono.hxx diff --git a/src/stream/fmt/serializers/format_stdlib.h b/src/stream/fmt/serializers/format_stdlib.hxx similarity index 100% rename from src/stream/fmt/serializers/format_stdlib.h rename to src/stream/fmt/serializers/format_stdlib.hxx diff --git a/src/stream/fmt/serializers/parse_chrono.h b/src/stream/fmt/serializers/parse_chrono.hxx similarity index 100% rename from src/stream/fmt/serializers/parse_chrono.h rename to src/stream/fmt/serializers/parse_chrono.hxx diff --git a/src/stream/fmt/serializers/parse_stdlib.h b/src/stream/fmt/serializers/parse_stdlib.hxx similarity index 100% rename from src/stream/fmt/serializers/parse_stdlib.h rename to src/stream/fmt/serializers/parse_stdlib.hxx diff --git a/src/stream/fmt/serializers/std_container/array.h b/src/stream/fmt/serializers/std_container/array.hxx similarity index 100% rename from src/stream/fmt/serializers/std_container/array.h rename to src/stream/fmt/serializers/std_container/array.hxx diff --git a/src/stream/fmt/serializers/std_container/deque.h b/src/stream/fmt/serializers/std_container/deque.hxx similarity index 100% rename from src/stream/fmt/serializers/std_container/deque.h rename to src/stream/fmt/serializers/std_container/deque.hxx diff --git a/src/stream/fmt/serializers/std_container/forward_list.h b/src/stream/fmt/serializers/std_container/forward_list.hxx similarity index 100% rename from src/stream/fmt/serializers/std_container/forward_list.h rename to src/stream/fmt/serializers/std_container/forward_list.hxx diff --git a/src/stream/fmt/serializers/std_container/list.h b/src/stream/fmt/serializers/std_container/list.hxx similarity index 100% rename from src/stream/fmt/serializers/std_container/list.h rename to src/stream/fmt/serializers/std_container/list.hxx diff --git a/src/stream/fmt/serializers/std_container/map.h b/src/stream/fmt/serializers/std_container/map.hxx similarity index 100% rename from src/stream/fmt/serializers/std_container/map.h rename to src/stream/fmt/serializers/std_container/map.hxx diff --git a/src/stream/fmt/serializers/std_container/queue.h b/src/stream/fmt/serializers/std_container/queue.hxx similarity index 100% rename from src/stream/fmt/serializers/std_container/queue.h rename to src/stream/fmt/serializers/std_container/queue.hxx diff --git a/src/stream/fmt/serializers/std_container/set.h b/src/stream/fmt/serializers/std_container/set.hxx similarity index 100% rename from src/stream/fmt/serializers/std_container/set.h rename to src/stream/fmt/serializers/std_container/set.hxx diff --git a/src/stream/fmt/serializers/std_container/stack.h b/src/stream/fmt/serializers/std_container/stack.hxx similarity index 100% rename from src/stream/fmt/serializers/std_container/stack.h rename to src/stream/fmt/serializers/std_container/stack.hxx diff --git a/src/stream/fmt/serializers/std_container/tuple.h b/src/stream/fmt/serializers/std_container/tuple.hxx similarity index 100% rename from src/stream/fmt/serializers/std_container/tuple.h rename to src/stream/fmt/serializers/std_container/tuple.hxx diff --git a/src/stream/fmt/serializers/std_container/unordered_map.h b/src/stream/fmt/serializers/std_container/unordered_map.hxx similarity index 100% rename from src/stream/fmt/serializers/std_container/unordered_map.h rename to src/stream/fmt/serializers/std_container/unordered_map.hxx diff --git a/src/stream/fmt/serializers/std_container/unordered_set.h b/src/stream/fmt/serializers/std_container/unordered_set.hxx similarity index 100% rename from src/stream/fmt/serializers/std_container/unordered_set.h rename to src/stream/fmt/serializers/std_container/unordered_set.hxx diff --git a/src/stream/fmt/serializers/std_container/vector.h b/src/stream/fmt/serializers/std_container/vector.hxx similarity index 100% rename from src/stream/fmt/serializers/std_container/vector.h rename to src/stream/fmt/serializers/std_container/vector.hxx diff --git a/src/stream/fmt/text_properties/base_text_properties.h b/src/stream/fmt/text_properties/base_text_properties.hxx similarity index 100% rename from src/stream/fmt/text_properties/base_text_properties.h rename to src/stream/fmt/text_properties/base_text_properties.hxx diff --git a/src/stream/fmt/text_properties/text_properties.h b/src/stream/fmt/text_properties/text_properties.hxx similarity index 100% rename from src/stream/fmt/text_properties/text_properties.h rename to src/stream/fmt/text_properties/text_properties.hxx diff --git a/src/stream/fmt/text_properties/text_properties_color.h b/src/stream/fmt/text_properties/text_properties_color.hxx similarity index 100% rename from src/stream/fmt/text_properties/text_properties_color.h rename to src/stream/fmt/text_properties/text_properties_color.hxx diff --git a/src/stream/fmt/text_properties/text_properties_front.h b/src/stream/fmt/text_properties/text_properties_front.hxx similarity index 100% rename from src/stream/fmt/text_properties/text_properties_front.h rename to src/stream/fmt/text_properties/text_properties_front.hxx diff --git a/src/stream/fmt/text_properties/text_properties_style.h b/src/stream/fmt/text_properties/text_properties_style.hxx similarity index 100% rename from src/stream/fmt/text_properties/text_properties_style.h rename to src/stream/fmt/text_properties/text_properties_style.hxx diff --git a/src/stream/json.h b/src/stream/json.hxx similarity index 100% rename from src/stream/json.h rename to src/stream/json.hxx diff --git a/src/stream/json/detail.h b/src/stream/json/detail.hxx similarity index 100% rename from src/stream/json/detail.h rename to src/stream/json/detail.hxx diff --git a/src/stream/json/json_factory.h b/src/stream/json/json_factory.hxx similarity index 100% rename from src/stream/json/json_factory.h rename to src/stream/json/json_factory.hxx diff --git a/src/stream/json/json_formatter.h b/src/stream/json/json_formatter.hxx similarity index 100% rename from src/stream/json/json_formatter.h rename to src/stream/json/json_formatter.hxx diff --git a/src/stream/json/json_formatter_impl.h b/src/stream/json/json_formatter_impl.hxx similarity index 100% rename from src/stream/json/json_formatter_impl.h rename to src/stream/json/json_formatter_impl.hxx diff --git a/src/stream/json/json_objects.cpp b/src/stream/json/json_objects.cxx similarity index 100% rename from src/stream/json/json_objects.cpp rename to src/stream/json/json_objects.cxx diff --git a/src/stream/json/json_objects.h b/src/stream/json/json_objects.hxx similarity index 100% rename from src/stream/json/json_objects.h rename to src/stream/json/json_objects.hxx diff --git a/src/stream/json/json_parser.cpp b/src/stream/json/json_parser.cxx similarity index 100% rename from src/stream/json/json_parser.cpp rename to src/stream/json/json_parser.cxx diff --git a/src/stream/json/json_parser.h b/src/stream/json/json_parser.hxx similarity index 100% rename from src/stream/json/json_parser.h rename to src/stream/json/json_parser.hxx diff --git a/src/stream/json/json_serializer.h b/src/stream/json/json_serializer.hxx similarity index 100% rename from src/stream/json/json_serializer.h rename to src/stream/json/json_serializer.hxx diff --git a/src/stream/json/serializers/base_serializers.h b/src/stream/json/serializers/base_serializers.hxx similarity index 100% rename from src/stream/json/serializers/base_serializers.h rename to src/stream/json/serializers/base_serializers.hxx diff --git a/src/stream/json/serializers/json_objects_serializer.h b/src/stream/json/serializers/json_objects_serializer.hxx similarity index 100% rename from src/stream/json/serializers/json_objects_serializer.h rename to src/stream/json/serializers/json_objects_serializer.hxx diff --git a/src/stream/json/serializers/serializers.h b/src/stream/json/serializers/serializers.hxx similarity index 100% rename from src/stream/json/serializers/serializers.h rename to src/stream/json/serializers/serializers.hxx diff --git a/src/stream/json/serializers/std_serializers/basic_std_serializers.h b/src/stream/json/serializers/std_serializers/basic_std_serializers.hxx similarity index 100% rename from src/stream/json/serializers/std_serializers/basic_std_serializers.h rename to src/stream/json/serializers/std_serializers/basic_std_serializers.hxx diff --git a/src/stream/json/serializers/std_serializers/json_map.h b/src/stream/json/serializers/std_serializers/json_map.hxx similarity index 100% rename from src/stream/json/serializers/std_serializers/json_map.h rename to src/stream/json/serializers/std_serializers/json_map.hxx diff --git a/src/stream/json/serializers/std_serializers/json_unordered_map.h b/src/stream/json/serializers/std_serializers/json_unordered_map.hxx similarity index 100% rename from src/stream/json/serializers/std_serializers/json_unordered_map.h rename to src/stream/json/serializers/std_serializers/json_unordered_map.hxx diff --git a/src/stream/json/serializers/std_serializers/json_vector.h b/src/stream/json/serializers/std_serializers/json_vector.hxx similarity index 100% rename from src/stream/json/serializers/std_serializers/json_vector.h rename to src/stream/json/serializers/std_serializers/json_vector.hxx diff --git a/src/stream/profiler.h b/src/stream/profiler.hxx similarity index 100% rename from src/stream/profiler.h rename to src/stream/profiler.hxx diff --git a/src/stream/profiler/all_events.h b/src/stream/profiler/all_events.hxx similarity index 100% rename from src/stream/profiler/all_events.h rename to src/stream/profiler/all_events.hxx diff --git a/src/stream/profiler/detail.h b/src/stream/profiler/detail.hxx similarity index 100% rename from src/stream/profiler/detail.h rename to src/stream/profiler/detail.hxx diff --git a/src/stream/profiler/event.h b/src/stream/profiler/event.hxx similarity index 100% rename from src/stream/profiler/event.h rename to src/stream/profiler/event.hxx diff --git a/src/stream/profiler/event_data.h b/src/stream/profiler/event_data.hxx similarity index 100% rename from src/stream/profiler/event_data.h rename to src/stream/profiler/event_data.hxx diff --git a/src/stream/profiler/get_pid.cpp b/src/stream/profiler/get_pid.cxx similarity index 100% rename from src/stream/profiler/get_pid.cpp rename to src/stream/profiler/get_pid.cxx diff --git a/src/stream/profiler/profiler.h b/src/stream/profiler/profiler.hxx similarity index 100% rename from src/stream/profiler/profiler.h rename to src/stream/profiler/profiler.hxx diff --git a/src/stream/profiler/profiler_event_creator.cpp b/src/stream/profiler/profiler_event_creator.cxx similarity index 100% rename from src/stream/profiler/profiler_event_creator.cpp rename to src/stream/profiler/profiler_event_creator.cxx diff --git a/src/stream/profiler/profiler_event_creator.h b/src/stream/profiler/profiler_event_creator.hxx similarity index 100% rename from src/stream/profiler/profiler_event_creator.h rename to src/stream/profiler/profiler_event_creator.hxx diff --git a/src/stream/profiler/profiler_factory.cpp b/src/stream/profiler/profiler_factory.cxx similarity index 100% rename from src/stream/profiler/profiler_factory.cpp rename to src/stream/profiler/profiler_factory.cxx diff --git a/src/stream/profiler/profiler_factory.h b/src/stream/profiler/profiler_factory.hxx similarity index 100% rename from src/stream/profiler/profiler_factory.h rename to src/stream/profiler/profiler_factory.hxx diff --git a/src/stream/profiler/profiler_json_serializers.h b/src/stream/profiler/profiler_json_serializers.hxx similarity index 100% rename from src/stream/profiler/profiler_json_serializers.h rename to src/stream/profiler/profiler_json_serializers.hxx diff --git a/src/stream/profiler/profiler_macros.h b/src/stream/profiler/profiler_macros.hxx similarity index 100% rename from src/stream/profiler/profiler_macros.h rename to src/stream/profiler/profiler_macros.hxx diff --git a/src/stream/tester/copy_move_check.h b/src/stream/tester/copy_move_check.hxx similarity index 100% rename from src/stream/tester/copy_move_check.h rename to src/stream/tester/copy_move_check.hxx diff --git a/src/stream/tester/test_suite/all_test_suite.h b/src/stream/tester/test_suite/all_test_suite.hxx similarity index 100% rename from src/stream/tester/test_suite/all_test_suite.h rename to src/stream/tester/test_suite/all_test_suite.hxx diff --git a/src/stream/tester/test_suite/basic_test.h b/src/stream/tester/test_suite/basic_test.hxx similarity index 100% rename from src/stream/tester/test_suite/basic_test.h rename to src/stream/tester/test_suite/basic_test.hxx diff --git a/src/stream/tester/test_suite/test_suite.cpp b/src/stream/tester/test_suite/test_suite.cxx similarity index 100% rename from src/stream/tester/test_suite/test_suite.cpp rename to src/stream/tester/test_suite/test_suite.cxx diff --git a/src/stream/tester/test_suite/test_suite.h b/src/stream/tester/test_suite/test_suite.hxx similarity index 100% rename from src/stream/tester/test_suite/test_suite.h rename to src/stream/tester/test_suite/test_suite.hxx diff --git a/src/stream/tester/tests_macros.h b/src/stream/tester/tests_macros.hxx similarity index 100% rename from src/stream/tester/tests_macros.h rename to src/stream/tester/tests_macros.hxx diff --git a/tests/fmt/shift.cpp b/tests/fmt/.hxxift.cxx similarity index 100% rename from tests/fmt/shift.cpp rename to tests/fmt/.hxxift.cxx diff --git a/tests/fmt/base_fmt_tests.h b/tests/fmt/base_fmt_tests.hxx similarity index 100% rename from tests/fmt/base_fmt_tests.h rename to tests/fmt/base_fmt_tests.hxx diff --git a/tests/fmt/complex_pattern.cpp b/tests/fmt/complex_pattern.cxx similarity index 100% rename from tests/fmt/complex_pattern.cpp rename to tests/fmt/complex_pattern.cxx diff --git a/tests/fmt/globber.cpp b/tests/fmt/globber.cxx similarity index 100% rename from tests/fmt/globber.cpp rename to tests/fmt/globber.cxx diff --git a/tests/fmt/index.cpp b/tests/fmt/index.cxx similarity index 100% rename from tests/fmt/index.cpp rename to tests/fmt/index.cxx diff --git a/tests/fmt/limits.cpp b/tests/fmt/limits.cxx similarity index 100% rename from tests/fmt/limits.cpp rename to tests/fmt/limits.cxx diff --git a/tests/fmt/specifier.cpp b/tests/fmt/specifier.cxx similarity index 100% rename from tests/fmt/specifier.cpp rename to tests/fmt/specifier.cxx diff --git a/tests/fmt/text_properties.cpp b/tests/fmt/text_properties.cxx similarity index 100% rename from tests/fmt/text_properties.cpp rename to tests/fmt/text_properties.cxx diff --git a/tests/tests.cpp b/tests/tests.cxx similarity index 100% rename from tests/tests.cpp rename to tests/tests.cxx From dcf24ca4e91290b68d2065e85b8e63ee6513d728 Mon Sep 17 00:00:00 2001 From: Sacha Bellier Date: Sun, 23 Mar 2025 19:22:40 +0100 Subject: [PATCH 23/42] wip: includes path changes from `h` to `hxx` --- BUILD.bazel | 4 ++-- examples/hello/BUILD.bazel | 2 +- examples/hello/main.cxx | 6 ++--- src/stream/default_logger.hxx | 2 +- src/stream/flog.hxx | 12 +++++----- src/stream/flog/backends/basic_logger.hxx | 4 ++-- .../flog/backends/logger_multi_sink.hxx | 4 ++-- .../flog/backends/logger_multi_sink_fast.hxx | 2 +- .../flog/backends/logger_multi_sink_safe.hxx | 2 +- src/stream/flog/detail/detail.hxx | 6 ++--- src/stream/flog/frontends/xlogger.cxx | 2 +- src/stream/flog/frontends/xlogger.hxx | 10 ++++----- src/stream/flog/logger_factory.hxx | 6 ++--- src/stream/flog/sinks/file_sink.hxx | 2 +- src/stream/flog/sinks/logger_sink.hxx | 2 +- src/stream/fmt.hxx | 4 ++-- src/stream/fmt/buf/fmt_manip_io.hxx | 6 ++--- src/stream/fmt/buf/fmt_read_manip.hxx | 10 ++++----- src/stream/fmt/buf/fmt_write_manip.hxx | 10 ++++----- src/stream/fmt/buf/manip.hxx | 2 +- src/stream/fmt/buf/manip_io.hxx | 8 +++---- src/stream/fmt/buf/read_manip.hxx | 4 ++-- src/stream/fmt/buf/stream.hxx | 2 +- src/stream/fmt/buf/streamio.hxx | 6 ++--- .../basic_streamio_manager.hxx | 4 ++-- .../dynamic_streamio_manager.hxx | 2 +- .../given_streamio_manager.hxx | 2 +- .../static_streamio_manager.hxx | 2 +- src/stream/fmt/buf/test_manip.hxx | 4 ++-- .../fmt/buf/utils/buffer_globber_manip.hxx | 4 ++-- .../fmt/buf/utils/buffer_shift_manip.hxx | 4 ++-- src/stream/fmt/buf/utils/buffer_utils.hxx | 18 +++++++-------- src/stream/fmt/buf/write_manip.hxx | 8 +++---- .../basic_context/basic_args_interface.hxx | 6 ++--- .../context/basic_context/basic_context.hxx | 22 +++++++++---------- .../basic_context_parse_impl.hxx | 16 +++++++------- .../text_properties_executor.hxx | 4 ++-- .../basic_context/text_properties_manager.cxx | 2 +- .../basic_context/text_properties_manager.hxx | 14 ++++++------ .../text_properties_manager_impl.hxx | 12 +++++----- .../basic_formatter_executor.hxx | 20 ++++++++--------- .../formatter_executor/format_basics_impl.hxx | 4 ++-- .../format_text_properties_impl.hxx | 2 +- .../formatter_executor/formatter_args.hxx | 6 ++--- .../formatter_text_properties_executor.hxx | 6 ++--- ...ormatter_text_properties_executor_ansi.hxx | 4 ++-- .../formatter_executor/formatter_type.hxx | 2 +- .../context/formatter_executor/index_args.hxx | 2 +- .../context/formatter_executor/named_args.hxx | 2 +- .../formatter_executor/std_enumerable.hxx | 6 ++--- .../formatter_executor/utility_functions.hxx | 10 ++++----- .../parser_executor/basic_parser_executor.hxx | 18 +++++++-------- .../parser_executor/parse_basics_impl.hxx | 4 ++-- .../parse_text_properties_impl.hxx | 2 +- .../context/parser_executor/parser_args.hxx | 4 ++-- .../parser_text_properties_executor.hxx | 6 ++--- .../parser_text_properties_executor_ansi.hxx | 2 +- .../context/parser_executor/parser_type.hxx | 2 +- .../parser_executor/utility_functions.hxx | 8 +++---- .../fmt/context/utils/context_functions.hxx | 2 +- src/stream/fmt/detail/convert_traits.hxx | 2 +- src/stream/fmt/detail/fmt_result.hxx | 2 +- src/stream/fmt/detail/indent_handlers.hxx | 4 ++-- src/stream/fmt/detail/prelude.hxx | 6 ++--- src/stream/fmt/detail/specifiers.hxx | 4 ++-- src/stream/fmt/detail/types_traits.hxx | 2 +- .../fmt/serializers/compilation_data.hxx | 4 ++-- src/stream/fmt/serializers/format_chrono.hxx | 10 ++++----- src/stream/fmt/serializers/format_stdlib.hxx | 2 +- src/stream/fmt/serializers/parse_chrono.hxx | 2 +- src/stream/fmt/serializers/parse_stdlib.hxx | 2 +- .../fmt/serializers/std_container/array.hxx | 4 ++-- .../fmt/serializers/std_container/deque.hxx | 4 ++-- .../std_container/forward_list.hxx | 4 ++-- .../fmt/serializers/std_container/list.hxx | 4 ++-- .../fmt/serializers/std_container/map.hxx | 4 ++-- .../fmt/serializers/std_container/queue.hxx | 2 +- .../fmt/serializers/std_container/set.hxx | 4 ++-- .../fmt/serializers/std_container/stack.hxx | 2 +- .../fmt/serializers/std_container/tuple.hxx | 2 +- .../std_container/unordered_map.hxx | 4 ++-- .../std_container/unordered_set.hxx | 4 ++-- .../fmt/serializers/std_container/vector.hxx | 4 ++-- .../text_properties/base_text_properties.hxx | 2 +- .../fmt/text_properties/text_properties.hxx | 6 ++--- .../text_properties/text_properties_color.hxx | 2 +- .../text_properties/text_properties_front.hxx | 2 +- .../text_properties/text_properties_style.hxx | 4 ++-- src/stream/json.hxx | 8 +++---- src/stream/json/json_factory.hxx | 20 ++++++++--------- src/stream/json/json_formatter.hxx | 6 ++--- src/stream/json/json_formatter_impl.hxx | 4 ++-- src/stream/json/json_objects.cxx | 4 ++-- src/stream/json/json_objects.hxx | 4 ++-- src/stream/json/json_parser.cxx | 4 ++-- src/stream/json/json_parser.hxx | 4 ++-- src/stream/json/json_serializer.hxx | 14 ++++++------ .../json/serializers/base_serializers.hxx | 4 ++-- .../serializers/json_objects_serializer.hxx | 8 +++---- src/stream/json/serializers/serializers.hxx | 6 ++--- .../std_serializers/basic_std_serializers.hxx | 2 +- .../serializers/std_serializers/json_map.hxx | 2 +- .../std_serializers/json_unordered_map.hxx | 4 ++-- .../std_serializers/json_vector.hxx | 4 ++-- src/stream/profiler.hxx | 4 ++-- src/stream/profiler/all_events.hxx | 2 +- src/stream/profiler/event.hxx | 16 +++++++------- src/stream/profiler/event_data.hxx | 2 +- src/stream/profiler/profiler.hxx | 10 ++++----- .../profiler/profiler_event_creator.cxx | 6 ++--- .../profiler/profiler_event_creator.hxx | 2 +- src/stream/profiler/profiler_factory.cxx | 4 ++-- src/stream/profiler/profiler_factory.hxx | 2 +- .../profiler/profiler_json_serializers.hxx | 14 +++++++----- src/stream/tester/copy_move_check.hxx | 2 +- .../tester/test_suite/all_test_suite.hxx | 4 ++-- src/stream/tester/test_suite/basic_test.hxx | 4 ++-- src/stream/tester/test_suite/test_suite.cxx | 4 ++-- src/stream/tester/test_suite/test_suite.hxx | 8 +++---- src/stream/tester/tests_macros.hxx | 2 +- tests/BUILD.bazel | 2 +- tests/fmt/base_fmt_tests.hxx | 2 +- tests/fmt/complex_pattern.cxx | 6 ++--- tests/fmt/globber.cxx | 6 ++--- tests/fmt/index.cxx | 6 ++--- tests/fmt/limits.cxx | 6 ++--- tests/fmt/{.hxxift.cxx => shift.cxx} | 6 ++--- tests/fmt/specifier.cxx | 6 ++--- tests/fmt/text_properties.cxx | 6 ++--- tests/tests.cxx | 4 ++-- 130 files changed, 345 insertions(+), 341 deletions(-) rename tests/fmt/{.hxxift.cxx => shift.cxx} (99%) diff --git a/BUILD.bazel b/BUILD.bazel index 21bfc394..4e1c7c89 100644 --- a/BUILD.bazel +++ b/BUILD.bazel @@ -4,8 +4,8 @@ load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test") cc_library( name = "stream", - srcs = glob([ "src/**/*.h", "src/**/*.cpp" ]), - hdrs = glob([ "src/**/*.h" ]), + srcs = glob([ "src/**/*.cxx" ]), + hdrs = glob([ "src/**/*.hxx" ]), includes = [ "src/" ], copts = select({ "@rules_cc//cc/compiler:msvc-cl": ["/std:latest"], diff --git a/examples/hello/BUILD.bazel b/examples/hello/BUILD.bazel index e4978637..777df52e 100644 --- a/examples/hello/BUILD.bazel +++ b/examples/hello/BUILD.bazel @@ -4,7 +4,7 @@ load("@rules_cc//cc:defs.bzl", "cc_binary") cc_binary( name = "hello", - srcs = [ "main.cpp" ], + srcs = [ "main.cxx" ], includes = [ "" ], copts = select({ "@rules_cc//cc/compiler:msvc-cl": ["/std:latest"], diff --git a/examples/hello/main.cxx b/examples/hello/main.cxx index 926a845b..25610fbc 100644 --- a/examples/hello/main.cxx +++ b/examples/hello/main.cxx @@ -1,7 +1,7 @@ -#include "stream/flog.h" -#include "stream/fmt/context/formatter_executor/utility_functions.h" +#include "stream/flog.hxx" +#include "stream/fmt/context/formatter_executor/utility_functions.hxx" -#include "stream/default_logger.h" +#include "stream/default_logger.hxx" #include diff --git a/src/stream/default_logger.hxx b/src/stream/default_logger.hxx index 61f11afb..130ce007 100644 --- a/src/stream/default_logger.hxx +++ b/src/stream/default_logger.hxx @@ -1,6 +1,6 @@ #pragma once -#include "flog/frontends/xlogger.h" +#include "flog/frontends/xlogger.hxx" #ifndef STREAMFORMAT_BASE_LOGGER_NAME #undef STREAMFORMAT_BASE_LOGGER_NAME diff --git a/src/stream/flog.hxx b/src/stream/flog.hxx index 621d4d65..f6892b85 100644 --- a/src/stream/flog.hxx +++ b/src/stream/flog.hxx @@ -1,11 +1,11 @@ #pragma once -#include "flog/backends/basic_logger.h" -#include "flog/backends/logger_multi_sink_fast.h" -#include "flog/backends/logger_multi_sink_safe.h" +#include "flog/backends/basic_logger.hxx" +#include "flog/backends/logger_multi_sink_fast.hxx" +#include "flog/backends/logger_multi_sink_safe.hxx" -#include "flog/sinks/file_sink.h" +#include "flog/sinks/file_sink.hxx" -#include "flog/frontends/xlogger.h" +#include "flog/frontends/xlogger.hxx" -#include "flog/logger_factory.h" +#include "flog/logger_factory.hxx" diff --git a/src/stream/flog/backends/basic_logger.hxx b/src/stream/flog/backends/basic_logger.hxx index 758b6d1a..f1204675 100644 --- a/src/stream/flog/backends/basic_logger.hxx +++ b/src/stream/flog/backends/basic_logger.hxx @@ -1,7 +1,7 @@ #pragma once -#include "stream/flog/detail/detail.h" -#include "stream/fmt/serializers/format_chrono.h" +#include "stream/flog/detail/detail.hxx" +#include "stream/fmt/serializers/format_chrono.hxx" #include #include diff --git a/src/stream/flog/backends/logger_multi_sink.hxx b/src/stream/flog/backends/logger_multi_sink.hxx index fdf6c4c9..318f5845 100644 --- a/src/stream/flog/backends/logger_multi_sink.hxx +++ b/src/stream/flog/backends/logger_multi_sink.hxx @@ -1,7 +1,7 @@ #pragma once -#include "stream/flog/detail/detail.h" -#include "stream/flog/sinks/logger_sink.h" +#include "stream/flog/detail/detail.hxx" +#include "stream/flog/sinks/logger_sink.hxx" namespace stream::flog::detail { template diff --git a/src/stream/flog/backends/logger_multi_sink_fast.hxx b/src/stream/flog/backends/logger_multi_sink_fast.hxx index d1ea360a..e7af54c9 100644 --- a/src/stream/flog/backends/logger_multi_sink_fast.hxx +++ b/src/stream/flog/backends/logger_multi_sink_fast.hxx @@ -1,6 +1,6 @@ #pragma once -#include "logger_multi_sink.h" +#include "logger_multi_sink.hxx" namespace stream::flog::detail { template diff --git a/src/stream/flog/backends/logger_multi_sink_safe.hxx b/src/stream/flog/backends/logger_multi_sink_safe.hxx index 955f6b4c..612ceb73 100644 --- a/src/stream/flog/backends/logger_multi_sink_safe.hxx +++ b/src/stream/flog/backends/logger_multi_sink_safe.hxx @@ -1,6 +1,6 @@ #pragma once -#include "logger_multi_sink.h" +#include "logger_multi_sink.hxx" namespace stream::flog::detail { template diff --git a/src/stream/flog/detail/detail.hxx b/src/stream/flog/detail/detail.hxx index d428da5b..b78635f9 100644 --- a/src/stream/flog/detail/detail.hxx +++ b/src/stream/flog/detail/detail.hxx @@ -1,9 +1,9 @@ #pragma once -#include "stream/fmt.h" +#include "stream/fmt.hxx" -#include "stream/fmt/buf/manip.h" -#include "stream/fmt/buf/write_manip.h" +#include "stream/fmt/buf/manip.hxx" +#include "stream/fmt/buf/write_manip.hxx" namespace stream::flog { template diff --git a/src/stream/flog/frontends/xlogger.cxx b/src/stream/flog/frontends/xlogger.cxx index ac7591ba..ef2737dd 100644 --- a/src/stream/flog/frontends/xlogger.cxx +++ b/src/stream/flog/frontends/xlogger.cxx @@ -1,4 +1,4 @@ -#include "xlogger.h" +#include "xlogger.hxx" namespace stream::flog { template class detail::XLogger>; diff --git a/src/stream/flog/frontends/xlogger.hxx b/src/stream/flog/frontends/xlogger.hxx index 8b66b381..bd7d8e22 100644 --- a/src/stream/flog/frontends/xlogger.hxx +++ b/src/stream/flog/frontends/xlogger.hxx @@ -1,10 +1,10 @@ #pragma once -#include "stream/flog/detail/detail.h" -#include "stream/flog/backends/basic_logger.h" -#include "stream/flog/backends/logger_multi_sink_fast.h" -#include "stream/flog/backends/logger_multi_sink_safe.h" -#include "stream/flog/sinks/file_sink.h" +#include "stream/flog/detail/detail.hxx" +#include "stream/flog/backends/basic_logger.hxx" +#include "stream/flog/backends/logger_multi_sink_fast.hxx" +#include "stream/flog/backends/logger_multi_sink_safe.hxx" +#include "stream/flog/sinks/file_sink.hxx" namespace stream::flog { struct LogSeverity { diff --git a/src/stream/flog/logger_factory.hxx b/src/stream/flog/logger_factory.hxx index 8f3bbce6..cb313618 100644 --- a/src/stream/flog/logger_factory.hxx +++ b/src/stream/flog/logger_factory.hxx @@ -1,8 +1,8 @@ #pragma once -#include "backends/basic_logger.h" -#include "backends/logger_multi_sink_fast.h" -#include "backends/logger_multi_sink_safe.h" +#include "backends/basic_logger.hxx" +#include "backends/logger_multi_sink_fast.hxx" +#include "backends/logger_multi_sink_safe.hxx" // TODO: namespace stream::flog { diff --git a/src/stream/flog/sinks/file_sink.hxx b/src/stream/flog/sinks/file_sink.hxx index d459ee65..9d9d55f9 100644 --- a/src/stream/flog/sinks/file_sink.hxx +++ b/src/stream/flog/sinks/file_sink.hxx @@ -1,6 +1,6 @@ #pragma once -#include "logger_sink.h" +#include "logger_sink.hxx" #include #include diff --git a/src/stream/flog/sinks/logger_sink.hxx b/src/stream/flog/sinks/logger_sink.hxx index 49ed328e..f5dde5b3 100644 --- a/src/stream/flog/sinks/logger_sink.hxx +++ b/src/stream/flog/sinks/logger_sink.hxx @@ -1,6 +1,6 @@ #pragma once -#include "stream/flog/detail/detail.h" +#include "stream/flog/detail/detail.hxx" #include diff --git a/src/stream/fmt.hxx b/src/stream/fmt.hxx index efdacdf9..3eb2d6f6 100644 --- a/src/stream/fmt.hxx +++ b/src/stream/fmt.hxx @@ -1,5 +1,5 @@ #pragma once -#include "fmt/context/formatter_executor/utility_functions.h" +#include "fmt/context/formatter_executor/utility_functions.hxx" -#include "fmt/serializers/format_stdlib.h" +#include "fmt/serializers/format_stdlib.hxx" diff --git a/src/stream/fmt/buf/fmt_manip_io.hxx b/src/stream/fmt/buf/fmt_manip_io.hxx index 6ae7f848..8ab54dc5 100644 --- a/src/stream/fmt/buf/fmt_manip_io.hxx +++ b/src/stream/fmt/buf/fmt_manip_io.hxx @@ -1,8 +1,8 @@ #pragma once -#include "stream.h" -#include "manip_io.h" -#include "test_manip.h" +#include "stream.hxx" +#include "manip_io.hxx" +#include "test_manip.hxx" namespace stream::fmt::buf { template diff --git a/src/stream/fmt/buf/fmt_read_manip.hxx b/src/stream/fmt/buf/fmt_read_manip.hxx index 1b97c2b8..d619da64 100644 --- a/src/stream/fmt/buf/fmt_read_manip.hxx +++ b/src/stream/fmt/buf/fmt_read_manip.hxx @@ -1,10 +1,10 @@ #pragma once -#include "stream/fmt/buf/stream.h" -#include "stream/fmt/buf/utils/buffer_shift_manip.h" -#include "stream/fmt/buf/manip.h" -#include "stream/fmt/buf/test_manip.h" -#include "stream/fmt/buf/read_manip.h" +#include "stream/fmt/buf/stream.hxx" +#include "stream/fmt/buf/utils/buffer_shift_manip.hxx" +#include "stream/fmt/buf/manip.hxx" +#include "stream/fmt/buf/test_manip.hxx" +#include "stream/fmt/buf/read_manip.hxx" namespace stream::fmt::buf { template diff --git a/src/stream/fmt/buf/fmt_write_manip.hxx b/src/stream/fmt/buf/fmt_write_manip.hxx index 38705ba3..42c30274 100644 --- a/src/stream/fmt/buf/fmt_write_manip.hxx +++ b/src/stream/fmt/buf/fmt_write_manip.hxx @@ -1,10 +1,10 @@ #pragma once -#include "stream.h" -#include "fmt_manip_io.h" -#include "utils/buffer_shift_manip.h" -#include "manip_io.h" -#include "write_manip.h" +#include "stream.hxx" +#include "fmt_manip_io.hxx" +#include "utils/buffer_shift_manip.hxx" +#include "manip_io.hxx" +#include "write_manip.hxx" #include diff --git a/src/stream/fmt/buf/manip.hxx b/src/stream/fmt/buf/manip.hxx index 25046ebc..fcfb392d 100644 --- a/src/stream/fmt/buf/manip.hxx +++ b/src/stream/fmt/buf/manip.hxx @@ -1,6 +1,6 @@ #pragma once -#include "stream.h" +#include "stream.hxx" namespace stream::fmt::buf { template diff --git a/src/stream/fmt/buf/manip_io.hxx b/src/stream/fmt/buf/manip_io.hxx index 616308e9..8e3b3ccd 100644 --- a/src/stream/fmt/buf/manip_io.hxx +++ b/src/stream/fmt/buf/manip_io.hxx @@ -1,10 +1,10 @@ #pragma once -#include "stream.h" -#include "streamio.h" -#include "manip.h" +#include "stream.hxx" +#include "streamio.hxx" +#include "manip.hxx" -#include "streamio_manager/basic_streamio_manager.h" +#include "streamio_manager/basic_streamio_manager.hxx" namespace stream::fmt::buf { template diff --git a/src/stream/fmt/buf/read_manip.hxx b/src/stream/fmt/buf/read_manip.hxx index f8883131..83ed2487 100644 --- a/src/stream/fmt/buf/read_manip.hxx +++ b/src/stream/fmt/buf/read_manip.hxx @@ -1,7 +1,7 @@ #pragma once -#include "stream/fmt/buf/stream.h" -#include "stream/fmt/buf/manip.h" +#include "stream/fmt/buf/stream.hxx" +#include "stream/fmt/buf/manip.hxx" namespace stream::fmt::buf { template diff --git a/src/stream/fmt/buf/stream.hxx b/src/stream/fmt/buf/stream.hxx index f6fa247c..872f0040 100644 --- a/src/stream/fmt/buf/stream.hxx +++ b/src/stream/fmt/buf/stream.hxx @@ -1,6 +1,6 @@ #pragma once -#include "stream/fmt/detail/prelude.h" +#include "stream/fmt/detail/prelude.hxx" namespace stream::fmt::buf { template diff --git a/src/stream/fmt/buf/streamio.hxx b/src/stream/fmt/buf/streamio.hxx index f9a5704c..72c2e780 100644 --- a/src/stream/fmt/buf/streamio.hxx +++ b/src/stream/fmt/buf/streamio.hxx @@ -1,9 +1,9 @@ #pragma once -#include "stream.h" -#include "manip.h" +#include "stream.hxx" +#include "manip.hxx" -#include "streamio_manager/basic_streamio_manager.h" +#include "streamio_manager/basic_streamio_manager.hxx" namespace stream::fmt::buf { template diff --git a/src/stream/fmt/buf/streamio_manager/basic_streamio_manager.hxx b/src/stream/fmt/buf/streamio_manager/basic_streamio_manager.hxx index b65d1e14..3be85b78 100644 --- a/src/stream/fmt/buf/streamio_manager/basic_streamio_manager.hxx +++ b/src/stream/fmt/buf/streamio_manager/basic_streamio_manager.hxx @@ -1,7 +1,7 @@ #pragma once -#include "stream/fmt/detail/prelude.h" -#include "stream/fmt/buf/stream.h" +#include "stream/fmt/detail/prelude.hxx" +#include "stream/fmt/buf/stream.hxx" namespace stream::fmt::buf { template diff --git a/src/stream/fmt/buf/streamio_manager/dynamic_streamio_manager.hxx b/src/stream/fmt/buf/streamio_manager/dynamic_streamio_manager.hxx index fbfdc552..5a553109 100644 --- a/src/stream/fmt/buf/streamio_manager/dynamic_streamio_manager.hxx +++ b/src/stream/fmt/buf/streamio_manager/dynamic_streamio_manager.hxx @@ -1,6 +1,6 @@ #pragma once -#include "basic_streamio_manager.h" +#include "basic_streamio_manager.hxx" #include #include diff --git a/src/stream/fmt/buf/streamio_manager/given_streamio_manager.hxx b/src/stream/fmt/buf/streamio_manager/given_streamio_manager.hxx index 12eb06e9..c02dce2d 100644 --- a/src/stream/fmt/buf/streamio_manager/given_streamio_manager.hxx +++ b/src/stream/fmt/buf/streamio_manager/given_streamio_manager.hxx @@ -1,6 +1,6 @@ #pragma once -#include "basic_streamio_manager.h" +#include "basic_streamio_manager.hxx" namespace stream::fmt::buf { template diff --git a/src/stream/fmt/buf/streamio_manager/static_streamio_manager.hxx b/src/stream/fmt/buf/streamio_manager/static_streamio_manager.hxx index 0b2cc15f..bbaa4f3c 100644 --- a/src/stream/fmt/buf/streamio_manager/static_streamio_manager.hxx +++ b/src/stream/fmt/buf/streamio_manager/static_streamio_manager.hxx @@ -1,6 +1,6 @@ #pragma once -#include "basic_streamio_manager.h" +#include "basic_streamio_manager.hxx" namespace stream::fmt::buf { template diff --git a/src/stream/fmt/buf/test_manip.hxx b/src/stream/fmt/buf/test_manip.hxx index dd561a58..76564564 100644 --- a/src/stream/fmt/buf/test_manip.hxx +++ b/src/stream/fmt/buf/test_manip.hxx @@ -1,7 +1,7 @@ #pragma once -#include "stream/fmt/buf/stream.h" -#include "stream/fmt/buf/manip.h" +#include "stream/fmt/buf/stream.hxx" +#include "stream/fmt/buf/manip.hxx" namespace stream::fmt::buf { template diff --git a/src/stream/fmt/buf/utils/buffer_globber_manip.hxx b/src/stream/fmt/buf/utils/buffer_globber_manip.hxx index cd1f2704..78374e96 100644 --- a/src/stream/fmt/buf/utils/buffer_globber_manip.hxx +++ b/src/stream/fmt/buf/utils/buffer_globber_manip.hxx @@ -1,7 +1,7 @@ #pragma once -#include "stream/fmt/buf/stream.h" -#include "stream/fmt/buf/manip.h" +#include "stream/fmt/buf/stream.hxx" +#include "stream/fmt/buf/manip.hxx" namespace stream::fmt::buf { template diff --git a/src/stream/fmt/buf/utils/buffer_shift_manip.hxx b/src/stream/fmt/buf/utils/buffer_shift_manip.hxx index 4db0830b..63ac8a97 100644 --- a/src/stream/fmt/buf/utils/buffer_shift_manip.hxx +++ b/src/stream/fmt/buf/utils/buffer_shift_manip.hxx @@ -1,7 +1,7 @@ #pragma once -#include "stream/fmt/buf/stream.h" -#include "stream/fmt/buf/manip_io.h" +#include "stream/fmt/buf/stream.hxx" +#include "stream/fmt/buf/manip_io.hxx" namespace stream::fmt::buf { template diff --git a/src/stream/fmt/buf/utils/buffer_utils.hxx b/src/stream/fmt/buf/utils/buffer_utils.hxx index 5887ae79..e59397c2 100644 --- a/src/stream/fmt/buf/utils/buffer_utils.hxx +++ b/src/stream/fmt/buf/utils/buffer_utils.hxx @@ -1,14 +1,14 @@ #pragma once -#include "stream/fmt/buf/stream.h" -#include "stream/fmt/buf/manip_io.h" -#include "stream/fmt/buf/test_manip.h" -#include "stream/fmt/buf/write_manip.h" -#include "stream/fmt/buf/read_manip.h" - -#include "stream/fmt/buf/streamio_manager/dynamic_streamio_manager.h" -#include "stream/fmt/buf/streamio_manager/given_streamio_manager.h" -#include "stream/fmt/buf/streamio_manager/static_streamio_manager.h" +#include "stream/fmt/buf/stream.hxx" +#include "stream/fmt/buf/manip_io.hxx" +#include "stream/fmt/buf/test_manip.hxx" +#include "stream/fmt/buf/write_manip.hxx" +#include "stream/fmt/buf/read_manip.hxx" + +#include "stream/fmt/buf/streamio_manager/dynamic_streamio_manager.hxx" +#include "stream/fmt/buf/streamio_manager/given_streamio_manager.hxx" +#include "stream/fmt/buf/streamio_manager/static_streamio_manager.hxx" namespace stream::fmt::buf { template diff --git a/src/stream/fmt/buf/write_manip.hxx b/src/stream/fmt/buf/write_manip.hxx index b6723411..62630197 100644 --- a/src/stream/fmt/buf/write_manip.hxx +++ b/src/stream/fmt/buf/write_manip.hxx @@ -1,9 +1,9 @@ #pragma once -#include "stream.h" -#include "manip.h" -#include "test_manip.h" -#include "manip_io.h" +#include "stream.hxx" +#include "manip.hxx" +#include "test_manip.hxx" +#include "manip_io.hxx" #include #include diff --git a/src/stream/fmt/context/basic_context/basic_args_interface.hxx b/src/stream/fmt/context/basic_context/basic_args_interface.hxx index 9f3aec56..9337fc19 100644 --- a/src/stream/fmt/context/basic_context/basic_args_interface.hxx +++ b/src/stream/fmt/context/basic_context/basic_args_interface.hxx @@ -1,8 +1,8 @@ #pragma once -#include "stream/fmt/detail/convert_traits.h" -#include "stream/fmt/detail/prelude.h" -#include "stream/fmt/buf/stream.h" +#include "stream/fmt/detail/convert_traits.hxx" +#include "stream/fmt/detail/prelude.hxx" +#include "stream/fmt/buf/stream.hxx" #include #include diff --git a/src/stream/fmt/context/basic_context/basic_context.hxx b/src/stream/fmt/context/basic_context/basic_context.hxx index a140887b..15fc80c2 100644 --- a/src/stream/fmt/context/basic_context/basic_context.hxx +++ b/src/stream/fmt/context/basic_context/basic_context.hxx @@ -1,18 +1,18 @@ #pragma once -#include "stream/fmt/detail/convert_traits.h" -#include "stream/fmt/detail/prelude.h" -#include "stream/fmt/detail/specifiers.h" +#include "stream/fmt/detail/convert_traits.hxx" +#include "stream/fmt/detail/prelude.hxx" +#include "stream/fmt/detail/specifiers.hxx" -#include "stream/fmt/buf/stream.h" -#include "stream/fmt/buf/manip.h" -#include "stream/fmt/buf/test_manip.h" -#include "stream/fmt/buf/read_manip.h" +#include "stream/fmt/buf/stream.hxx" +#include "stream/fmt/buf/manip.hxx" +#include "stream/fmt/buf/test_manip.hxx" +#include "stream/fmt/buf/read_manip.hxx" -#include "basic_args_interface.h" +#include "basic_args_interface.hxx" -#include "text_properties_executor.h" -#include "text_properties_manager.h" +#include "text_properties_executor.hxx" +#include "text_properties_manager.hxx" namespace stream::fmt::context { template @@ -147,4 +147,4 @@ namespace stream::fmt::context { } } // namespace stream::fmt::context -#include "basic_context_parse_impl.h" +#include "basic_context_parse_impl.hxx" diff --git a/src/stream/fmt/context/basic_context/basic_context_parse_impl.hxx b/src/stream/fmt/context/basic_context/basic_context_parse_impl.hxx index 9b7fca25..78057fa1 100644 --- a/src/stream/fmt/context/basic_context/basic_context_parse_impl.hxx +++ b/src/stream/fmt/context/basic_context/basic_context_parse_impl.hxx @@ -1,13 +1,13 @@ #pragma once -#include "basic_context.h" - -#include "stream/fmt/buf/manip.h" -#include "stream/fmt/buf/test_manip.h" -#include "stream/fmt/buf/write_manip.h" -#include "stream/fmt/buf/read_manip.h" -#include "stream/fmt/buf/fmt_manip_io.h" -#include "stream/fmt/buf/fmt_read_manip.h" +#include "basic_context.hxx" + +#include "stream/fmt/buf/manip.hxx" +#include "stream/fmt/buf/test_manip.hxx" +#include "stream/fmt/buf/write_manip.hxx" +#include "stream/fmt/buf/read_manip.hxx" +#include "stream/fmt/buf/fmt_manip_io.hxx" +#include "stream/fmt/buf/fmt_read_manip.hxx" namespace stream::fmt::context { template diff --git a/src/stream/fmt/context/basic_context/text_properties_executor.hxx b/src/stream/fmt/context/basic_context/text_properties_executor.hxx index 2f2f8741..a6ee8ad8 100644 --- a/src/stream/fmt/context/basic_context/text_properties_executor.hxx +++ b/src/stream/fmt/context/basic_context/text_properties_executor.hxx @@ -1,7 +1,7 @@ #pragma once -#include "stream/fmt/detail/prelude.h" -#include "stream/fmt/text_properties/text_properties.h" +#include "stream/fmt/detail/prelude.hxx" +#include "stream/fmt/text_properties/text_properties.hxx" namespace stream::fmt::detail { class ITextPropertiesExecutor { diff --git a/src/stream/fmt/context/basic_context/text_properties_manager.cxx b/src/stream/fmt/context/basic_context/text_properties_manager.cxx index 20ab8632..ddd7e405 100644 --- a/src/stream/fmt/context/basic_context/text_properties_manager.cxx +++ b/src/stream/fmt/context/basic_context/text_properties_manager.cxx @@ -1,4 +1,4 @@ -#include "text_properties_manager.h" +#include "text_properties_manager.hxx" namespace stream::fmt::detail { [[nodiscard]] std::expected TextPropertiesapplyManager::reload_color_fg(const TextProperties::TextColor::ColorFG& target) { diff --git a/src/stream/fmt/context/basic_context/text_properties_manager.hxx b/src/stream/fmt/context/basic_context/text_properties_manager.hxx index d3774563..950e6e4c 100644 --- a/src/stream/fmt/context/basic_context/text_properties_manager.hxx +++ b/src/stream/fmt/context/basic_context/text_properties_manager.hxx @@ -1,11 +1,11 @@ #pragma once -#include "stream/fmt/detail/prelude.h" -#include "text_properties_executor.h" -#include "basic_args_interface.h" -#include "stream/fmt/buf/stream.h" -#include "stream/fmt/buf/test_manip.h" -#include "stream/fmt/buf/utils/buffer_utils.h" +#include "stream/fmt/detail/prelude.hxx" +#include "text_properties_executor.hxx" +#include "basic_args_interface.hxx" +#include "stream/fmt/buf/stream.hxx" +#include "stream/fmt/buf/test_manip.hxx" +#include "stream/fmt/buf/utils/buffer_utils.hxx" namespace stream::fmt::detail { class TextPropertiesapplyManager { @@ -207,4 +207,4 @@ namespace stream::fmt::detail { } } // namespace stream::fmt::detail -#include "text_properties_manager_impl.h" +#include "text_properties_manager_impl.hxx" diff --git a/src/stream/fmt/context/basic_context/text_properties_manager_impl.hxx b/src/stream/fmt/context/basic_context/text_properties_manager_impl.hxx index 78240298..bed27981 100644 --- a/src/stream/fmt/context/basic_context/text_properties_manager_impl.hxx +++ b/src/stream/fmt/context/basic_context/text_properties_manager_impl.hxx @@ -1,12 +1,12 @@ #pragma once -#include "text_properties_manager.h" +#include "text_properties_manager.hxx" -#include "stream/fmt/buf/manip.h" -#include "stream/fmt/buf/manip_io.h" -#include "stream/fmt/buf/test_manip.h" -#include "stream/fmt/buf/fmt_manip_io.h" -#include "stream/fmt/buf/utils/buffer_utils.h" +#include "stream/fmt/buf/manip.hxx" +#include "stream/fmt/buf/manip_io.hxx" +#include "stream/fmt/buf/test_manip.hxx" +#include "stream/fmt/buf/fmt_manip_io.hxx" +#include "stream/fmt/buf/utils/buffer_utils.hxx" namespace stream::fmt::detail { template diff --git a/src/stream/fmt/context/formatter_executor/basic_formatter_executor.hxx b/src/stream/fmt/context/formatter_executor/basic_formatter_executor.hxx index 22052281..65a0e179 100644 --- a/src/stream/fmt/context/formatter_executor/basic_formatter_executor.hxx +++ b/src/stream/fmt/context/formatter_executor/basic_formatter_executor.hxx @@ -1,16 +1,16 @@ #pragma once -#include "stream/fmt/context/basic_context/basic_context.h" +#include "stream/fmt/context/basic_context/basic_context.hxx" -#include "stream/fmt/buf/fmt_manip_io.h" -#include "stream/fmt/buf/write_manip.h" +#include "stream/fmt/buf/fmt_manip_io.hxx" +#include "stream/fmt/buf/write_manip.hxx" -#include "formatter_type.h" -#include "index_args.h" -#include "named_args.h" -#include "std_enumerable.h" +#include "formatter_type.hxx" +#include "index_args.hxx" +#include "named_args.hxx" +#include "std_enumerable.hxx" -#include "formatter_args.h" +#include "formatter_args.hxx" namespace stream::fmt::context { enum class EndOfStringCharMode { @@ -110,5 +110,5 @@ namespace stream::fmt::context { } } // namespace stream::fmt::context -#include "format_basics_impl.h" -#include "format_text_properties_impl.h" +#include "format_basics_impl.hxx" +#include "format_text_properties_impl.hxx" diff --git a/src/stream/fmt/context/formatter_executor/format_basics_impl.hxx b/src/stream/fmt/context/formatter_executor/format_basics_impl.hxx index 55ceb1cd..547c7764 100644 --- a/src/stream/fmt/context/formatter_executor/format_basics_impl.hxx +++ b/src/stream/fmt/context/formatter_executor/format_basics_impl.hxx @@ -1,8 +1,8 @@ #pragma once -#include "basic_formatter_executor.h" +#include "basic_formatter_executor.hxx" -#include "stream/fmt/buf/fmt_write_manip.h" +#include "stream/fmt/buf/fmt_write_manip.hxx" namespace stream::fmt { //---------------------------------------------// diff --git a/src/stream/fmt/context/formatter_executor/format_text_properties_impl.hxx b/src/stream/fmt/context/formatter_executor/format_text_properties_impl.hxx index c7ca38d0..6d6f1666 100644 --- a/src/stream/fmt/context/formatter_executor/format_text_properties_impl.hxx +++ b/src/stream/fmt/context/formatter_executor/format_text_properties_impl.hxx @@ -1,6 +1,6 @@ #pragma once -#include "basic_formatter_executor.h" +#include "basic_formatter_executor.hxx" namespace stream::fmt { //------------------------------------------// diff --git a/src/stream/fmt/context/formatter_executor/formatter_args.hxx b/src/stream/fmt/context/formatter_executor/formatter_args.hxx index b1a2a472..6825afe9 100644 --- a/src/stream/fmt/context/formatter_executor/formatter_args.hxx +++ b/src/stream/fmt/context/formatter_executor/formatter_args.hxx @@ -1,10 +1,10 @@ #pragma once -#include "stream/fmt/context/basic_context/basic_args_interface.h" -#include "stream/fmt/detail/prelude.h" +#include "stream/fmt/context/basic_context/basic_args_interface.hxx" +#include "stream/fmt/detail/prelude.hxx" -#include "formatter_type.h" +#include "formatter_type.hxx" namespace stream::fmt::detail { /****************************/ diff --git a/src/stream/fmt/context/formatter_executor/formatter_text_properties_executor/formatter_text_properties_executor.hxx b/src/stream/fmt/context/formatter_executor/formatter_text_properties_executor/formatter_text_properties_executor.hxx index 52c52e72..cf31eb35 100644 --- a/src/stream/fmt/context/formatter_executor/formatter_text_properties_executor/formatter_text_properties_executor.hxx +++ b/src/stream/fmt/context/formatter_executor/formatter_text_properties_executor/formatter_text_properties_executor.hxx @@ -1,8 +1,8 @@ #pragma once -#include "stream/fmt/context/basic_context/text_properties_executor.h" -#include "stream/fmt/buf/fmt_manip_io.h" -#include "stream/fmt/context/formatter_executor/basic_formatter_executor.h" +#include "stream/fmt/context/basic_context/text_properties_executor.hxx" +#include "stream/fmt/buf/fmt_manip_io.hxx" +#include "stream/fmt/context/formatter_executor/basic_formatter_executor.hxx" namespace stream::fmt::detail { template diff --git a/src/stream/fmt/context/formatter_executor/formatter_text_properties_executor/formatter_text_properties_executor_ansi.hxx b/src/stream/fmt/context/formatter_executor/formatter_text_properties_executor/formatter_text_properties_executor_ansi.hxx index f634af5c..54a2b933 100644 --- a/src/stream/fmt/context/formatter_executor/formatter_text_properties_executor/formatter_text_properties_executor_ansi.hxx +++ b/src/stream/fmt/context/formatter_executor/formatter_text_properties_executor/formatter_text_properties_executor_ansi.hxx @@ -1,7 +1,7 @@ #pragma once -#include "formatter_text_properties_executor.h" -#include "stream/fmt/detail/indent_handlers.h" +#include "formatter_text_properties_executor.hxx" +#include "stream/fmt/detail/indent_handlers.hxx" namespace stream::fmt::detail { template diff --git a/src/stream/fmt/context/formatter_executor/formatter_type.hxx b/src/stream/fmt/context/formatter_executor/formatter_type.hxx index 35f15d74..d611864c 100644 --- a/src/stream/fmt/context/formatter_executor/formatter_type.hxx +++ b/src/stream/fmt/context/formatter_executor/formatter_type.hxx @@ -1,6 +1,6 @@ #pragma once -#include "stream/fmt/detail/prelude.h" +#include "stream/fmt/detail/prelude.hxx" #define STREAMFORMAT_FORMATTER_DECLARED namespace stream::fmt { diff --git a/src/stream/fmt/context/formatter_executor/index_args.hxx b/src/stream/fmt/context/formatter_executor/index_args.hxx index f3f8a055..12fd6875 100644 --- a/src/stream/fmt/context/formatter_executor/index_args.hxx +++ b/src/stream/fmt/context/formatter_executor/index_args.hxx @@ -1,6 +1,6 @@ #pragma once -#include "formatter_type.h" +#include "formatter_type.hxx" namespace stream::fmt { template diff --git a/src/stream/fmt/context/formatter_executor/named_args.hxx b/src/stream/fmt/context/formatter_executor/named_args.hxx index 7d14d48b..9d4e0458 100644 --- a/src/stream/fmt/context/formatter_executor/named_args.hxx +++ b/src/stream/fmt/context/formatter_executor/named_args.hxx @@ -1,6 +1,6 @@ #pragma once -#include "formatter_type.h" +#include "formatter_type.hxx" namespace stream::fmt { /////---------- string_view NamedArgs Do not allocate memory (Best) ----------///// diff --git a/src/stream/fmt/context/formatter_executor/std_enumerable.hxx b/src/stream/fmt/context/formatter_executor/std_enumerable.hxx index ec66e9da..b5194290 100644 --- a/src/stream/fmt/context/formatter_executor/std_enumerable.hxx +++ b/src/stream/fmt/context/formatter_executor/std_enumerable.hxx @@ -1,8 +1,8 @@ #pragma once -#include "formatter_type.h" -#include "stream/fmt/context/utils/context_functions.h" -#include "stream/fmt/detail/prelude.h" +#include "formatter_type.hxx" +#include "stream/fmt/context/utils/context_functions.hxx" +#include "stream/fmt/detail/prelude.hxx" #include #include diff --git a/src/stream/fmt/context/formatter_executor/utility_functions.hxx b/src/stream/fmt/context/formatter_executor/utility_functions.hxx index a4e77a9b..f3419aca 100644 --- a/src/stream/fmt/context/formatter_executor/utility_functions.hxx +++ b/src/stream/fmt/context/formatter_executor/utility_functions.hxx @@ -1,12 +1,12 @@ #pragma once -#include "basic_formatter_executor.h" +#include "basic_formatter_executor.hxx" -#include "stream/fmt/buf/streamio_manager/dynamic_streamio_manager.h" -#include "stream/fmt/buf/streamio_manager/given_streamio_manager.h" -#include "stream/fmt/buf/streamio_manager/static_streamio_manager.h" +#include "stream/fmt/buf/streamio_manager/dynamic_streamio_manager.hxx" +#include "stream/fmt/buf/streamio_manager/given_streamio_manager.hxx" +#include "stream/fmt/buf/streamio_manager/static_streamio_manager.hxx" -#include "formatter_text_properties_executor/formatter_text_properties_executor_ansi.h" +#include "formatter_text_properties_executor/formatter_text_properties_executor_ansi.hxx" #include diff --git a/src/stream/fmt/context/parser_executor/basic_parser_executor.hxx b/src/stream/fmt/context/parser_executor/basic_parser_executor.hxx index 3e71acdf..46340832 100644 --- a/src/stream/fmt/context/parser_executor/basic_parser_executor.hxx +++ b/src/stream/fmt/context/parser_executor/basic_parser_executor.hxx @@ -1,16 +1,16 @@ #pragma once -#include "stream/fmt/buf/stream.h" -#include "stream/fmt/buf/manip.h" -#include "stream/fmt/buf/test_manip.h" +#include "stream/fmt/buf/stream.hxx" +#include "stream/fmt/buf/manip.hxx" +#include "stream/fmt/buf/test_manip.hxx" -#include "stream/fmt/context/basic_context/basic_context.h" +#include "stream/fmt/context/basic_context/basic_context.hxx" -#include "parser_type.h" +#include "parser_type.hxx" -#include "parser_args.h" +#include "parser_args.hxx" -#include "parser_text_properties_executor/parser_text_properties_executor.h" +#include "parser_text_properties_executor/parser_text_properties_executor.hxx" namespace stream::fmt::context { template @@ -89,5 +89,5 @@ namespace stream::fmt::context { } } // namespace stream::fmt::context -#include "parse_basics_impl.h" -#include "parse_text_properties_impl.h" +#include "parse_basics_impl.hxx" +#include "parse_text_properties_impl.hxx" diff --git a/src/stream/fmt/context/parser_executor/parse_basics_impl.hxx b/src/stream/fmt/context/parser_executor/parse_basics_impl.hxx index eeb7a7f9..70b6f4ae 100644 --- a/src/stream/fmt/context/parser_executor/parse_basics_impl.hxx +++ b/src/stream/fmt/context/parser_executor/parse_basics_impl.hxx @@ -1,7 +1,7 @@ #pragma once -#include "basic_parser_executor.h" -#include "stream/fmt/buf/fmt_read_manip.h" +#include "basic_parser_executor.hxx" +#include "stream/fmt/buf/fmt_read_manip.hxx" namespace stream::fmt { //----------------------------------------------// diff --git a/src/stream/fmt/context/parser_executor/parse_text_properties_impl.hxx b/src/stream/fmt/context/parser_executor/parse_text_properties_impl.hxx index 867e77b5..6272e3f7 100644 --- a/src/stream/fmt/context/parser_executor/parse_text_properties_impl.hxx +++ b/src/stream/fmt/context/parser_executor/parse_text_properties_impl.hxx @@ -1,6 +1,6 @@ #pragma once -#include "basic_parser_executor.h" +#include "basic_parser_executor.hxx" namespace stream::fmt { //------------------------------------------// diff --git a/src/stream/fmt/context/parser_executor/parser_args.hxx b/src/stream/fmt/context/parser_executor/parser_args.hxx index ff97329b..40dec187 100644 --- a/src/stream/fmt/context/parser_executor/parser_args.hxx +++ b/src/stream/fmt/context/parser_executor/parser_args.hxx @@ -1,7 +1,7 @@ #pragma once -#include "stream/fmt/context/basic_context/basic_args_interface.h" -#include "stream/fmt/detail/prelude.h" +#include "stream/fmt/context/basic_context/basic_args_interface.hxx" +#include "stream/fmt/detail/prelude.hxx" namespace stream::fmt::detail { /****************************/ diff --git a/src/stream/fmt/context/parser_executor/parser_text_properties_executor/parser_text_properties_executor.hxx b/src/stream/fmt/context/parser_executor/parser_text_properties_executor/parser_text_properties_executor.hxx index bba4bc69..7a33ddf4 100644 --- a/src/stream/fmt/context/parser_executor/parser_text_properties_executor/parser_text_properties_executor.hxx +++ b/src/stream/fmt/context/parser_executor/parser_text_properties_executor/parser_text_properties_executor.hxx @@ -1,8 +1,8 @@ #pragma once -#include "stream/fmt/context/basic_context/text_properties_executor.h" -#include "stream/fmt/detail/prelude.h" -#include "stream/fmt/context/parser_executor/basic_parser_executor.h" +#include "stream/fmt/context/basic_context/text_properties_executor.hxx" +#include "stream/fmt/detail/prelude.hxx" +#include "stream/fmt/context/parser_executor/basic_parser_executor.hxx" namespace stream::fmt::detail { template diff --git a/src/stream/fmt/context/parser_executor/parser_text_properties_executor/parser_text_properties_executor_ansi.hxx b/src/stream/fmt/context/parser_executor/parser_text_properties_executor/parser_text_properties_executor_ansi.hxx index 245e606b..de071b57 100644 --- a/src/stream/fmt/context/parser_executor/parser_text_properties_executor/parser_text_properties_executor_ansi.hxx +++ b/src/stream/fmt/context/parser_executor/parser_text_properties_executor/parser_text_properties_executor_ansi.hxx @@ -1,6 +1,6 @@ #pragma once -#include "parser_text_properties_executor.h" +#include "parser_text_properties_executor.hxx" namespace stream::fmt::detail { template diff --git a/src/stream/fmt/context/parser_executor/parser_type.hxx b/src/stream/fmt/context/parser_executor/parser_type.hxx index 5c451366..70ea460a 100644 --- a/src/stream/fmt/context/parser_executor/parser_type.hxx +++ b/src/stream/fmt/context/parser_executor/parser_type.hxx @@ -1,6 +1,6 @@ #pragma once -#include "stream/fmt/detail/prelude.h" +#include "stream/fmt/detail/prelude.hxx" #define STREAMFORMAT_PARSER_DECLARED namespace stream::fmt { diff --git a/src/stream/fmt/context/parser_executor/utility_functions.hxx b/src/stream/fmt/context/parser_executor/utility_functions.hxx index 1f97ec7c..4421c02b 100644 --- a/src/stream/fmt/context/parser_executor/utility_functions.hxx +++ b/src/stream/fmt/context/parser_executor/utility_functions.hxx @@ -1,11 +1,11 @@ #pragma once -#include "basic_parser_executor.h" +#include "basic_parser_executor.hxx" -#include "stream/fmt/buf/streamio_manager/given_streamio_manager.h" -#include "stream/fmt/buf/streamio_manager/static_streamio_manager.h" +#include "stream/fmt/buf/streamio_manager/given_streamio_manager.hxx" +#include "stream/fmt/buf/streamio_manager/static_streamio_manager.hxx" -#include "parser_text_properties_executor/parser_text_properties_executor_ansi.h" +#include "parser_text_properties_executor/parser_text_properties_executor_ansi.hxx" namespace stream::fmt { template diff --git a/src/stream/fmt/context/utils/context_functions.hxx b/src/stream/fmt/context/utils/context_functions.hxx index fc84f838..33170f81 100644 --- a/src/stream/fmt/context/utils/context_functions.hxx +++ b/src/stream/fmt/context/utils/context_functions.hxx @@ -1,6 +1,6 @@ #pragma once -#include "stream/fmt/detail/specifiers.h" +#include "stream/fmt/detail/specifiers.hxx" namespace stream::fmt::detail { template diff --git a/src/stream/fmt/detail/convert_traits.hxx b/src/stream/fmt/detail/convert_traits.hxx index 1f73ab28..f560549a 100644 --- a/src/stream/fmt/detail/convert_traits.hxx +++ b/src/stream/fmt/detail/convert_traits.hxx @@ -1,6 +1,6 @@ #pragma once -#include "prelude.h" +#include "prelude.hxx" namespace stream::fmt::detail { template diff --git a/src/stream/fmt/detail/fmt_result.hxx b/src/stream/fmt/detail/fmt_result.hxx index a410b945..8b5f0bc1 100644 --- a/src/stream/fmt/detail/fmt_result.hxx +++ b/src/stream/fmt/detail/fmt_result.hxx @@ -1,6 +1,6 @@ #pragma once -#include "stream/core/prelude.h" +#include "stream/core/prelude.hxx" namespace stream::fmt { enum class FMTResult { diff --git a/src/stream/fmt/detail/indent_handlers.hxx b/src/stream/fmt/detail/indent_handlers.hxx index eeab721e..217ad045 100644 --- a/src/stream/fmt/detail/indent_handlers.hxx +++ b/src/stream/fmt/detail/indent_handlers.hxx @@ -1,7 +1,7 @@ #pragma once -#include "stream/fmt/detail/prelude.h" -#include "stream/fmt/buf/fmt_manip_io.h" +#include "stream/fmt/detail/prelude.hxx" +#include "stream/fmt/buf/fmt_manip_io.hxx" namespace stream::fmt::detail { template diff --git a/src/stream/fmt/detail/prelude.hxx b/src/stream/fmt/detail/prelude.hxx index 43b146f3..e93c207b 100644 --- a/src/stream/fmt/detail/prelude.hxx +++ b/src/stream/fmt/detail/prelude.hxx @@ -1,8 +1,8 @@ #pragma once -#include "stream/core/prelude.h" -#include "types_traits.h" -#include "fmt_result.h" +#include "stream/core/prelude.hxx" +#include "types_traits.hxx" +#include "fmt_result.hxx" #define UNKOWN_TYPE_MESSAGE diff --git a/src/stream/fmt/detail/specifiers.hxx b/src/stream/fmt/detail/specifiers.hxx index b909806d..82c263c5 100644 --- a/src/stream/fmt/detail/specifiers.hxx +++ b/src/stream/fmt/detail/specifiers.hxx @@ -1,7 +1,7 @@ #pragma once -#include "stream/core/prelude.h" -#include "stream/core/prelude.h" +#include "stream/core/prelude.hxx" +#include "stream/core/prelude.hxx" #include #include diff --git a/src/stream/fmt/detail/types_traits.hxx b/src/stream/fmt/detail/types_traits.hxx index 5ea339f2..5bab1ed3 100644 --- a/src/stream/fmt/detail/types_traits.hxx +++ b/src/stream/fmt/detail/types_traits.hxx @@ -1,6 +1,6 @@ #pragma once -#include "stream/core/prelude.h" +#include "stream/core/prelude.hxx" #include diff --git a/src/stream/fmt/serializers/compilation_data.hxx b/src/stream/fmt/serializers/compilation_data.hxx index 73422323..e13f9cb9 100644 --- a/src/stream/fmt/serializers/compilation_data.hxx +++ b/src/stream/fmt/serializers/compilation_data.hxx @@ -1,7 +1,7 @@ #pragma once -#include "stream/core/prelude.h" -#include "stream/flog.h" +#include "stream/core/prelude.hxx" +#include "stream/flog.hxx" namespace stream::fmt::detail { struct FileLocation { diff --git a/src/stream/fmt/serializers/format_chrono.hxx b/src/stream/fmt/serializers/format_chrono.hxx index ed781ba1..7d391269 100644 --- a/src/stream/fmt/serializers/format_chrono.hxx +++ b/src/stream/fmt/serializers/format_chrono.hxx @@ -1,11 +1,11 @@ #pragma once -#include "stream/fmt/buf/test_manip.h" -#include "stream/fmt/buf/write_manip.h" -#include "stream/fmt/buf/read_manip.h" -#include "stream/fmt/buf/fmt_write_manip.h" +#include "stream/fmt/buf/test_manip.hxx" +#include "stream/fmt/buf/write_manip.hxx" +#include "stream/fmt/buf/read_manip.hxx" +#include "stream/fmt/buf/fmt_write_manip.hxx" -#include "stream/fmt/context/formatter_executor/basic_formatter_executor.h" +#include "stream/fmt/context/formatter_executor/basic_formatter_executor.hxx" #include diff --git a/src/stream/fmt/serializers/format_stdlib.hxx b/src/stream/fmt/serializers/format_stdlib.hxx index 9ee49160..484f1b4b 100644 --- a/src/stream/fmt/serializers/format_stdlib.hxx +++ b/src/stream/fmt/serializers/format_stdlib.hxx @@ -1,6 +1,6 @@ #pragma once -#include "stream/fmt/context/formatter_executor/basic_formatter_executor.h" +#include "stream/fmt/context/formatter_executor/basic_formatter_executor.hxx" #include #include diff --git a/src/stream/fmt/serializers/parse_chrono.hxx b/src/stream/fmt/serializers/parse_chrono.hxx index 4f7d8e60..d88280e3 100644 --- a/src/stream/fmt/serializers/parse_chrono.hxx +++ b/src/stream/fmt/serializers/parse_chrono.hxx @@ -1,7 +1,7 @@ #pragma once #include -#include "stream/fmt/context/parser_executor/basic_parser_executor.h" +#include "stream/fmt/context/parser_executor/basic_parser_executor.hxx" namespace stream::fmt::detail {} diff --git a/src/stream/fmt/serializers/parse_stdlib.hxx b/src/stream/fmt/serializers/parse_stdlib.hxx index 3bd27579..25c5fae5 100644 --- a/src/stream/fmt/serializers/parse_stdlib.hxx +++ b/src/stream/fmt/serializers/parse_stdlib.hxx @@ -1,6 +1,6 @@ #pragma once -#include "stream/fmt/context/parser_executor/basic_parser_executor.h" +#include "stream/fmt/context/parser_executor/basic_parser_executor.hxx" #include #include diff --git a/src/stream/fmt/serializers/std_container/array.hxx b/src/stream/fmt/serializers/std_container/array.hxx index e590546d..28feec7c 100644 --- a/src/stream/fmt/serializers/std_container/array.hxx +++ b/src/stream/fmt/serializers/std_container/array.hxx @@ -1,7 +1,7 @@ #pragma once -#include "stream/fmt/context/formatter_executor/formatter_type.h" -#include "stream/fmt/context/formatter_executor/std_enumerable.h" +#include "stream/fmt/context/formatter_executor/formatter_type.hxx" +#include "stream/fmt/context/formatter_executor/std_enumerable.hxx" #include diff --git a/src/stream/fmt/serializers/std_container/deque.hxx b/src/stream/fmt/serializers/std_container/deque.hxx index 5f037951..cac3d2ec 100644 --- a/src/stream/fmt/serializers/std_container/deque.hxx +++ b/src/stream/fmt/serializers/std_container/deque.hxx @@ -1,7 +1,7 @@ #pragma once -#include "stream/fmt/context/formatter_executor/formatter_type.h" -#include "stream/fmt/context/formatter_executor/std_enumerable.h" +#include "stream/fmt/context/formatter_executor/formatter_type.hxx" +#include "stream/fmt/context/formatter_executor/std_enumerable.hxx" #include diff --git a/src/stream/fmt/serializers/std_container/forward_list.hxx b/src/stream/fmt/serializers/std_container/forward_list.hxx index b585e574..44b4e0e3 100644 --- a/src/stream/fmt/serializers/std_container/forward_list.hxx +++ b/src/stream/fmt/serializers/std_container/forward_list.hxx @@ -1,7 +1,7 @@ #pragma once -#include "stream/fmt/context/formatter_executor/formatter_type.h" -#include "stream/fmt/context/formatter_executor/std_enumerable.h" +#include "stream/fmt/context/formatter_executor/formatter_type.hxx" +#include "stream/fmt/context/formatter_executor/std_enumerable.hxx" #include diff --git a/src/stream/fmt/serializers/std_container/list.hxx b/src/stream/fmt/serializers/std_container/list.hxx index d52deef1..e1d8526f 100644 --- a/src/stream/fmt/serializers/std_container/list.hxx +++ b/src/stream/fmt/serializers/std_container/list.hxx @@ -1,7 +1,7 @@ #pragma once -#include "stream/fmt/context/formatter_executor/formatter_type.h" -#include "stream/fmt/context/formatter_executor/std_enumerable.h" +#include "stream/fmt/context/formatter_executor/formatter_type.hxx" +#include "stream/fmt/context/formatter_executor/std_enumerable.hxx" #include diff --git a/src/stream/fmt/serializers/std_container/map.hxx b/src/stream/fmt/serializers/std_container/map.hxx index 57c725c6..5bccca33 100644 --- a/src/stream/fmt/serializers/std_container/map.hxx +++ b/src/stream/fmt/serializers/std_container/map.hxx @@ -1,8 +1,8 @@ #pragma once #include -#include "stream/fmt/context/formatter_executor/formatter_type.h" -#include "stream/fmt/context/formatter_executor/std_enumerable.h" +#include "stream/fmt/context/formatter_executor/formatter_type.hxx" +#include "stream/fmt/context/formatter_executor/std_enumerable.hxx" #include "tuple.h" diff --git a/src/stream/fmt/serializers/std_container/queue.hxx b/src/stream/fmt/serializers/std_container/queue.hxx index 4f746ea3..1e430001 100644 --- a/src/stream/fmt/serializers/std_container/queue.hxx +++ b/src/stream/fmt/serializers/std_container/queue.hxx @@ -1,7 +1,7 @@ #pragma once #include -#include "stream/fmt/context/formatter_executor/formatter_type.h" +#include "stream/fmt/context/formatter_executor/formatter_type.hxx" namespace stream::fmt { template diff --git a/src/stream/fmt/serializers/std_container/set.hxx b/src/stream/fmt/serializers/std_container/set.hxx index b4abbb15..49fc6ab6 100644 --- a/src/stream/fmt/serializers/std_container/set.hxx +++ b/src/stream/fmt/serializers/std_container/set.hxx @@ -1,7 +1,7 @@ #pragma once -#include "stream/fmt/context/formatter_executor/formatter_type.h" -#include "stream/fmt/context/formatter_executor/std_enumerable.h" +#include "stream/fmt/context/formatter_executor/formatter_type.hxx" +#include "stream/fmt/context/formatter_executor/std_enumerable.hxx" #include diff --git a/src/stream/fmt/serializers/std_container/stack.hxx b/src/stream/fmt/serializers/std_container/stack.hxx index f36e8079..8e030508 100644 --- a/src/stream/fmt/serializers/std_container/stack.hxx +++ b/src/stream/fmt/serializers/std_container/stack.hxx @@ -1,7 +1,7 @@ #pragma once #include -#include "stream/fmt/context/formatter_executor/formatter_type.h" +#include "stream/fmt/context/formatter_executor/formatter_type.hxx" namespace stream::fmt { /* diff --git a/src/stream/fmt/serializers/std_container/tuple.hxx b/src/stream/fmt/serializers/std_container/tuple.hxx index ccfd26a6..a8a03394 100644 --- a/src/stream/fmt/serializers/std_container/tuple.hxx +++ b/src/stream/fmt/serializers/std_container/tuple.hxx @@ -2,7 +2,7 @@ #include #include -#include "stream/fmt/context/formatter_executor/formatter_type.h" +#include "stream/fmt/context/formatter_executor/formatter_type.hxx" namespace stream::fmt::tuple_detail { template diff --git a/src/stream/fmt/serializers/std_container/unordered_map.hxx b/src/stream/fmt/serializers/std_container/unordered_map.hxx index 49ab72c3..db93431c 100644 --- a/src/stream/fmt/serializers/std_container/unordered_map.hxx +++ b/src/stream/fmt/serializers/std_container/unordered_map.hxx @@ -1,7 +1,7 @@ #pragma once -#include "stream/fmt/context/formatter_executor/formatter_type.h" -#include "stream/fmt/context/formatter_executor/std_enumerable.h" +#include "stream/fmt/context/formatter_executor/formatter_type.hxx" +#include "stream/fmt/context/formatter_executor/std_enumerable.hxx" #include #include "tuple.h" diff --git a/src/stream/fmt/serializers/std_container/unordered_set.hxx b/src/stream/fmt/serializers/std_container/unordered_set.hxx index 9aa223a3..e1d2024f 100644 --- a/src/stream/fmt/serializers/std_container/unordered_set.hxx +++ b/src/stream/fmt/serializers/std_container/unordered_set.hxx @@ -1,7 +1,7 @@ #pragma once -#include "stream/fmt/context/formatter_executor/formatter_type.h" -#include "stream/fmt/context/formatter_executor/std_enumerable.h" +#include "stream/fmt/context/formatter_executor/formatter_type.hxx" +#include "stream/fmt/context/formatter_executor/std_enumerable.hxx" #include diff --git a/src/stream/fmt/serializers/std_container/vector.hxx b/src/stream/fmt/serializers/std_container/vector.hxx index a38ecc32..cb0ade55 100644 --- a/src/stream/fmt/serializers/std_container/vector.hxx +++ b/src/stream/fmt/serializers/std_container/vector.hxx @@ -1,7 +1,7 @@ #pragma once -#include "stream/fmt/context/formatter_executor/formatter_type.h" -#include "stream/fmt/context/formatter_executor/std_enumerable.h" +#include "stream/fmt/context/formatter_executor/formatter_type.hxx" +#include "stream/fmt/context/formatter_executor/std_enumerable.hxx" #include diff --git a/src/stream/fmt/text_properties/base_text_properties.hxx b/src/stream/fmt/text_properties/base_text_properties.hxx index 37d47c82..fe97a3cf 100644 --- a/src/stream/fmt/text_properties/base_text_properties.hxx +++ b/src/stream/fmt/text_properties/base_text_properties.hxx @@ -1,6 +1,6 @@ #pragma once -#include "stream/core/prelude.h" +#include "stream/core/prelude.hxx" // According to : https://en.wikipedia.org/wiki/ANSI_escape_code diff --git a/src/stream/fmt/text_properties/text_properties.hxx b/src/stream/fmt/text_properties/text_properties.hxx index 64da2cb3..7401317e 100644 --- a/src/stream/fmt/text_properties/text_properties.hxx +++ b/src/stream/fmt/text_properties/text_properties.hxx @@ -1,8 +1,8 @@ #pragma once -#include "text_properties_color.h" -#include "text_properties_front.h" -#include "text_properties_style.h" +#include "text_properties_color.hxx" +#include "text_properties_front.hxx" +#include "text_properties_style.hxx" namespace stream::fmt::detail { struct TextProperties::Properties { diff --git a/src/stream/fmt/text_properties/text_properties_color.hxx b/src/stream/fmt/text_properties/text_properties_color.hxx index 17be7d65..08e6e46e 100644 --- a/src/stream/fmt/text_properties/text_properties_color.hxx +++ b/src/stream/fmt/text_properties/text_properties_color.hxx @@ -1,6 +1,6 @@ #pragma once -#include "base_text_properties.h" +#include "base_text_properties.hxx" namespace stream::fmt::detail { struct TextProperties::TextColor { diff --git a/src/stream/fmt/text_properties/text_properties_front.hxx b/src/stream/fmt/text_properties/text_properties_front.hxx index 240d523b..28f0991f 100644 --- a/src/stream/fmt/text_properties/text_properties_front.hxx +++ b/src/stream/fmt/text_properties/text_properties_front.hxx @@ -1,6 +1,6 @@ #pragma once -#include "base_text_properties.h" +#include "base_text_properties.hxx" namespace stream::fmt::detail { struct TextProperties::TextFront { diff --git a/src/stream/fmt/text_properties/text_properties_style.hxx b/src/stream/fmt/text_properties/text_properties_style.hxx index f12133ed..a37636f3 100644 --- a/src/stream/fmt/text_properties/text_properties_style.hxx +++ b/src/stream/fmt/text_properties/text_properties_style.hxx @@ -1,7 +1,7 @@ #pragma once -#include "base_text_properties.h" -#include "text_properties_color.h" +#include "base_text_properties.hxx" +#include "text_properties_color.hxx" namespace stream::fmt::detail { struct TextProperties::TextStyle { diff --git a/src/stream/json.hxx b/src/stream/json.hxx index 3e4c6d08..7e09551f 100644 --- a/src/stream/json.hxx +++ b/src/stream/json.hxx @@ -1,7 +1,7 @@ #pragma once -#include "json/json_factory.h" -#include "json/json_objects.h" +#include "json/json_factory.hxx" +#include "json/json_objects.hxx" -#include "json/json_serializer.h" -#include "json/serializers/serializers.h" +#include "json/json_serializer.hxx" +#include "json/serializers/serializers.hxx" diff --git a/src/stream/json/json_factory.hxx b/src/stream/json/json_factory.hxx index 52f8a81b..70e849f5 100644 --- a/src/stream/json/json_factory.hxx +++ b/src/stream/json/json_factory.hxx @@ -1,12 +1,12 @@ #pragma once -#include "json_formatter_impl.h" -#include "json_formatter.h" -#include "json_objects.h" -#include "json_parser.h" -#include "json_serializer.h" -#include "serializers/json_objects_serializer.h" -#include "serializers/serializers.h" +#include "json_formatter_impl.hxx" +#include "json_formatter.hxx" +#include "json_objects.hxx" +#include "json_parser.hxx" +#include "json_serializer.hxx" +#include "serializers/json_objects_serializer.hxx" +#include "serializers/serializers.hxx" #include #include @@ -21,7 +21,7 @@ namespace stream::json { }; } // namespace stream::json -#include "stream/fmt.h" +#include "stream/fmt.hxx" namespace stream::fmt { template struct FormatterType { @@ -33,8 +33,8 @@ namespace stream::fmt { #include #include -#include "stream//fmt/buf/streamio_manager/dynamic_streamio_manager.h" -#include "serializers/json_objects_serializer.h" +#include "stream//fmt/buf/streamio_manager/dynamic_streamio_manager.hxx" +#include "serializers/json_objects_serializer.hxx" namespace stream::json { template T JsonFactory::FromPath(const std::filesystem::path& path) { diff --git a/src/stream/json/json_formatter.hxx b/src/stream/json/json_formatter.hxx index 6c06859a..dff2fba3 100644 --- a/src/stream/json/json_formatter.hxx +++ b/src/stream/json/json_formatter.hxx @@ -1,8 +1,8 @@ #pragma once -#include "json_objects.h" -#include "stream/fmt/buf/streamio.h" -#include "stream/fmt/buf/manip_io.h" +#include "json_objects.hxx" +#include "stream/fmt/buf/streamio.hxx" +#include "stream/fmt/buf/manip_io.hxx" namespace stream::json::detail { class JsonFormatter { diff --git a/src/stream/json/json_formatter_impl.hxx b/src/stream/json/json_formatter_impl.hxx index e8367489..feca8de5 100644 --- a/src/stream/json/json_formatter_impl.hxx +++ b/src/stream/json/json_formatter_impl.hxx @@ -1,6 +1,6 @@ -#include "json_formatter.h" +#include "json_formatter.hxx" -#include "json_serializer.h" +#include "json_serializer.hxx" namespace stream::json::detail { inline JsonFormatter::StructIntermediate::StructIntermediate(JsonFormatter& formatter) : Formatter(formatter), Idx(0) { diff --git a/src/stream/json/json_objects.cxx b/src/stream/json/json_objects.cxx index 81586434..be14c878 100644 --- a/src/stream/json/json_objects.cxx +++ b/src/stream/json/json_objects.cxx @@ -1,5 +1,5 @@ -#include "json_objects.h" -#include "serializers/json_objects_serializer.h" +#include "json_objects.hxx" +#include "serializers/json_objects_serializer.hxx" namespace stream::json { void JsonStringObject::ParserExecute(detail::JsonParser& parser) { diff --git a/src/stream/json/json_objects.hxx b/src/stream/json/json_objects.hxx index 6ff68113..7a921cc4 100644 --- a/src/stream/json/json_objects.hxx +++ b/src/stream/json/json_objects.hxx @@ -1,7 +1,7 @@ #pragma once -#include "detail.h" -#include "stream/fmt.h" +#include "detail.hxx" +#include "stream/fmt.hxx" #include #include diff --git a/src/stream/json/json_parser.cxx b/src/stream/json/json_parser.cxx index 1361ce5d..a38c8d9d 100644 --- a/src/stream/json/json_parser.cxx +++ b/src/stream/json/json_parser.cxx @@ -1,10 +1,10 @@ -#include "detail.h" +#include "detail.hxx" #include #include #include -#include "json_serializer.h" +#include "json_serializer.hxx" namespace stream::json::detail { void JsonParser::Intermediate::parse(detail::JsonParser& parser) { diff --git a/src/stream/json/json_parser.hxx b/src/stream/json/json_parser.hxx index 8fd9a0de..91b0ffe8 100644 --- a/src/stream/json/json_parser.hxx +++ b/src/stream/json/json_parser.hxx @@ -1,8 +1,8 @@ #pragma once -#include "stream/fmt/buf/stream.h" +#include "stream/fmt/buf/stream.hxx" -#include "json_objects.h" +#include "json_objects.hxx" namespace stream::json::detail { class JsonParser { diff --git a/src/stream/json/json_serializer.hxx b/src/stream/json/json_serializer.hxx index c759e757..92ea4a04 100644 --- a/src/stream/json/json_serializer.hxx +++ b/src/stream/json/json_serializer.hxx @@ -1,12 +1,12 @@ #pragma once -#include "json_formatter.h" -#include "json_parser.h" +#include "json_formatter.hxx" +#include "json_parser.hxx" -#include "stream/fmt.h" -#include "stream/fmt/buf/read_manip.h" -#include "stream/fmt/buf/write_manip.h" -#include "stream/fmt/buf/utils/buffer_utils.h" +#include "stream/fmt.hxx" +#include "stream/fmt/buf/read_manip.hxx" +#include "stream/fmt/buf/write_manip.hxx" +#include "stream/fmt/buf/utils/buffer_utils.hxx" #include #include @@ -292,7 +292,7 @@ namespace stream::json { }; } // namespace stream::json -#include "stream/fmt.h" +#include "stream/fmt.hxx" namespace stream::fmt { #ifdef STREAMFORMAT_FORMATTER_DECLARED template diff --git a/src/stream/json/serializers/base_serializers.hxx b/src/stream/json/serializers/base_serializers.hxx index 8fe3c161..6827e7d6 100644 --- a/src/stream/json/serializers/base_serializers.hxx +++ b/src/stream/json/serializers/base_serializers.hxx @@ -1,7 +1,7 @@ #pragma once -#include "../json_objects.h" -#include "../json_serializer.h" +#include "../json_objects.hxx" +#include "../json_serializer.hxx" #include diff --git a/src/stream/json/serializers/json_objects_serializer.hxx b/src/stream/json/serializers/json_objects_serializer.hxx index 69b65faf..a9ce8ac0 100644 --- a/src/stream/json/serializers/json_objects_serializer.hxx +++ b/src/stream/json/serializers/json_objects_serializer.hxx @@ -1,10 +1,10 @@ #pragma once -#include "../json_objects.h" -#include "../json_serializer.h" +#include "../json_objects.hxx" +#include "../json_serializer.hxx" -#include "std_serializers/json_unordered_map.h" -#include "std_serializers/json_vector.h" +#include "std_serializers/json_unordered_map.hxx" +#include "std_serializers/json_vector.hxx" #include diff --git a/src/stream/json/serializers/serializers.hxx b/src/stream/json/serializers/serializers.hxx index 1c4e5668..20426d0e 100644 --- a/src/stream/json/serializers/serializers.hxx +++ b/src/stream/json/serializers/serializers.hxx @@ -1,5 +1,5 @@ #pragma once -#include "base_serializers.h" -#include "json_objects_serializer.h" -#include "std_serializers/basic_std_serializers.h" +#include "base_serializers.hxx" +#include "json_objects_serializer.hxx" +#include "std_serializers/basic_std_serializers.hxx" diff --git a/src/stream/json/serializers/std_serializers/basic_std_serializers.hxx b/src/stream/json/serializers/std_serializers/basic_std_serializers.hxx index e6827444..80f5b93f 100644 --- a/src/stream/json/serializers/std_serializers/basic_std_serializers.hxx +++ b/src/stream/json/serializers/std_serializers/basic_std_serializers.hxx @@ -1,6 +1,6 @@ #pragma once -#include "stream/json/json_serializer.h" +#include "stream/json/json_serializer.hxx" #include diff --git a/src/stream/json/serializers/std_serializers/json_map.hxx b/src/stream/json/serializers/std_serializers/json_map.hxx index 8c436e76..500a3a10 100644 --- a/src/stream/json/serializers/std_serializers/json_map.hxx +++ b/src/stream/json/serializers/std_serializers/json_map.hxx @@ -1,6 +1,6 @@ #pragma once -#include "stream/json/json_serializer.h" +#include "stream/json/json_serializer.hxx" #include diff --git a/src/stream/json/serializers/std_serializers/json_unordered_map.hxx b/src/stream/json/serializers/std_serializers/json_unordered_map.hxx index ce3ddeee..83a88f70 100644 --- a/src/stream/json/serializers/std_serializers/json_unordered_map.hxx +++ b/src/stream/json/serializers/std_serializers/json_unordered_map.hxx @@ -1,7 +1,7 @@ #pragma once -#include "stream/json/json_objects.h" -#include "stream/json/json_serializer.h" +#include "stream/json/json_objects.hxx" +#include "stream/json/json_serializer.hxx" #include diff --git a/src/stream/json/serializers/std_serializers/json_vector.hxx b/src/stream/json/serializers/std_serializers/json_vector.hxx index 4ee5c363..f8f7b48f 100644 --- a/src/stream/json/serializers/std_serializers/json_vector.hxx +++ b/src/stream/json/serializers/std_serializers/json_vector.hxx @@ -1,7 +1,7 @@ #pragma once -#include "stream/json/json_objects.h" -#include "stream/json/json_serializer.h" +#include "stream/json/json_objects.hxx" +#include "stream/json/json_serializer.hxx" #include diff --git a/src/stream/profiler.hxx b/src/stream/profiler.hxx index 32e2ce5f..a2714559 100644 --- a/src/stream/profiler.hxx +++ b/src/stream/profiler.hxx @@ -1,4 +1,4 @@ #pragma once -#include "profiler/profiler.h" -#include "profiler/profiler_factory.h" +#include "profiler/profiler.hxx" +#include "profiler/profiler_factory.hxx" diff --git a/src/stream/profiler/all_events.hxx b/src/stream/profiler/all_events.hxx index 6a3386cd..976a8a5d 100644 --- a/src/stream/profiler/all_events.hxx +++ b/src/stream/profiler/all_events.hxx @@ -1,6 +1,6 @@ #pragma once -#include "event.h" +#include "event.hxx" namespace stream::profiler { class DurationEvent : public Event { diff --git a/src/stream/profiler/event.hxx b/src/stream/profiler/event.hxx index a0fe3306..d52de44c 100644 --- a/src/stream/profiler/event.hxx +++ b/src/stream/profiler/event.hxx @@ -1,9 +1,9 @@ #pragma once -#include "detail.h" -#include "event_data.h" -#include "stream/core/prelude.h" -#include "stream/fmt.h" +#include "detail.hxx" +#include "event_data.hxx" +#include "stream/core/prelude.hxx" +#include "stream/fmt.hxx" #include #include @@ -13,7 +13,7 @@ // https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview namespace stream::profiler { - int GetPid(); + int get_pid(); enum class EventType : char { Unknow = '.', @@ -55,7 +55,7 @@ namespace stream::profiler { id(0), time_of_event(profiler::get_nanoseconds()), duration(0), - pid(GetPid()), + pid(get_pid()), tid(std::hash{}(std::this_thread::get_id())), data(nullptr) {} @@ -66,7 +66,7 @@ namespace stream::profiler { id(0), time_of_event(profiler::get_nanoseconds()), duration(0), - pid(GetPid()), + pid(get_pid()), tid(std::hash{}(std::this_thread::get_id())), data(data) {} @@ -77,7 +77,7 @@ namespace stream::profiler { id(0), time_of_event(profiler::get_nanoseconds()), duration(0), - pid(GetPid()), + pid(get_pid()), tid(std::hash{}(std::this_thread::get_id())), data(data) {} diff --git a/src/stream/profiler/event_data.hxx b/src/stream/profiler/event_data.hxx index 96fc861b..2cfd9425 100644 --- a/src/stream/profiler/event_data.hxx +++ b/src/stream/profiler/event_data.hxx @@ -1,6 +1,6 @@ #pragma once -#include "stream/json.h" +#include "stream/json.hxx" namespace stream::profiler { class EventData { diff --git a/src/stream/profiler/profiler.hxx b/src/stream/profiler/profiler.hxx index 20df09f8..a8dd21c9 100644 --- a/src/stream/profiler/profiler.hxx +++ b/src/stream/profiler/profiler.hxx @@ -1,11 +1,11 @@ #pragma once -#include "stream/core/prelude.h" -#include "stream/flog.h" +#include "stream/core/prelude.hxx" +#include "stream/flog.hxx" -#include "all_events.h" -#include "event.h" -#include "profiler_event_creator.h" +#include "all_events.hxx" +#include "event.hxx" +#include "profiler_event_creator.hxx" namespace stream::profiler { class Profiler { diff --git a/src/stream/profiler/profiler_event_creator.cxx b/src/stream/profiler/profiler_event_creator.cxx index f117168f..60fc9b56 100644 --- a/src/stream/profiler/profiler_event_creator.cxx +++ b/src/stream/profiler/profiler_event_creator.cxx @@ -1,5 +1,5 @@ -#include "profiler_event_creator.h" -#include "profiler.h" +#include "profiler_event_creator.hxx" +#include "profiler.hxx" namespace stream::profiler { ScopeProfile::~ScopeProfile() { @@ -14,7 +14,7 @@ namespace stream::profiler { else if (millis.count() > 5.0) profiler_.get_logger().trace("{} : {} ms", info.name, millis.count()); else - profiler_.get_logger().trace("{} : {} us", info.name, us); + profiler_.get_logger().trace("{} : {} us", info.name, us.count()); profiler_.add_event(*this); } diff --git a/src/stream/profiler/profiler_event_creator.hxx b/src/stream/profiler/profiler_event_creator.hxx index 5799325f..ba88984f 100644 --- a/src/stream/profiler/profiler_event_creator.hxx +++ b/src/stream/profiler/profiler_event_creator.hxx @@ -1,6 +1,6 @@ #pragma once -#include "all_events.h" +#include "all_events.hxx" namespace stream::profiler { class Profiler; diff --git a/src/stream/profiler/profiler_factory.cxx b/src/stream/profiler/profiler_factory.cxx index 830d7792..a1ae82df 100644 --- a/src/stream/profiler/profiler_factory.cxx +++ b/src/stream/profiler/profiler_factory.cxx @@ -1,5 +1,5 @@ -#include "profiler_factory.h" -#include "profiler_json_serializers.h" +#include "profiler_factory.hxx" +#include "profiler_json_serializers.hxx" #include diff --git a/src/stream/profiler/profiler_factory.hxx b/src/stream/profiler/profiler_factory.hxx index a58697d4..b89b63f1 100644 --- a/src/stream/profiler/profiler_factory.hxx +++ b/src/stream/profiler/profiler_factory.hxx @@ -1,6 +1,6 @@ #pragma once -#include "profiler.h" +#include "profiler.hxx" #include diff --git a/src/stream/profiler/profiler_json_serializers.hxx b/src/stream/profiler/profiler_json_serializers.hxx index 91de2082..74d84f79 100644 --- a/src/stream/profiler/profiler_json_serializers.hxx +++ b/src/stream/profiler/profiler_json_serializers.hxx @@ -1,7 +1,7 @@ #pragma once -#include "profiler_factory.h" -#include "stream/json.h" +#include "profiler_factory.hxx" +#include "stream/json.hxx" namespace stream::json { template <> @@ -49,8 +49,8 @@ namespace stream::json { intermediate.format("ph", t.type); intermediate.format("pid", t.pid); intermediate.format("tid", t.tid); - intermediate.format("ts", t.time_of_event); - intermediate.format("dur", t.duration); + intermediate.format("ts", t.time_of_event.count()); + intermediate.format("dur", t.duration.count()); intermediate.format("id", t.id); if (t.data != nullptr) intermediate.format("args", *t.data); } @@ -62,8 +62,12 @@ namespace stream::json { intermediate.parse("ph", t.type); intermediate.parse("pid", t.pid); intermediate.parse("tid", t.tid); - intermediate.parse("ts", t.time_of_event); + std::uint64_t time_of_event = 0; + intermediate.parse("ts", time_of_event); + t.time_of_event = std::chrono::microseconds(time_of_event); + std::uint64_t duration = 0; intermediate.parse("dur", t.duration); + t.duration = std::chrono::microseconds(duration); intermediate.parse("id", t.id); intermediate.parse("args", *t.data); } diff --git a/src/stream/tester/copy_move_check.hxx b/src/stream/tester/copy_move_check.hxx index ee27c72d..7e6709a8 100644 --- a/src/stream/tester/copy_move_check.hxx +++ b/src/stream/tester/copy_move_check.hxx @@ -1,6 +1,6 @@ #pragma once -#include "stream/flog.h" +#include "stream/flog.hxx" namespace stream::tester { class CopyMoveCheck { diff --git a/src/stream/tester/test_suite/all_test_suite.hxx b/src/stream/tester/test_suite/all_test_suite.hxx index f3e01254..58627b70 100644 --- a/src/stream/tester/test_suite/all_test_suite.hxx +++ b/src/stream/tester/test_suite/all_test_suite.hxx @@ -1,2 +1,2 @@ -#include "basic_test.h" -#include "test_suite.h" +#include "basic_test.hxx" +#include "test_suite.hxx" diff --git a/src/stream/tester/test_suite/basic_test.hxx b/src/stream/tester/test_suite/basic_test.hxx index 74aaf6d7..2bb60025 100644 --- a/src/stream/tester/test_suite/basic_test.hxx +++ b/src/stream/tester/test_suite/basic_test.hxx @@ -1,8 +1,8 @@ #pragma once -#include "test_suite.h" +#include "test_suite.hxx" -#include "stream/core/prelude.h" +#include "stream/core/prelude.hxx" namespace stream::tester::detail { struct TestFunction : public Test { diff --git a/src/stream/tester/test_suite/test_suite.cxx b/src/stream/tester/test_suite/test_suite.cxx index fcbc09ab..3d38fb6d 100644 --- a/src/stream/tester/test_suite/test_suite.cxx +++ b/src/stream/tester/test_suite/test_suite.cxx @@ -1,8 +1,8 @@ -#include "test_suite.h" +#include "test_suite.hxx" #include -#include "stream/profiler.h" +#include "stream/profiler.hxx" namespace stream::tester { bool TestSuitesManager::exec_all_test_suites() { diff --git a/src/stream/tester/test_suite/test_suite.hxx b/src/stream/tester/test_suite/test_suite.hxx index f05a4a38..d389878b 100644 --- a/src/stream/tester/test_suite/test_suite.hxx +++ b/src/stream/tester/test_suite/test_suite.hxx @@ -1,10 +1,10 @@ #pragma once -#include "stream/flog.h" -#include "stream/fmt.h" -#include "stream/profiler.h" +#include "stream/flog.hxx" +#include "stream/fmt.hxx" +#include "stream/profiler.hxx" -#include "stream/fmt/serializers/compilation_data.h" +#include "stream/fmt/serializers/compilation_data.hxx" #include #include diff --git a/src/stream/tester/tests_macros.hxx b/src/stream/tester/tests_macros.hxx index 53e9102a..315dddfe 100644 --- a/src/stream/tester/tests_macros.hxx +++ b/src/stream/tester/tests_macros.hxx @@ -1,6 +1,6 @@ #pragma once -#include "stream/flog.h" +#include "stream/flog.hxx" #define STREAMFORMAT_TEST_TRACE(...) stream::Test::TestCore::get_logger().trace(__VA_ARGS__) #define STREAMFORMAT_TEST_INFO(...) stream::Test::TestCore::get_logger().info(__VA_ARGS__) diff --git a/tests/BUILD.bazel b/tests/BUILD.bazel index cf938353..bb2a239d 100644 --- a/tests/BUILD.bazel +++ b/tests/BUILD.bazel @@ -4,7 +4,7 @@ load("@rules_cc//cc:defs.bzl", "cc_test") cc_test( name = "units", - srcs = [ "tests.cpp" ] + glob([ "fmt/*.h", "fmt/*.cpp" ]), + srcs = [ "tests.cxx" ] + glob([ "fmt/*.hxx", "fmt/*.cxx" ]), copts = select({ "@rules_cc//cc/compiler:msvc-cl": ["/std:latest"], "//conditions:default": [ diff --git a/tests/fmt/base_fmt_tests.hxx b/tests/fmt/base_fmt_tests.hxx index 9327aecc..ffeeb494 100644 --- a/tests/fmt/base_fmt_tests.hxx +++ b/tests/fmt/base_fmt_tests.hxx @@ -1,5 +1,5 @@ #pragma once -#include "stream/tester/test_suite/all_test_suite.h" +#include "stream/tester/test_suite/all_test_suite.hxx" inline SFT_TEST_SUITE(FMT); diff --git a/tests/fmt/complex_pattern.cxx b/tests/fmt/complex_pattern.cxx index 267f6dd2..04a1a573 100644 --- a/tests/fmt/complex_pattern.cxx +++ b/tests/fmt/complex_pattern.cxx @@ -1,7 +1,7 @@ -#include "stream/fmt.h" -#include "stream/tester/test_suite/all_test_suite.h" +#include "stream/fmt.hxx" +#include "stream/tester/test_suite/all_test_suite.hxx" -#include "base_fmt_tests.h" +#include "base_fmt_tests.hxx" // NOLINTBEGIN(misc-const-correctness) // NOLINTBEGIN(readability-magic-numbers) diff --git a/tests/fmt/globber.cxx b/tests/fmt/globber.cxx index cc2d675b..906b3e1a 100644 --- a/tests/fmt/globber.cxx +++ b/tests/fmt/globber.cxx @@ -1,8 +1,8 @@ -#include "base_fmt_tests.h" +#include "base_fmt_tests.hxx" -#include "stream/fmt/context/parser_executor/utility_functions.h" +#include "stream/fmt/context/parser_executor/utility_functions.hxx" -#include "stream/fmt/buf/utils/buffer_globber_manip.h" +#include "stream/fmt/buf/utils/buffer_globber_manip.hxx" // NOLINTBEGIN(misc-const-correctness) // NOLINTBEGIN(readability-magic-numbers) diff --git a/tests/fmt/index.cxx b/tests/fmt/index.cxx index 612e657b..515951ba 100644 --- a/tests/fmt/index.cxx +++ b/tests/fmt/index.cxx @@ -1,7 +1,7 @@ -#include "stream/fmt.h" -#include "stream/tester/test_suite/all_test_suite.h" +#include "stream/fmt.hxx" +#include "stream/tester/test_suite/all_test_suite.hxx" -#include "base_fmt_tests.h" +#include "base_fmt_tests.hxx" // NOLINTBEGIN(misc-const-correctness) // NOLINTBEGIN(readability-magic-numbers) diff --git a/tests/fmt/limits.cxx b/tests/fmt/limits.cxx index cbe7f07b..0f52ebe7 100644 --- a/tests/fmt/limits.cxx +++ b/tests/fmt/limits.cxx @@ -1,7 +1,7 @@ -#include "stream/fmt.h" -#include "stream/tester/test_suite/all_test_suite.h" +#include "stream/fmt.hxx" +#include "stream/tester/test_suite/all_test_suite.hxx" -#include "base_fmt_tests.h" +#include "base_fmt_tests.hxx" // NOLINTBEGIN(misc-const-correctness) // NOLINTBEGIN(readability-magic-numbers) diff --git a/tests/fmt/.hxxift.cxx b/tests/fmt/shift.cxx similarity index 99% rename from tests/fmt/.hxxift.cxx rename to tests/fmt/shift.cxx index c0237021..82b6e191 100644 --- a/tests/fmt/.hxxift.cxx +++ b/tests/fmt/shift.cxx @@ -1,7 +1,7 @@ -#include "stream/fmt.h" -#include "stream/tester/test_suite/all_test_suite.h" +#include "stream/fmt.hxx" +#include "stream/tester/test_suite/all_test_suite.hxx" -#include "base_fmt_tests.h" +#include "base_fmt_tests.hxx" // NOLINTBEGIN(misc-const-correctness) // NOLINTBEGIN(readability-magic-numbers) diff --git a/tests/fmt/specifier.cxx b/tests/fmt/specifier.cxx index ce3083f1..154f49fe 100644 --- a/tests/fmt/specifier.cxx +++ b/tests/fmt/specifier.cxx @@ -1,7 +1,7 @@ -#include "stream/fmt.h" -#include "stream/tester/test_suite/all_test_suite.h" +#include "stream/fmt.hxx" +#include "stream/tester/test_suite/all_test_suite.hxx" -#include "base_fmt_tests.h" +#include "base_fmt_tests.hxx" // NOLINTBEGIN(misc-const-correctness) // NOLINTBEGIN(readability-magic-numbers) diff --git a/tests/fmt/text_properties.cxx b/tests/fmt/text_properties.cxx index cd22f769..9b4d45b4 100644 --- a/tests/fmt/text_properties.cxx +++ b/tests/fmt/text_properties.cxx @@ -1,7 +1,7 @@ -#include "stream/fmt.h" -#include "stream/tester/test_suite/all_test_suite.h" +#include "stream/fmt.hxx" +#include "stream/tester/test_suite/all_test_suite.hxx" -#include "base_fmt_tests.h" +#include "base_fmt_tests.hxx" // NOLINTBEGIN(misc-const-correctness) // NOLINTBEGIN(readability-magic-numbers) diff --git a/tests/tests.cxx b/tests/tests.cxx index f146fcc5..70bb2135 100644 --- a/tests/tests.cxx +++ b/tests/tests.cxx @@ -1,6 +1,6 @@ -#include "stream/tester/test_suite/all_test_suite.h" -#include "stream/default_logger.h" +#include "stream/tester/test_suite/all_test_suite.hxx" +#include "stream/default_logger.hxx" int main() { stream::tester::TestSuitesManager::verbose = false; From d61fdae390d04f768db5306e731f62072c70e697 Mon Sep 17 00:00:00 2001 From: Sacha Bellier Date: Sun, 23 Mar 2025 19:25:56 +0100 Subject: [PATCH 24/42] feat: save fix `clang-tidy` --- conf | 2 +- .../context/basic_context/text_properties_manager.cxx | 2 ++ src/stream/fmt/context/parser_executor/parser_args.hxx | 1 + src/stream/fmt/serializers/std_container/map.hxx | 2 +- src/stream/fmt/serializers/std_container/tuple.hxx | 10 +++++----- .../fmt/serializers/std_container/unordered_map.hxx | 4 ++-- src/stream/fmt/serializers/std_container/vector.hxx | 2 +- src/stream/profiler/profiler_event_creator.cxx | 4 ++++ 8 files changed, 17 insertions(+), 10 deletions(-) diff --git a/conf b/conf index ba69cca0..e0a36c8f 160000 --- a/conf +++ b/conf @@ -1 +1 @@ -Subproject commit ba69cca07f908ff389da36bc07140ffe14643665 +Subproject commit e0a36c8f57c036f7b0dd6be93a285c73ddb4ead0 diff --git a/src/stream/fmt/context/basic_context/text_properties_manager.cxx b/src/stream/fmt/context/basic_context/text_properties_manager.cxx index ddd7e405..185649eb 100644 --- a/src/stream/fmt/context/basic_context/text_properties_manager.cxx +++ b/src/stream/fmt/context/basic_context/text_properties_manager.cxx @@ -53,6 +53,7 @@ namespace stream::fmt::detail { return {}; } + // NOLINTBEGIN(readability-function-cognitive-complexity) [[nodiscard]] std::expected TextPropertiesapplyManager::reload_style(const TextProperties::TextStyle::Style& target) { if (target.intensity != current_context_properties_.style.intensity) { SF_TRY(apply_style(target.intensity)); @@ -119,6 +120,7 @@ namespace stream::fmt::detail { } return {}; } + // NOLINTEND(readability-function-cognitive-complexity) [[nodiscard]] std::expected TextPropertiesapplyManager::reload_front(const TextProperties::TextFront::Front& target) { if (current_context_properties_.front == target) return {}; diff --git a/src/stream/fmt/context/parser_executor/parser_args.hxx b/src/stream/fmt/context/parser_executor/parser_args.hxx index 40dec187..2f74a540 100644 --- a/src/stream/fmt/context/parser_executor/parser_args.hxx +++ b/src/stream/fmt/context/parser_executor/parser_args.hxx @@ -2,6 +2,7 @@ #include "stream/fmt/context/basic_context/basic_args_interface.hxx" #include "stream/fmt/detail/prelude.hxx" +#include "stream/fmt/context/formatter_executor/named_args.hxx" namespace stream::fmt::detail { /****************************/ diff --git a/src/stream/fmt/serializers/std_container/map.hxx b/src/stream/fmt/serializers/std_container/map.hxx index 5bccca33..bf3d3eaf 100644 --- a/src/stream/fmt/serializers/std_container/map.hxx +++ b/src/stream/fmt/serializers/std_container/map.hxx @@ -17,7 +17,7 @@ namespace stream::fmt { template struct FormatterType, FormatterExecutor> { [[nodiscard]] static std::expected format(const std::multimap& t, FormatterExecutor& executor) { - return ormatterType>, FormatterExecutor>::format(t, executor); + return FormatterType>, FormatterExecutor>::format(t, executor); } }; } // namespace stream::fmt diff --git a/src/stream/fmt/serializers/std_container/tuple.hxx b/src/stream/fmt/serializers/std_container/tuple.hxx index a8a03394..8dcf3e0f 100644 --- a/src/stream/fmt/serializers/std_container/tuple.hxx +++ b/src/stream/fmt/serializers/std_container/tuple.hxx @@ -29,18 +29,18 @@ namespace stream::fmt::tuple_detail { SF_TRY(executor.write_type(t)); SF_TRY(executor.ostream.pushback(',')); SF_TRY(executor.ostream.pushback(' ')); - return tuple_format_rec(context, args...); + return tuple_format_rec(executor, args...); } } // namespace stream::fmt::tuple_detail namespace stream::fmt { template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static inline std::expected format(const std::tuple& t, FormatterExecutor& executor) { + [[nodiscard]] static std::expected format(const std::tuple& t, FormatterExecutor& executor) { SF_TRY(executor.ostream.pushback('<')); std::expected err = {}; - std::apply([&context, &err](auto&&... args) { - auto&& res = tuple_detail::tuple_format_rec(context, args...); + std::apply([&context_executor, &err](auto&&... args) { + auto&& res = tuple_detail::tuple_format_rec(context_executor, args...); if (not res) { err = res.error(); } @@ -51,7 +51,7 @@ namespace stream::fmt { template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static inline std::expected format(const std::pair& t, FormatterExecutor& executor) { + [[nodiscard]] static std::expected format(const std::pair& t, FormatterExecutor& executor) { SF_TRY(executor.ostream.pushback('<')); SF_TRY(executor.write_type(t.first)); SF_TRY(executor.ostream.pushback(':')); diff --git a/src/stream/fmt/serializers/std_container/unordered_map.hxx b/src/stream/fmt/serializers/std_container/unordered_map.hxx index db93431c..9f94d5e0 100644 --- a/src/stream/fmt/serializers/std_container/unordered_map.hxx +++ b/src/stream/fmt/serializers/std_container/unordered_map.hxx @@ -9,14 +9,14 @@ namespace stream::fmt { template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static inline std::expected format(const std::unordered_map& t, FormatterExecutor& executor) { + [[nodiscard]] static std::expected format(const std::unordered_map& t, FormatterExecutor& executor) { return FormatterType>, FormatterExecutor>::format(t, executor); } }; template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static inline std::expected format(const std::unordered_multimap& t, FormatterExecutor& executor) { + [[nodiscard]] static std::expected format(const std::unordered_multimap& t, FormatterExecutor& executor) { return FormatterType>, FormatterExecutor>::format(t, executor); } }; diff --git a/src/stream/fmt/serializers/std_container/vector.hxx b/src/stream/fmt/serializers/std_container/vector.hxx index cb0ade55..92759bdf 100644 --- a/src/stream/fmt/serializers/std_container/vector.hxx +++ b/src/stream/fmt/serializers/std_container/vector.hxx @@ -8,7 +8,7 @@ namespace stream::fmt { template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static inline std::expected format(const std::vector& t, FormatterExecutor& executor) { + [[nodiscard]] static std::expected format(const std::vector& t, FormatterExecutor& executor) { return FormatterType>, FormatterExecutor>::format(t, executor); } }; diff --git a/src/stream/profiler/profiler_event_creator.cxx b/src/stream/profiler/profiler_event_creator.cxx index 60fc9b56..2cf3fa94 100644 --- a/src/stream/profiler/profiler_event_creator.cxx +++ b/src/stream/profiler/profiler_event_creator.cxx @@ -9,12 +9,14 @@ namespace stream::profiler { std::chrono::milliseconds const millis = std::chrono::duration_cast(info.duration); std::chrono::seconds const seconds = std::chrono::duration_cast(info.duration); + // NOLINTBEGIN(readability-magic-numbers) if (seconds.count() > 1.5) profiler_.get_logger().trace("{} : {} seconds", info.name, seconds.count()); else if (millis.count() > 5.0) profiler_.get_logger().trace("{} : {} ms", info.name, millis.count()); else profiler_.get_logger().trace("{} : {} us", info.name, us.count()); + // NOLINTEND(readability-magic-numbers) profiler_.add_event(*this); } @@ -24,6 +26,7 @@ namespace stream::profiler { profiler_.add_event(created); } + // NOLINTBEGIN(readability-magic-numbers) ObjectTracker::ObjectTracker(Profiler& profiler, std::string&& name, std::string&& category) : profiler_(profiler), name_(std::move(name)), category_(std::move(category)) { Event created(name_, category_, EventType::Objectcreated); created.info.id = 10; @@ -41,6 +44,7 @@ namespace stream::profiler { snapshot.info.id = 10; profiler_.add_event(snapshot); } + // NOLINTEND(readability-magic-numbers) void EventCounter::snapshot() { idx_++; From ec5d411eaba37cdc38acd497f11b06823c5b16f4 Mon Sep 17 00:00:00 2001 From: Sacha Bellier Date: Sun, 23 Mar 2025 19:27:06 +0100 Subject: [PATCH 25/42] fix: clang-format --- src/stream/profiler/profiler_json_serializers.hxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/stream/profiler/profiler_json_serializers.hxx b/src/stream/profiler/profiler_json_serializers.hxx index 74d84f79..8480af8a 100644 --- a/src/stream/profiler/profiler_json_serializers.hxx +++ b/src/stream/profiler/profiler_json_serializers.hxx @@ -64,7 +64,7 @@ namespace stream::json { intermediate.parse("tid", t.tid); std::uint64_t time_of_event = 0; intermediate.parse("ts", time_of_event); - t.time_of_event = std::chrono::microseconds(time_of_event); + t.time_of_event = std::chrono::microseconds(time_of_event); std::uint64_t duration = 0; intermediate.parse("dur", t.duration); t.duration = std::chrono::microseconds(duration); From edd58840d26cc467599e7f78cd8fd54ca5eee537 Mon Sep 17 00:00:00 2001 From: Sacha Bellier Date: Sun, 23 Mar 2025 19:36:38 +0100 Subject: [PATCH 26/42] fix: update MODULE deps --- .buildkite/windows_amd64.yml | 4 ---- MODULE.bazel | 19 +++++++++++++------ 2 files changed, 13 insertions(+), 10 deletions(-) diff --git a/.buildkite/windows_amd64.yml b/.buildkite/windows_amd64.yml index 8208a33e..71f111bf 100644 --- a/.buildkite/windows_amd64.yml +++ b/.buildkite/windows_amd64.yml @@ -2,10 +2,6 @@ agents: queue: "agent-runners-windows-amd64" steps: - # - label: ":bazel: Build And Test MSVC" - # commands: - # - bazelisk test //tests:units - - label: ":bazel: Build And Test Winlibs/clang" commands: - bazelisk build --config=winlibs-clang //tests:units diff --git a/MODULE.bazel b/MODULE.bazel index 65e8c940..443d565e 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -6,19 +6,26 @@ module( version = "0.1", ) -bazel_dep(name = "rules_cc", version = "0.0.10") -bazel_dep(name = "platforms", version = "0.0.10") +# libs-deps +# +bazel_dep(name = "platforms", version = "0.0.11") +bazel_dep(name = "rules_cc", version = "0.0.17") -git_override(module_name="bazel_utilities", remote="https://github.com/0-Sacha/bazel_utilities.git", commit="fbb17685ac9ba78fef914a322e6c37839dc16d4f") -git_override(module_name="bazel_buildbuddy", remote="https://github.com/0-Sacha/bazel_buildbuddy.git", commit="f3e98389266ce759fc71e1186502fa40f3ed3049") -git_override(module_name="bazel_winlibs", remote="https://github.com/0-Sacha/bazel_winlibs.git", commit="86a2725fb26fb73bfe8dc535f8f46bd1190cdae8") +# toolchains-deps +git_override(module_name="bazel_utilities", remote="https://github.com/0-Sacha/bazel_utilities.git", commit="1c3c6c01dcccc6c922c4955c92aa7c3c015a9d1c") +git_override(module_name="bazel_buildbuddy", remote="https://github.com/0-Sacha/bazel_buildbuddy.git", commit="cbcefed87e2baf56a6f74ad3e0613ce8ab0fdcf3") +git_override(module_name="bazel_winlibs", remote="https://github.com/0-Sacha/bazel_winlibs.git", commit="8c6a667fcb08c1b479db28562fa724c7f666504c") +# bazel_dep(name = "bazel_utilities", version = "0.0.1", dev_dependency = True) bazel_dep(name = "bazel_buildbuddy", version = "0.0.1", dev_dependency = True) bazel_dep(name = "bazel_winlibs", version = "0.0.1", dev_dependency = True) -git_override(module_name = "hedron_compile_commands", remote = "https://github.com/hedronvision/bazel-compile-commands-extractor.git", commit = "1e08f8e0507b6b6b1f4416a9a22cf5c28beaba93",) +# tools-deps +git_override(module_name = "hedron_compile_commands", remote = "https://github.com/hedronvision/bazel-compile-commands-extractor.git", commit = "1e08f8e0507b6b6b1f4416a9a22cf5c28beaba93") +# bazel_dep(name = "hedron_compile_commands", dev_dependency = True) +# toolchains winlibs_toolchain_extension = use_extension("@bazel_winlibs//:rules.bzl", "winlibs_toolchain_extension", dev_dependency = True) inject_repo(winlibs_toolchain_extension, "platforms", "bazel_utilities") winlibs_toolchain_extension.winlibs_toolchain(name = "winlibs", dbg_copts = [ "-g3", "-O0" ]) From 6bd7ddacf2e30669d9eac614ddd28b99acfd5379 Mon Sep 17 00:00:00 2001 From: Sacha Bellier Date: Sun, 23 Mar 2025 19:41:36 +0100 Subject: [PATCH 27/42] fix: test with clang-20 --- .github/workflows/tests_linux.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/tests_linux.yml b/.github/workflows/tests_linux.yml index 3dfb58d2..0f13c96b 100644 --- a/.github/workflows/tests_linux.yml +++ b/.github/workflows/tests_linux.yml @@ -37,12 +37,12 @@ jobs: run: | wget https://apt.llvm.org/llvm.sh chmod +x ./llvm.sh - sudo ./llvm.sh 17 + sudo ./llvm.sh 20 - name: Version run: clang --version - name: Building... - run: CC=clang++-17 bazelisk build //tests:units + run: CC=clang++-20 bazelisk build //tests:units - name: Testing... - run: CC=clang++-17 bazelisk test //tests:units + run: CC=clang++-20 bazelisk test //tests:units - name: Testing (asan)... - run: CC=clang++-17 bazelisk test --features=asan //tests:units + run: CC=clang++-20 bazelisk test --features=asan //tests:units From 89f95afc2df331bd4a082be713088e522e5aaf1b Mon Sep 17 00:00:00 2001 From: Sacha Bellier Date: Sun, 23 Mar 2025 22:17:28 +0100 Subject: [PATCH 28/42] wip: SF_VERIFY --- .github/workflows/linter.yml | 4 + BUILD.bazel | 2 +- examples/hello/BUILD.bazel | 2 +- src/stream/core/prelude.hxx | 7 +- src/stream/flog/backends/basic_logger.hxx | 12 +- .../flog/backends/logger_multi_sink_fast.hxx | 12 +- .../flog/backends/logger_multi_sink_safe.hxx | 22 +-- src/stream/flog/detail/detail.hxx | 2 +- src/stream/flog/sinks/logger_sink.hxx | 20 +-- src/stream/fmt/buf/fmt_manip_io.hxx | 14 +- src/stream/fmt/buf/fmt_read_manip.hxx | 22 +-- src/stream/fmt/buf/fmt_write_manip.hxx | 54 +++---- src/stream/fmt/buf/manip_io.hxx | 10 +- src/stream/fmt/buf/read_manip.hxx | 33 ++-- src/stream/fmt/buf/streamio.hxx | 4 +- src/stream/fmt/buf/test_manip.hxx | 16 +- .../fmt/buf/utils/buffer_globber_manip.hxx | 30 ++-- .../fmt/buf/utils/buffer_shift_manip.hxx | 10 +- src/stream/fmt/buf/utils/buffer_utils.hxx | 32 ++-- src/stream/fmt/buf/write_manip.hxx | 24 +-- .../basic_context/basic_args_interface.hxx | 2 +- .../context/basic_context/basic_context.hxx | 24 +-- .../basic_context_parse_impl.hxx | 144 +++++++++--------- .../basic_context/text_properties_manager.cxx | 26 ++-- .../basic_context/text_properties_manager.hxx | 17 +-- .../text_properties_manager_impl.hxx | 71 ++++----- .../basic_formatter_executor.hxx | 8 +- .../formatter_executor/format_basics_impl.hxx | 18 +-- .../format_text_properties_impl.hxx | 4 +- ...ormatter_text_properties_executor_ansi.hxx | 2 +- .../formatter_executor/std_enumerable.hxx | 10 +- .../formatter_executor/utility_functions.hxx | 32 ++-- .../parser_executor/basic_parser_executor.hxx | 8 +- .../parser_executor/parse_basics_impl.hxx | 12 +- .../parse_text_properties_impl.hxx | 4 +- .../parser_text_properties_executor_ansi.hxx | 2 +- .../parser_executor/utility_functions.hxx | 2 +- .../fmt/serializers/compilation_data.hxx | 8 +- src/stream/fmt/serializers/format_chrono.hxx | 46 +++--- .../fmt/serializers/std_container/tuple.hxx | 20 +-- .../text_properties/text_properties_front.hxx | 32 ++-- src/stream/tester/test_suite/test_suite.hxx | 28 ++-- tests/BUILD.bazel | 2 +- 43 files changed, 441 insertions(+), 413 deletions(-) diff --git a/.github/workflows/linter.yml b/.github/workflows/linter.yml index 319c12ce..4a81efd4 100644 --- a/.github/workflows/linter.yml +++ b/.github/workflows/linter.yml @@ -14,6 +14,8 @@ jobs: submodules: true - name: Install clang-format... run: sudo apt install clang-format + - name: Version + run: clang-format --version - run: ./conf/linter/clang-format.sh clang-tidy: @@ -29,5 +31,7 @@ jobs: key: bazel - name: Install clang-tidy... run: sudo apt install clang-tidy + - name: Version + run: clang-tidy --version - name: Running clang-tidy... run: ./scripts/clang-tidy.sh diff --git a/BUILD.bazel b/BUILD.bazel index 4e1c7c89..4cdfc025 100644 --- a/BUILD.bazel +++ b/BUILD.bazel @@ -8,7 +8,7 @@ cc_library( hdrs = glob([ "src/**/*.hxx" ]), includes = [ "src/" ], copts = select({ - "@rules_cc//cc/compiler:msvc-cl": ["/std:latest"], + "@rules_cc//cc/compiler:msvc-cl": ["/std:c++latest"], "//conditions:default": ["-std=c++23"], }), strip_include_prefix = "src", diff --git a/examples/hello/BUILD.bazel b/examples/hello/BUILD.bazel index 777df52e..c8b359b7 100644 --- a/examples/hello/BUILD.bazel +++ b/examples/hello/BUILD.bazel @@ -7,7 +7,7 @@ cc_binary( srcs = [ "main.cxx" ], includes = [ "" ], copts = select({ - "@rules_cc//cc/compiler:msvc-cl": ["/std:latest"], + "@rules_cc//cc/compiler:msvc-cl": ["/std:c++latest"], "//conditions:default": ["-std=c++23"], }), linkopts = select({ diff --git a/src/stream/core/prelude.hxx b/src/stream/core/prelude.hxx index 646e1f43..fa2f477c 100644 --- a/src/stream/core/prelude.hxx +++ b/src/stream/core/prelude.hxx @@ -49,4 +49,9 @@ namespace stream::detail { __expected.value(); \ }); -#define SF_FORWARD(exp) SF_TRY(exp) +#define SF_VERIFY(exp) \ + { \ + auto __expected = exp; \ + if (not __expected) [[unlikely]] \ + return std::unexpected(stream::detail::forward_error(__expected.error())); \ + } diff --git a/src/stream/flog/backends/basic_logger.hxx b/src/stream/flog/backends/basic_logger.hxx index f1204675..808e20ad 100644 --- a/src/stream/flog/backends/basic_logger.hxx +++ b/src/stream/flog/backends/basic_logger.hxx @@ -85,11 +85,11 @@ namespace stream::flog::detail { std::chrono::nanoseconds logTime = std::chrono::high_resolution_clock::now() - start_time_; - SF_TRY(fmt::detail::format_in_manager(preFormatStreamIOManager, false, fmt::buf::StreamView(m_Pattern), FORMAT_SV("time", logTime), FORMAT_SV("name", name_), - FORMAT_SV("data", flog::AddIndentInFormat(format)))); + SF_VERIFY(fmt::detail::format_in_manager(preFormatStreamIOManager, false, fmt::buf::StreamView(m_Pattern), FORMAT_SV("time", logTime), FORMAT_SV("name", name_), + FORMAT_SV("data", flog::AddIndentInFormat(format)))); - SF_TRY(fmt::detail::format_in_manager(fullFormatStreamIOManager, true, preFormatStreamIOManager.get_last_generated_buffer_info_view(), std::forward(args)..., - FORMAT_SV("color", severity))); + SF_VERIFY(fmt::detail::format_in_manager(fullFormatStreamIOManager, true, preFormatStreamIOManager.get_last_generated_buffer_info_view(), std::forward(args)..., + FORMAT_SV("color", severity))); m_Stream.write(fullFormatStreamIOManager.get_buffer(), static_cast(fullFormatStreamIOManager.get_last_generated_data_size())); m_Stream.flush(); @@ -102,8 +102,8 @@ namespace stream::flog::detail { std::chrono::nanoseconds logTime = std::chrono::high_resolution_clock::now() - start_time_; - SF_TRY(fmt::detail::format_in_manager(fullFormatStreamIOManager, true, fmt::buf::StreamView(m_Pattern), FORMAT_SV("data", t), FORMAT_SV("color", severity), - FORMAT_SV("time", logTime), FORMAT_SV("name", name_))); + SF_VERIFY(fmt::detail::format_in_manager(fullFormatStreamIOManager, true, fmt::buf::StreamView(m_Pattern), FORMAT_SV("data", t), FORMAT_SV("color", severity), + FORMAT_SV("time", logTime), FORMAT_SV("name", name_))); m_Stream.write(fullFormatStreamIOManager.get_buffer(), static_cast(fullFormatStreamIOManager.get_last_generated_data_size())); m_Stream.flush(); diff --git a/src/stream/flog/backends/logger_multi_sink_fast.hxx b/src/stream/flog/backends/logger_multi_sink_fast.hxx index e7af54c9..b057f48d 100644 --- a/src/stream/flog/backends/logger_multi_sink_fast.hxx +++ b/src/stream/flog/backends/logger_multi_sink_fast.hxx @@ -38,10 +38,12 @@ namespace stream::flog::detail { std::chrono::nanoseconds logTime = std::chrono::high_resolution_clock::now() - start_time_; fmt::buf::DynamicStreamIOManager manager(256); - auto formatBuffer = SF_TRY(fmt::detail::format_in_manager(manager, false, format, std::forward(args)...)); + + auto format_buffer = fmt::detail::format_in_manager(manager, false, format, std::forward(args)...); + if (format_buffer.has_value() == false) return std::unexpected(format_buffer.error()); for (auto& sink : sinks_) if (sink->need_to_log(severity)) { - SF_TRY(sink->format_and_write_to_sink(sink->get_pattern(severity), logTime, name_, static_cast>(*formatBuffer))); + SF_VERIFY(sink->format_and_write_to_sink(sink->get_pattern(severity), logTime, name_, static_cast>(*format_buffer.value()))); } await(severity); @@ -53,10 +55,12 @@ namespace stream::flog::detail { std::chrono::nanoseconds logTime = std::chrono::high_resolution_clock::now() - start_time_; fmt::buf::DynamicStreamIOManager manager(256); - auto formatBuffer = SF_TRY(fmt::detail::format_in_manager(manager, false, std::forward(t))); + + auto format_buffer = fmt::detail::format_in_manager(manager, false, std::forward(t)); + if (format_buffer.has_value() == false) return std::unexpected(format_buffer.error()); for (auto& sink : sinks_) if (sink->need_to_log(severity)) { - SF_TRY(sink->format_and_write_to_sink(sink->get_pattern(severity), logTime, name_, static_cast>(*formatBuffer))); + SF_VERIFY(sink->format_and_write_to_sink(sink->get_pattern(severity), logTime, name_, static_cast>(*format_buffer.value()))); } await(severity); diff --git a/src/stream/flog/backends/logger_multi_sink_safe.hxx b/src/stream/flog/backends/logger_multi_sink_safe.hxx index 612ceb73..54f2ea8a 100644 --- a/src/stream/flog/backends/logger_multi_sink_safe.hxx +++ b/src/stream/flog/backends/logger_multi_sink_safe.hxx @@ -42,12 +42,15 @@ namespace stream::flog::detail { if (sink->need_to_log(severity)) { fmt::buf::DynamicStreamIOManager manager_pattern(256); fmt::buf::DynamicStreamIOManager manager_format(256); - auto format_pattern_str = - SF_TRY(fmt::detail::format_in_manager(manager_pattern, false, std::string_view(sink->get_pattern(severity)), FORMAT_SV("time", logTime), - FORMAT_SV("name", FutureConcatNameAndSinkName(name_)), FORMAT_SV("data", flog::AddIndentInFormat(format)))); - auto format_format_str = SF_TRY(fmt::detail::format_in_manager(manager_format, false, static_cast(*format_pattern_str), - std::forward(args)..., FORMAT_SV("sink", sink->get_name()), FORMAT_SV("color", severity))); - SF_TRY(sink->WriteToSink(static_cast>(*format_format_str))); + + auto format_pattern_str = + fmt::detail::format_in_manager(manager_pattern, false, std::string_view(sink->get_pattern(severity)), FORMAT_SV("time", logTime), + FORMAT_SV("name", FutureConcatNameAndSinkName(name_)), FORMAT_SV("data", flog::AddIndentInFormat(format))); + if (format_pattern_str.has_value() == false) return std::unexpected(format_pattern_str.error()); + auto format_format_str = fmt::detail::format_in_manager(manager_format, false, static_cast(*format_pattern_str.value()), + std::forward(args)..., FORMAT_SV("sink", sink->get_name()), FORMAT_SV("color", severity)); + if (format_format_str.has_value() == false) return std::unexpected(format_format_str.error()); + SF_VERIFY(sink->WriteToSink(static_cast>(*format_format_str.value()))); } } @@ -62,9 +65,10 @@ namespace stream::flog::detail { for (auto& sink : sinks_) { if (sink->need_to_log(severity)) { fmt::buf::DynamicStreamIOManager manager(256); - auto formatBuffer = SF_TRY(fmt::detail::format_in_manager(manager, false, std::string_view(sink->get_pattern(severity)), FORMAT_SV("time", logTime), - FORMAT_SV("name", ConcatNameAndSinkName(name_, sink->get_name())), FORMAT_SV("data", t))); - SF_TRY(sink->WriteToSink(static_cast>(*formatBuffer))); + auto format_buffer = fmt::detail::format_in_manager(manager, false, std::string_view(sink->get_pattern(severity)), FORMAT_SV("time", logTime), + FORMAT_SV("name", ConcatNameAndSinkName(name_, sink->get_name())), FORMAT_SV("data", t)); + if (format_buffer.has_value() == false) return std::unexpected(format_buffer.error()); + SF_VERIFY(sink->WriteToSink(static_cast>(*format_buffer.value()))); } } diff --git a/src/stream/flog/detail/detail.hxx b/src/stream/flog/detail/detail.hxx index b78635f9..2be1a146 100644 --- a/src/stream/flog/detail/detail.hxx +++ b/src/stream/flog/detail/detail.hxx @@ -30,7 +30,7 @@ namespace stream::fmt { template struct FormatterType, FormatterExecutor> { [[nodiscard]] static std::expected format(const stream::flog::AddIndentInFormat& format, FormatterExecutor& executor) { - SF_TRY(buf::WriteManip(executor.ostream).fast_write_string_literal("{K:indent}")); + SF_VERIFY(buf::WriteManip(executor.ostream).fast_write_string_literal("{K:indent}")); return executor.write_type(format.format); } }; diff --git a/src/stream/flog/sinks/logger_sink.hxx b/src/stream/flog/sinks/logger_sink.hxx index f5dde5b3..8728c086 100644 --- a/src/stream/flog/sinks/logger_sink.hxx +++ b/src/stream/flog/sinks/logger_sink.hxx @@ -76,26 +76,28 @@ namespace stream::flog::detail { } [[nodiscard]] std::expected FormatAndWriteToSinkSync(PatternTransferType pattern, const std::chrono::nanoseconds& logTime, const NameType& loggerName, - const BufferType& formatBuffer) { + const BufferType& format_buffer) { fmt::buf::DynamicStreamIOManager manager(256); - auto format_pattern_str = SF_TRY(fmt::detail::format_in_manager(manager, false, pattern, FORMAT_SV("time", logTime), - FORMAT_SV("name", ConcatNameAndSinkName(loggerName, name)), FORMAT_SV("data", formatBuffer))); - BufferType buffer(*format_pattern_str); + + auto format_pattern_str = fmt::detail::format_in_manager(manager, false, pattern, FORMAT_SV("time", logTime), + FORMAT_SV("name", ConcatNameAndSinkName(loggerName, name)), FORMAT_SV("data", format_buffer)); + if (format_pattern_str.has_value() == false) return format_pattern_str.error(); + BufferType buffer(*format_pattern_str.value()); WriteToSinkSync(buffer); return {}; } [[nodiscard]] std::expected FormatAndWriteToSinkAsync(PatternTransferType pattern, const std::chrono::nanoseconds& logTime, - const NameType& loggerName, const BufferType& formatBuffer) { + const NameType& loggerName, const BufferType& format_buffer) { // TODO - m_AsyncWaiter = std::async(std::launch::async, &BasicLoggerSink::FormatAndWriteToSinkSync, this, pattern, logTime, loggerName, formatBuffer); + m_AsyncWaiter = std::async(std::launch::async, &BasicLoggerSink::FormatAndWriteToSinkSync, this, pattern, logTime, loggerName, format_buffer); return {}; } [[nodiscard]] std::expected format_and_write_to_sink(PatternTransferType pattern, const std::chrono::nanoseconds& logTime, const NameType& loggerName, - const BufferType& formatBuffer) { - if (IsAsync == AsyncSink::Sync) return FormatAndWriteToSinkSync(pattern, logTime, loggerName, formatBuffer); - return FormatAndWriteToSinkAsync(pattern, logTime, loggerName, formatBuffer); + const BufferType& format_buffer) { + if (IsAsync == AsyncSink::Sync) return FormatAndWriteToSinkSync(pattern, logTime, loggerName, format_buffer); + return FormatAndWriteToSinkAsync(pattern, logTime, loggerName, format_buffer); } }; } // namespace stream::flog::detail diff --git a/src/stream/fmt/buf/fmt_manip_io.hxx b/src/stream/fmt/buf/fmt_manip_io.hxx index 8ab54dc5..2f7c78c1 100644 --- a/src/stream/fmt/buf/fmt_manip_io.hxx +++ b/src/stream/fmt/buf/fmt_manip_io.hxx @@ -24,7 +24,7 @@ namespace stream::fmt::buf { public: [[nodiscard]] static std::expected, FMTResult> create(BasicStreamIOManager& ostream_manager) { FMTStreamIO res(ostream_manager); - SF_TRY(StreamIO::init(res)); + SF_VERIFY(StreamIO::init(res)); return res; } @@ -58,12 +58,12 @@ namespace stream::fmt::buf { public: [[nodiscard]] constexpr inline std::expected new_line_indent() { - SF_TRY(ManipIO(buffer).pushback('\n')); + SF_VERIFY(ManipIO(buffer).pushback('\n')); return ManipIO(buffer).pushback(' ', buffer.indent); } [[nodiscard]] constexpr inline std::expected pushback_check_indent(const TChar c) { - SF_TRY(ManipIO(buffer).pushback(c)); + SF_VERIFY(ManipIO(buffer).pushback(c)); if (c == '\n') { return ManipIO(buffer).pushback(' ', buffer.indent); } @@ -102,9 +102,11 @@ namespace stream::fmt::buf { TestAccess access(buffer); TestManip manip(buffer); - TChar* const oldpos = buffer.current_pos; - auto is_same = SF_TRY(manip.is_same_forward(sv)); - if (is_same && (access.is_equal_to(':') || access.is_equal_to('}'))) { + TChar* const oldpos = buffer.current_pos; + + auto is_same = manip.is_same_forward(sv); + if (is_same.has_value() == false) return std::unexpected(is_same.error()); + if (is_same.value() && (access.is_equal_to(':') || access.is_equal_to('}'))) { return true; } buffer.current_pos = oldpos; diff --git a/src/stream/fmt/buf/fmt_read_manip.hxx b/src/stream/fmt/buf/fmt_read_manip.hxx index d619da64..0bee31cb 100644 --- a/src/stream/fmt/buf/fmt_read_manip.hxx +++ b/src/stream/fmt/buf/fmt_read_manip.hxx @@ -21,7 +21,7 @@ namespace stream::fmt::buf { ShiftReadManip shift_manip(buffer); buf::TestManip manip(buffer); - SF_TRY(shift_manip.ignore_shift_begin_space(shift)); + SF_VERIFY(shift_manip.ignore_shift_begin_space(shift)); bool sign = false; if constexpr (std::is_signed_v) { @@ -38,7 +38,7 @@ namespace stream::fmt::buf { --shift.size; } - SF_TRY(shift_manip.ignore_shift_end(shift)); + SF_VERIFY(shift_manip.ignore_shift_end(shift)); i = sign ? -res : res; return {}; @@ -51,7 +51,7 @@ namespace stream::fmt::buf { buf::TestAccess access(buffer); buf::TestManip manip(buffer); - SF_TRY(shift_manip.ignore_shift_begin_space(shift)); + SF_VERIFY(shift_manip.ignore_shift_begin_space(shift)); bool sign = SF_TRY(manip.is_equal_to_forward('-')); if (sign) --shift.size; @@ -59,12 +59,12 @@ namespace stream::fmt::buf { T intpart = static_cast(0); if (access.is_a_digit()) { while (access.is_a_digit()) { - char c = SF_TRY(Manip(buffer).get_and_forward()); - intpart = intpart * 10 + (c - '0'); + intpart = intpart * 10 + (buffer.get() - '0'); + SF_VERIFY(Manip(buffer).forward()); --shift.size; } } else if (access.is_equal_to('.')) { - SF_TRY(buf::Manip(buffer).forward()); + SF_VERIFY(buf::Manip(buffer).forward()); } else { return std::unexpected(FMTResult::Parse_NonValidDigit); } @@ -90,7 +90,7 @@ namespace stream::fmt::buf { dec /= 10; } - SF_TRY(shift_manip.ignore_shift_end(shift)); + SF_VERIFY(shift_manip.ignore_shift_end(shift)); t = sign ? -intpart - dec : intpart + dec; return {}; @@ -107,11 +107,11 @@ namespace stream::fmt::buf { shift.size -= sizeof(T) * 8; if (base_prefix != '\0') shift.size -= 2; - SF_TRY(shift_manip.ignore_shift_begin_space(shift)); + SF_VERIFY(shift_manip.ignore_shift_begin_space(shift)); if (base_prefix != '\0') { - SF_TRY(manip.skip_one_of('0')); - SF_TRY(manip.skip_one_of(base_prefix)); + SF_VERIFY(manip.skip_one_of('0')); + SF_VERIFY(manip.skip_one_of(base_prefix)); } T res = (T)0; @@ -121,7 +121,7 @@ namespace stream::fmt::buf { Manip(buffer).forward_force(); } - SF_TRY(shift_manip.ignore_shift_end(shift)); + SF_VERIFY(shift_manip.ignore_shift_end(shift)); i = res; return {}; diff --git a/src/stream/fmt/buf/fmt_write_manip.hxx b/src/stream/fmt/buf/fmt_write_manip.hxx index 42c30274..1b544f54 100644 --- a/src/stream/fmt/buf/fmt_write_manip.hxx +++ b/src/stream/fmt/buf/fmt_write_manip.hxx @@ -33,20 +33,20 @@ namespace stream::fmt::buf { } if (!shift.print.before_is_a_digit()) { - SF_TRY(ShiftWriteManip(buffer).write_shift_begin(shift)); + SF_VERIFY(ShiftWriteManip(buffer).write_shift_begin(shift)); } if (i < 0) { - SF_TRY(ManipIO(buffer).pushback('-')); + SF_VERIFY(ManipIO(buffer).pushback('-')); i = -i; } if (shift.print.before_is_a_digit()) { - SF_TRY(ShiftWriteManip(buffer).write_shift_right_all(shift)); + SF_VERIFY(ShiftWriteManip(buffer).write_shift_right_all(shift)); } if (i == 0) { - SF_TRY(ManipIO(buffer).pushback('0')); + SF_VERIFY(ManipIO(buffer).pushback('0')); } else { - SF_TRY(ManipIO(buffer).forward(nb_digit)); + SF_VERIFY(ManipIO(buffer).forward(nb_digit)); std::int32_t nb_digit_ = nb_digit; while (nb_digit_ > 0) { Manip(buffer).backward_force(); @@ -54,10 +54,10 @@ namespace stream::fmt::buf { i /= 10; nb_digit_--; } - SF_TRY(ManipIO(buffer).forward(nb_digit)); + SF_VERIFY(ManipIO(buffer).forward(nb_digit)); } - SF_TRY(ShiftWriteManip(buffer).write_shift_end(shift)); + SF_VERIFY(ShiftWriteManip(buffer).write_shift_end(shift)); shift.print.after = old_after; return {}; @@ -79,21 +79,21 @@ namespace stream::fmt::buf { } if (!shift.print.before_is_a_digit()) { - SF_TRY(ShiftWriteManip(buffer).write_shift_begin(shift)); + SF_VERIFY(ShiftWriteManip(buffer).write_shift_begin(shift)); } if (i < 0) { - SF_TRY(ManipIO(buffer).pushback('-')); + SF_VERIFY(ManipIO(buffer).pushback('-')); i = -i; } if (shift.print.before_is_a_digit()) { - SF_TRY(ShiftWriteManip(buffer).write_shift_right_all(shift)); + SF_VERIFY(ShiftWriteManip(buffer).write_shift_right_all(shift)); } T k = std::trunc(i); if (k == 0) { - SF_TRY(ManipIO(buffer).pushback('0')); + SF_VERIFY(ManipIO(buffer).pushback('0')); } else { - SF_TRY(ManipIO(buffer).forward(nb_digit)); + SF_VERIFY(ManipIO(buffer).forward(nb_digit)); std::int32_t nb_digit_ = nb_digit; while (nb_digit_ > 0) { Manip(buffer).backward_force(); @@ -101,18 +101,18 @@ namespace stream::fmt::buf { k /= 10; nb_digit_--; } - SF_TRY(ManipIO(buffer).forward(nb_digit)); + SF_VERIFY(ManipIO(buffer).forward(nb_digit)); } - SF_TRY(ManipIO(buffer).pushback('.')); + SF_VERIFY(ManipIO(buffer).pushback('.')); i -= k; while (float_precision-- != 0) { T decimal = std::trunc(i *= 10); - SF_TRY(ManipIO(buffer).pushback((char)decimal + '0')); + SF_VERIFY(ManipIO(buffer).pushback((char)decimal + '0')); i -= decimal; } - SF_TRY(ShiftWriteManip(buffer).write_shift_end(shift)); + SF_VERIFY(ShiftWriteManip(buffer).write_shift_end(shift)); shift.print.before = old_before; return {}; @@ -138,18 +138,18 @@ namespace stream::fmt::buf { } if (base_prefix != '\0') { - SF_TRY(ManipIO(buffer).pushback('0')); - SF_TRY(ManipIO(buffer).pushback(base_prefix)); + SF_VERIFY(ManipIO(buffer).pushback('0')); + SF_VERIFY(ManipIO(buffer).pushback(base_prefix)); } - SF_TRY(manip.forward(digit_count)); + SF_VERIFY(manip.forward(digit_count)); std::int32_t k = digit_count + 1; while (--k != 0) { Manip(buffer).backward_force(); buffer.set(lut[i & (0b1 << digitSize)]); i = i >> digitSize; } - SF_TRY(manip.forward(digit_count)); + SF_VERIFY(manip.forward(digit_count)); return {}; } @@ -196,10 +196,10 @@ namespace stream::fmt::buf { } const CharStr* const end = str; - SF_TRY(WriteManip(buffer).fast_write_char_array(begin, end - begin)); + SF_VERIFY(WriteManip(buffer).fast_write_char_array(begin, end - begin)); if (size > 0 && *str == '\n') { - SF_TRY(FMTManipIO(buffer).new_line_indent()); + SF_VERIFY(FMTManipIO(buffer).new_line_indent()); ++str; --size; } @@ -219,18 +219,18 @@ namespace stream::fmt::buf { [[nodiscard]] inline std::expected write_char_ptr(const CharStr* str, std::size_t size, detail::ShiftInfo& shift) { if (shift.size <= 0) return WriteManip(buffer).fast_write_char_array(str, size); - SF_TRY(ManipIO(buffer).reserve(std::max(static_cast(shift.size), size))); + SF_VERIFY(ManipIO(buffer).reserve(std::max(static_cast(shift.size), size))); if (static_cast(shift.size) > size) { shift.size -= static_cast(size); - SF_TRY(ShiftWriteManip(buffer).write_shift_begin(shift)); + SF_VERIFY(ShiftWriteManip(buffer).write_shift_begin(shift)); - SF_TRY(WriteManip(buffer).fast_write_char_array(str, size)); + SF_VERIFY(WriteManip(buffer).fast_write_char_array(str, size)); - SF_TRY(ShiftWriteManip(buffer).write_shift_end(shift)); + SF_VERIFY(ShiftWriteManip(buffer).write_shift_end(shift)); } else { - SF_TRY(WriteManip(buffer).fast_write_char_array(str, size)); + SF_VERIFY(WriteManip(buffer).fast_write_char_array(str, size)); } return {}; } diff --git a/src/stream/fmt/buf/manip_io.hxx b/src/stream/fmt/buf/manip_io.hxx index 8e3b3ccd..3f44cc4b 100644 --- a/src/stream/fmt/buf/manip_io.hxx +++ b/src/stream/fmt/buf/manip_io.hxx @@ -23,7 +23,7 @@ namespace stream::fmt::buf { public: [[nodiscard]] std::expected add_size(const std::size_t count) noexcept { std::size_t currentSize = Access(buffer).get_buffer_current_size(); - SF_TRY(buffer.Manager.add_size(count)) + SF_VERIFY(buffer.Manager.add_size(count)) Manip(buffer).reload(buffer.Manager.get_buffer(), buffer.Manager.get_buffer_size()); buffer.current_pos = buffer.Manager.get_buffer() + currentSize; return {}; @@ -35,7 +35,7 @@ namespace stream::fmt::buf { } [[nodiscard]] inline std::expected forward(const std::size_t count = 1) noexcept { - SF_TRY(reserve(count)); + SF_VERIFY(reserve(count)); buffer.current_pos += count; return {}; } @@ -46,7 +46,7 @@ namespace stream::fmt::buf { } [[nodiscard]] inline std::expected pushback(const TChar c) noexcept { - SF_TRY(reserve(1)); + SF_VERIFY(reserve(1)); *buffer.current_pos++ = c; return {}; } @@ -56,7 +56,7 @@ namespace stream::fmt::buf { public: [[nodiscard]] inline std::expected pushback(const TChar c, auto count) noexcept { - SF_TRY(reserve(count)) + SF_VERIFY(reserve(count)) while (count-- > 0) pushback_force(c); return {}; @@ -72,7 +72,7 @@ namespace stream::fmt::buf { public: template [[nodiscard]] inline std::expected pushback_seq(const CharToPush... ele) noexcept { - SF_TRY(reserve(sizeof...(ele))) + SF_VERIFY(reserve(sizeof...(ele))) pushback_seq_impl(ele...); return {}; } diff --git a/src/stream/fmt/buf/read_manip.hxx b/src/stream/fmt/buf/read_manip.hxx index 83ed2487..3a1be547 100644 --- a/src/stream/fmt/buf/read_manip.hxx +++ b/src/stream/fmt/buf/read_manip.hxx @@ -3,6 +3,8 @@ #include "stream/fmt/buf/stream.hxx" #include "stream/fmt/buf/manip.hxx" +#include + namespace stream::fmt::buf { template class ReadManip { @@ -26,8 +28,8 @@ namespace stream::fmt::buf { T value = static_cast(0); while (TestAccess(buffer).is_a_digit()) { - char c = SF_TRY(Manip(buffer).get_and_forward()); - value = value * static_cast(10) + static_cast(c - static_cast('0')); + value = value * static_cast(10) + static_cast(buffer.get() - static_cast('0')); + SF_VERIFY(Manip(buffer).forward()); } t = sign ? -value : value; @@ -45,9 +47,9 @@ namespace stream::fmt::buf { bool sign = SF_TRY(manip.is_equal_to_forward('-')); if (access.is_a_digit()) { - SF_TRY(fast_read_integer(intpart)); + SF_VERIFY(fast_read_integer(intpart)); } else if (access.is_equal_to('.')) { - SF_TRY(buf::Manip(buffer).forward()); + SF_VERIFY(buf::Manip(buffer).forward()); } else { return std::unexpected(FMTResult::Parse_NonValidDigit); } @@ -77,28 +79,27 @@ namespace stream::fmt::buf { public: template - [[nodiscard]] std::expected FastReadCharPtr(const CharPtr* str, std::size_t sizeToCopy, bool isZeroEnded = true) { - if (Access(buffer).can_move_forward(sizeToCopy) == false) { - return ReadManip(buffer).FastReadCharPtr(str, Access(buffer).get_buffer_remaining_size(), isZeroEnded); + [[nodiscard]] std::expected fast_read_char_ptr(const CharPtr* str, std::size_t size_to_copy, bool is_zero_ended = true) { + if (Access(buffer).can_move_forward(size_to_copy) == false) { + return ReadManip(buffer).fast_read_char_ptr(str, Access(buffer).get_buffer_remaining_size(), is_zero_ended); } - // TODO : Opti with bigger types - while (sizeToCopy-- != 0) { - *str++ = SF_TRY(Manip(buffer).get_and_forward()); - } - if (isZeroEnded) { + std::copy_n(str, size_to_copy, buffer.current_pos); + buffer.current_pos += size_to_copy; + + if (is_zero_ended) { *str = 0; } return {}; } template - [[nodiscard]] inline std::expected FastReadCharArray(const CharStr (&str)[SIZE], bool isZeroEnded = true) { - return FastReadCharPtr(str, SIZE); + [[nodiscard]] inline std::expected fast_read_char_array(const CharStr (&str)[SIZE], bool is_zero_ended = true) { + return fast_read_char_ptr(str, SIZE); } template - [[nodiscard]] inline std::expected FastReadCharBound(const CharStr* begin, const CharStr* end, bool isZeroEnded = true) { - return FastReadCharPtr(begin, end - begin - (isZeroEnded ? 1 : 0), isZeroEnded); + [[nodiscard]] inline std::expected fast_read_char_bound(const CharStr* begin, const CharStr* end, bool is_zero_ended = true) { + return fast_read_char_ptr(begin, end - begin - (is_zero_ended ? 1 : 0), is_zero_ended); } }; } // namespace stream::fmt::buf diff --git a/src/stream/fmt/buf/streamio.hxx b/src/stream/fmt/buf/streamio.hxx index 72c2e780..fae0b253 100644 --- a/src/stream/fmt/buf/streamio.hxx +++ b/src/stream/fmt/buf/streamio.hxx @@ -22,7 +22,7 @@ namespace stream::fmt::buf { protected: [[nodiscard]] static std::expected init(StreamIO& in) { - SF_TRY(in.Manager.BeginContext()); + SF_VERIFY(in.Manager.BeginContext()); Manip(in).reload(in.Manager.get_buffer(), in.Manager.get_buffer_size()); return {}; } @@ -30,7 +30,7 @@ namespace stream::fmt::buf { public: [[nodiscard]] static std::expected, FMTResult> create(BasicStreamIOManager& ostream_manager) { StreamIO res(ostream_manager); - SF_TRY(init(res)); + SF_VERIFY(init(res)); return res; } diff --git a/src/stream/fmt/buf/test_manip.hxx b/src/stream/fmt/buf/test_manip.hxx index 76564564..ddc1c065 100644 --- a/src/stream/fmt/buf/test_manip.hxx +++ b/src/stream/fmt/buf/test_manip.hxx @@ -29,10 +29,10 @@ namespace stream::fmt::buf { } public: - constexpr inline bool IsLowerCase() const noexcept { + constexpr inline bool is_lower_case() const noexcept { return buffer.get() >= 'a' && buffer.get() <= 'z'; } - constexpr inline bool IsUpperCase() const noexcept { + constexpr inline bool is_upper_case() const noexcept { return buffer.get() >= 'A' && buffer.get() <= 'Z'; } constexpr inline bool is_a_digit() const noexcept { @@ -82,7 +82,7 @@ namespace stream::fmt::buf { template [[nodiscard]] constexpr inline std::expected is_equal_to_forward(const CharToTest... ele) noexcept { if (access().is_equal_to(ele...)) { - SF_TRY(Manip(buffer).forward()); + SF_VERIFY(Manip(buffer).forward()); return true; } return false; @@ -90,7 +90,7 @@ namespace stream::fmt::buf { template [[nodiscard]] constexpr inline std::expected is_not_equal_forward(const CharToTest... ele) noexcept { if (access().is_not_equal_to(ele...)) { - SF_TRY(Manip(buffer).forward()); + SF_VERIFY(Manip(buffer).forward()); return true; } return false; @@ -100,7 +100,7 @@ namespace stream::fmt::buf { template [[nodiscard]] constexpr std::expected is_same_forward(const CharToTest* str, std::size_t size) noexcept { if (access().is_same(str, size)) { - SF_TRY(Manip(buffer).forward(size)); + SF_VERIFY(Manip(buffer).forward(size)); return true; } return false; @@ -108,7 +108,7 @@ namespace stream::fmt::buf { template [[nodiscard]] constexpr inline std::expected is_same_forward(std::basic_string_view sv) noexcept { if (access().is_same(sv)) { - SF_TRY(Manip(buffer).forward(sv.size())); + SF_VERIFY(Manip(buffer).forward(sv.size())); return true; } return false; @@ -118,7 +118,7 @@ namespace stream::fmt::buf { template [[nodiscard]] inline std::expected skip_one_of(const CharToTest... ele) noexcept { if (access().is_equal_to(ele...)) { - SF_TRY(Manip(buffer).forward()); + SF_VERIFY(Manip(buffer).forward()); return {}; } return std::unexpected(FMTResult::Parse_TokenNotExpected); @@ -169,7 +169,7 @@ namespace stream::fmt::buf { template [[nodiscard]] std::expected, FMTResult> ViewExec(Func&& func) { TChar* begin = buffer.current_pos; - SF_TRY(func()); + SF_VERIFY(func()); TChar* end = buffer.current_pos; return std::basic_string_view(begin, end - begin); } diff --git a/src/stream/fmt/buf/utils/buffer_globber_manip.hxx b/src/stream/fmt/buf/utils/buffer_globber_manip.hxx index 78374e96..85ee160a 100644 --- a/src/stream/fmt/buf/utils/buffer_globber_manip.hxx +++ b/src/stream/fmt/buf/utils/buffer_globber_manip.hxx @@ -23,29 +23,31 @@ namespace stream::fmt::buf { } if (TestAccess(glob).is_equal_to('?')) { - SF_TRY(Manip(glob).forward()); - SF_TRY(Manip(istream).forward()); + SF_VERIFY(Manip(glob).forward()); + SF_VERIFY(Manip(istream).forward()); return buffer_exec_glob_(istream, glob); } else if (TestAccess(glob).is_equal_to('*')) { - SF_TRY(Manip(glob).forward()); + SF_VERIFY(Manip(glob).forward()); const TChar* further = SF_TRY(buffer_exec_glob_(istream, glob)); while (Access(istream).can_move_forward()) { - SF_TRY(Manip(istream).forward()); + SF_VERIFY(Manip(istream).forward()); const TChar* last = SF_TRY(buffer_exec_glob_(istream, glob)); if (last > further || further == nullptr) further = last; } return further; } else if (TestAccess(glob).is_equal_to('[')) { - SF_TRY(Manip(istream).forward()); + SF_VERIFY(Manip(istream).forward()); const TChar* begin = glob.current_pos; - SF_TRY(TestManip(glob).go_to_forward(']')); + SF_VERIFY(TestManip(glob).go_to_forward(']')); const TChar* end = glob.current_pos; StreamView charSet(begin, end - begin); - bool is_inverted = SF_TRY(TestManip(glob).is_equal_to_forward('!')); - TChar toMatch = SF_TRY(Manip(istream).get_and_forward()); - bool found = false; + bool is_inverted = TestAccess(glob).is_equal_to('!'); + TChar toMatch = istream.get(); + SF_VERIFY(Manip(glob).forward()); + SF_VERIFY(Manip(istream).forward()); + bool found = false; while (found == false && Access(charSet).can_move_forward()) { if (TestAccess(charSet).is_equal_to(toMatch)) { @@ -73,8 +75,8 @@ namespace stream::fmt::buf { } if (istream.get() == glob.get()) { - SF_TRY(Manip(glob).forward()); - SF_TRY(Manip(istream).forward()); + SF_VERIFY(Manip(glob).forward()); + SF_VERIFY(Manip(istream).forward()); return buffer_exec_glob_(istream, glob); } return nullptr; @@ -98,17 +100,17 @@ namespace stream::fmt::buf { Stream& buffer; public: - [[nodiscard]] std::expected FastReadCharPtrGlobber(std::basic_string_view globPattern, TChar* str, std::size_t sizeToCopy) { + [[nodiscard]] std::expected fast_read_char_ptrGlobber(std::basic_string_view globPattern, TChar* str, std::size_t size_to_copy) { Stream globber(globPattern); const TChar* begin = buffer.current_pos; Globber::buffer_exec_glob(*this, globber); const TChar* end = buffer.current_pos; Stream subContext(begin, end); - return ReadManip(subContext).FastReadCharPtr(str, sizeToCopy); + return ReadManip(subContext).fast_read_char_ptr(str, size_to_copy); } - [[nodiscard]] std::expected FastReadCharPtrRegex(std::basic_string_view regexPattern, TChar* str, std::size_t sizeToCopy) { + [[nodiscard]] std::expected fast_read_char_ptrRegex(std::basic_string_view regexPattern, TChar* str, std::size_t size_to_copy) { return std::unexpected(FMTResult::FunctionNotImpl); } }; diff --git a/src/stream/fmt/buf/utils/buffer_shift_manip.hxx b/src/stream/fmt/buf/utils/buffer_shift_manip.hxx index 63ac8a97..76a05b1f 100644 --- a/src/stream/fmt/buf/utils/buffer_shift_manip.hxx +++ b/src/stream/fmt/buf/utils/buffer_shift_manip.hxx @@ -17,7 +17,7 @@ namespace stream::fmt::buf { if (shift.type == detail::ShiftInfo::ShiftType::CenterRight || shift.type == detail::ShiftInfo::ShiftType::CenterLeft) { std::int32_t shift_ = shift.size / 2; if (shift.type == detail::ShiftInfo::ShiftType::CenterLeft) shift_ = (shift.size + 1) / 2; - SF_TRY(ManipIO(buffer).pushback(shift.print.before, shift.size - shift_)); + SF_VERIFY(ManipIO(buffer).pushback(shift.print.before, shift.size - shift_)); shift.size = shift_; } @@ -41,12 +41,12 @@ namespace stream::fmt::buf { } [[nodiscard]] inline std::expected write_shift_begin(detail::ShiftInfo& shift) { - SF_TRY(WriteShiftCenterBegin(shift)); + SF_VERIFY(WriteShiftCenterBegin(shift)); return write_shift_right_all(shift); } [[nodiscard]] inline std::expected write_shift_end(detail::ShiftInfo& shift) { - SF_TRY(WriteShiftLeftAll(shift)); + SF_VERIFY(WriteShiftLeftAll(shift)); return WriteShiftCenterEnd(shift); } }; @@ -65,7 +65,7 @@ namespace stream::fmt::buf { if (shift.type == detail::ShiftInfo::ShiftType::Right || shift.type == detail::ShiftInfo::ShiftType::CenterLeft || shift.type == detail::ShiftInfo::ShiftType::CenterRight) { while (buffer.get() == ' ') { - SF_TRY(Manip(buffer).forward()); + SF_VERIFY(Manip(buffer).forward()); --shift.size; } } @@ -76,7 +76,7 @@ namespace stream::fmt::buf { if (shift.type == detail::ShiftInfo::ShiftType::Left || shift.type == detail::ShiftInfo::ShiftType::CenterLeft || shift.type == detail::ShiftInfo::ShiftType::CenterRight) { while (buffer.get() == ' ' && shift.size > 0) { - SF_TRY(Manip(buffer).forward()); + SF_VERIFY(Manip(buffer).forward()); --shift.size; } } diff --git a/src/stream/fmt/buf/utils/buffer_utils.hxx b/src/stream/fmt/buf/utils/buffer_utils.hxx index e59397c2..bbe06ab0 100644 --- a/src/stream/fmt/buf/utils/buffer_utils.hxx +++ b/src/stream/fmt/buf/utils/buffer_utils.hxx @@ -48,69 +48,69 @@ namespace stream::fmt::buf { namespace utils { template [[nodiscard]] static std::expected parse_escaped_quoted_string(buf::Stream& buffer, buf::StreamIO& stringOut) { - SF_TRY(buf::TestManip(buffer).skip_one_of('"')); + SF_VERIFY(buf::TestManip(buffer).skip_one_of('"')); while (buf::Access(buffer).is_end_of_string() == false) { auto view = SF_TRY(buf::TestManip(buffer).view_until('"', '\\')); - SF_TRY(buf::WriteManip(stringOut).fast_write_string(view)); + SF_VERIFY(buf::WriteManip(stringOut).fast_write_string(view)); if (buf::TestAccess(buffer).is_equal_to('"')) { break; } - SF_TRY(buf::TestManip(buffer).skip_one_of('\\')); + SF_VERIFY(buf::TestManip(buffer).skip_one_of('\\')); switch (buffer.get()) { // TODO : Do all others escape char case '"': - SF_TRY(buf::ManipIO(stringOut).pushback('"')); + SF_VERIFY(buf::ManipIO(stringOut).pushback('"')); break; case 't': - SF_TRY(buf::ManipIO(stringOut).pushback('\t')); + SF_VERIFY(buf::ManipIO(stringOut).pushback('\t')); break; case 'r': - SF_TRY(buf::ManipIO(stringOut).pushback('\r')); + SF_VERIFY(buf::ManipIO(stringOut).pushback('\r')); break; case 'n': - SF_TRY(buf::ManipIO(stringOut).pushback('\n')); + SF_VERIFY(buf::ManipIO(stringOut).pushback('\n')); break; default: break; } } - SF_TRY(buf::TestManip(buffer).skip_one_of('"')); + SF_VERIFY(buf::TestManip(buffer).skip_one_of('"')); return {}; } template [[nodiscard]] static std::expected format_escaped_quoted_string(buf::StreamIO& buffer, buf::Stream& string_in) { - SF_TRY(buf::ManipIO(buffer).pushback('"')); + SF_VERIFY(buf::ManipIO(buffer).pushback('"')); while (buf::Access(string_in).is_end_of_string() == false) { auto view = SF_TRY(buf::TestManip(string_in).view_until('\\')); - SF_TRY(buf::WriteManip(buffer).fast_write_string(view)); + SF_VERIFY(buf::WriteManip(buffer).fast_write_string(view)); if (buf::Access(string_in).is_end_of_string()) break; // TODO - SF_TRY(buf::TestManip(string_in).skip_one_of('\\')); + SF_VERIFY(buf::TestManip(string_in).skip_one_of('\\')); switch (string_in.get()) { // TODO : Do all others escape char case '"': - SF_TRY(buf::ManipIO(buffer).pushback('"')); + SF_VERIFY(buf::ManipIO(buffer).pushback('"')); break; case 't': - SF_TRY(buf::ManipIO(buffer).pushback('\t')); + SF_VERIFY(buf::ManipIO(buffer).pushback('\t')); break; case 'r': - SF_TRY(buf::ManipIO(buffer).pushback('\r')); + SF_VERIFY(buf::ManipIO(buffer).pushback('\r')); break; case 'n': - SF_TRY(buf::ManipIO(buffer).pushback('\n')); + SF_VERIFY(buf::ManipIO(buffer).pushback('\n')); break; default: break; } } - SF_TRY(buf::ManipIO(buffer).pushback('"')); + SF_VERIFY(buf::ManipIO(buffer).pushback('"')); return {}; } diff --git a/src/stream/fmt/buf/write_manip.hxx b/src/stream/fmt/buf/write_manip.hxx index 62630197..3b19a99f 100644 --- a/src/stream/fmt/buf/write_manip.hxx +++ b/src/stream/fmt/buf/write_manip.hxx @@ -55,25 +55,25 @@ namespace stream::fmt::buf { ManipIO manip(buffer); if (i == 0) { - SF_TRY(manip.pushback('0')); + SF_VERIFY(manip.pushback('0')); return {}; } if constexpr (std::is_signed_v) { if (i < 0) { - SF_TRY(manip.pushback('-')); + SF_VERIFY(manip.pushback('-')); i = -i; } } std::int32_t nb_digit = WriteUtils::get_number_of_digit_dec(i); - SF_TRY(manip.forward(nb_digit)); + SF_VERIFY(manip.forward(nb_digit)); while (i > 0) { Manip(buffer).backward_force(); ManipIO(buffer).set(i % 10 + '0'); i /= 10; } - SF_TRY(manip.forward(nb_digit)); + SF_VERIFY(manip.forward(nb_digit)); return {}; } @@ -85,18 +85,18 @@ namespace stream::fmt::buf { ManipIO manip(buffer); if (i == 0) { - SF_TRY(manip.pushback('0')); + SF_VERIFY(manip.pushback('0')); return {}; } if (i < 0) { - SF_TRY(manip.pushback('-')); + SF_VERIFY(manip.pushback('-')); i = -i; } T k = std::trunc(i); i = i - k; std::int32_t nb_digit = WriteUtils::get_number_of_digit_dec(k); - SF_TRY(manip.forward(nb_digit)); + SF_VERIFY(manip.forward(nb_digit)); std::int32_t nb_digit_ = nb_digit; while (nb_digit_ > 0) { Manip(buffer).backward_force(); @@ -104,12 +104,12 @@ namespace stream::fmt::buf { k /= 10; nb_digit_--; } - SF_TRY(manip.forward(nb_digit)); - SF_TRY(manip.pushback('.')); + SF_VERIFY(manip.forward(nb_digit)); + SF_VERIFY(manip.pushback('.')); while (float_precision-- >= 0) { TChar intPart = static_cast(std::trunc(i *= 10)); - SF_TRY(manip.pushback(intPart + '0')); + SF_VERIFY(manip.pushback(intPart + '0')); i -= intPart; } @@ -167,8 +167,8 @@ namespace stream::fmt::buf { template [[nodiscard]] inline std::expected basic_write_type(Type&& type, Rest&&... rest) { - SF_TRY(basic_write_type(type)); - if constexpr (sizeof...(rest) > 0) SF_TRY(basic_write_type(std::forward(rest)...)); + SF_VERIFY(basic_write_type(type)); + if constexpr (sizeof...(rest) > 0) SF_VERIFY(basic_write_type(std::forward(rest)...)); return {}; } }; diff --git a/src/stream/fmt/context/basic_context/basic_args_interface.hxx b/src/stream/fmt/context/basic_context/basic_args_interface.hxx index 9337fc19..e255ad38 100644 --- a/src/stream/fmt/context/basic_context/basic_args_interface.hxx +++ b/src/stream/fmt/context/basic_context/basic_args_interface.hxx @@ -51,7 +51,7 @@ namespace stream::fmt::detail { template [[nodiscard]] std::expected run_func_from_type_at(std::int32_t idx, std::function(const T&)> func) { const T* value = SF_TRY(get_type_at(idx)); - SF_TRY(func(*value)); + SF_VERIFY(func(*value)); return {}; } }; diff --git a/src/stream/fmt/context/basic_context/basic_context.hxx b/src/stream/fmt/context/basic_context/basic_context.hxx index 15fc80c2..a61431ce 100644 --- a/src/stream/fmt/context/basic_context/basic_context.hxx +++ b/src/stream/fmt/context/basic_context/basic_context.hxx @@ -53,12 +53,12 @@ namespace stream::fmt::context { [[nodiscard]] std::expected run(); private: - [[nodiscard]] std::expected GetFormatIndex_Number(); - [[nodiscard]] std::expected GetFormatIndex_Name(); - [[nodiscard]] std::expected GetFormatIndex_SubIndex(); + [[nodiscard]] std::expected get_format_index_number(); + [[nodiscard]] std::expected get_format_index_name(); + [[nodiscard]] std::expected get_format_index_sub_index(); public: - [[nodiscard]] std::expected GetFormatIndex(); + [[nodiscard]] std::expected get_format_index(); template [[nodiscard]] std::expected format_read_parameter(const T& default_value); @@ -70,11 +70,11 @@ namespace stream::fmt::context { [[nodiscard]] std::expected parse_format_data_base(); [[nodiscard]] std::expected parse_format_dataSpecial(); - [[nodiscard]] std::expected parse_format_dataSpecial_ShiftType(const detail::ShiftInfo::ShiftType type); + [[nodiscard]] std::expected parse_format_data_special_shift_type(const detail::ShiftInfo::ShiftType type); [[nodiscard]] std::expected parse_format_dataCustom(); [[nodiscard]] std::expected parse_format_data(); - [[nodiscard]] std::expected ParseVariable(std::int32_t formatIdx); + [[nodiscard]] std::expected parse_variable(std::int32_t formatIdx); [[nodiscard]] std::expected parse(); public: @@ -101,12 +101,12 @@ namespace stream::fmt::context { std::size_t size_continuous_string = 0; while (buf::Access(fmtstream).is_end_of_string() == false && buf::TestAccess(fmtstream).is_equal_to('{') == false) { ++size_continuous_string; - SF_TRY(buf::Manip(fmtstream).forward()); + SF_VERIFY(buf::Manip(fmtstream).forward()); } - SF_TRY(executor.exec_raw_string(std::basic_string_view(begin_continuous_string, size_continuous_string))); + SF_VERIFY(executor.exec_raw_string(std::basic_string_view(begin_continuous_string, size_continuous_string))); if (buf::Access(fmtstream).is_end_of_string() == false && buf::TestAccess(fmtstream).is_equal_to('{')) { - SF_TRY(parse()); + SF_VERIFY(parse()); } } @@ -131,13 +131,13 @@ namespace stream::fmt::context { [[nodiscard]] std::expected BasicContext::format_read_parameter(const T& default_value) { if (!buf::TestAccess(fmtstream).is_equal_to('{')) { T t; - SF_TRY(buf::ReadManip(fmtstream).fast_read_integer(t)); + SF_VERIFY(buf::ReadManip(fmtstream).fast_read_integer(t)); return t; } // SubIndex - SF_TRY(buf::TestManip(fmtstream).skip_one_of('}')); - std::int32_t formatIdx = SF_TRY(GetFormatIndex()); + SF_VERIFY(buf::TestManip(fmtstream).skip_one_of('}')); + std::int32_t formatIdx = SF_TRY(get_format_index()); if constexpr (std::is_convertible_v) return args_interface.get_int_at(formatIdx); else if constexpr (std::is_convertible_v>) diff --git a/src/stream/fmt/context/basic_context/basic_context_parse_impl.hxx b/src/stream/fmt/context/basic_context/basic_context_parse_impl.hxx index 78057fa1..7242ec95 100644 --- a/src/stream/fmt/context/basic_context/basic_context_parse_impl.hxx +++ b/src/stream/fmt/context/basic_context/basic_context_parse_impl.hxx @@ -24,18 +24,18 @@ namespace stream::fmt::context { buf::FMTParamsManip(fmtstream).param_go_to('{'); const TChar* begin = fmtstream.current_pos; - SF_TRY(manip.skip_one_of('{')); + SF_VERIFY(manip.skip_one_of('{')); int scopes = 0; while (buf::FMTParamsManip(fmtstream).is_end_of_parameter() == false || scopes > 0) { manip.GoTo('\'', '}', '{'); if (access.is_equal_to('\'')) { - SF_TRY(buf::Manip(fmtstream).forward()); + SF_VERIFY(buf::Manip(fmtstream).forward()); manip.go_to_forward('\''); } else if (access.is_equal_to('{')) { - SF_TRY(buf::Manip(fmtstream).forward()); + SF_VERIFY(buf::Manip(fmtstream).forward()); scopes++; } else if (scopes > 0 && access.is_equal_to('}')) { - SF_TRY(buf::Manip(fmtstream).forward()); + SF_VERIFY(buf::Manip(fmtstream).forward()); scopes--; } } @@ -49,23 +49,23 @@ namespace stream::fmt::context { buf::TestAccess access(fmtstream); if (access.is_equal_to('C')) { - SF_TRY(buf::Manip(fmtstream).forward()); - SF_TRY(executor.text_manager.parse_color(*this)); + SF_VERIFY(buf::Manip(fmtstream).forward()); + SF_VERIFY(executor.text_manager.parse_color(*this)); } else if (access.is_equal_to('S')) { - SF_TRY(buf::Manip(fmtstream).forward()); - SF_TRY(executor.text_manager.parse_style(*this)); + SF_VERIFY(buf::Manip(fmtstream).forward()); + SF_VERIFY(executor.text_manager.parse_style(*this)); } else if (access.is_equal_to('F')) { - SF_TRY(buf::Manip(fmtstream).forward()); - SF_TRY(executor.text_manager.parse_front(*this)); + SF_VERIFY(buf::Manip(fmtstream).forward()); + SF_VERIFY(executor.text_manager.parse_front(*this)); } else if (access.is_equal_to('K')) { - SF_TRY(buf::Manip(fmtstream).forward()); + SF_VERIFY(buf::Manip(fmtstream).forward()); executor.data.keep_new_style = true; } else if (access.is_equal_to('N')) { - SF_TRY(buf::Manip(fmtstream).forward()); + SF_VERIFY(buf::Manip(fmtstream).forward()); executor.data.next_override = SF_TRY(parse_next_override_format_data()); } @@ -73,16 +73,18 @@ namespace stream::fmt::context { } template - [[nodiscard]] std::expected BasicContext::parse_format_dataSpecial_ShiftType(const detail::ShiftInfo::ShiftType type) { + [[nodiscard]] std::expected BasicContext::parse_format_data_special_shift_type(const detail::ShiftInfo::ShiftType type) { executor.data.shift.type = type; executor.data.shift.size = SF_TRY(format_read_parameter(-1)); if (buf::TestAccess(fmtstream).is_equal_to(':')) { - SF_TRY(buf::Manip(fmtstream).forward()); - executor.data.shift.print.before = SF_TRY(buf::Manip(fmtstream).get_and_forward()); + SF_VERIFY(buf::Manip(fmtstream).forward()); + executor.data.shift.print.before = fmtstream.get(); executor.data.shift.print.after = executor.data.shift.print.before; + SF_VERIFY(buf::Manip(fmtstream).forward()); if (buf::TestAccess(fmtstream).is_equal_to('|')) { - SF_TRY(buf::Manip(fmtstream).forward()); - executor.data.shift.print.after = SF_TRY(buf::Manip(fmtstream).get_and_forward()); + SF_VERIFY(buf::Manip(fmtstream).forward()); + executor.data.shift.print.after = fmtstream.get(); + SF_VERIFY(buf::Manip(fmtstream).forward()); } } return {}; @@ -94,8 +96,8 @@ namespace stream::fmt::context { buf::TestManip manip(fmtstream); if (access.is_equal_to('{')) { - SF_TRY(buf::Manip(fmtstream).forward()); - std::int32_t formatIndex = SF_TRY(GetFormatIndex()); + SF_VERIFY(buf::Manip(fmtstream).forward()); + std::int32_t formatIndex = SF_TRY(get_format_index()); bool ableToapply = false; auto applyFormatData = SF_TRY(args_interface.template get_type_at>(formatIndex)); @@ -110,38 +112,38 @@ namespace stream::fmt::context { if (not ableToapply) { return std::unexpected(FMTResult::Context_CannotapplyType); } - SF_TRY(manip.skip_one_of('}')); + SF_VERIFY(manip.skip_one_of('}')); } else if (access.is_equal_to('.')) { - SF_TRY(buf::Manip(fmtstream).forward()); + SF_VERIFY(buf::Manip(fmtstream).forward()); executor.data.float_precision = SF_TRY(format_read_parameter(-1)); } else if (access.is_equal_to('d', 'b', 'b', 'o', 'O', 'x', 'X')) { - auto get = SF_TRY(buf::Manip(fmtstream).get_and_forward()); - executor.data.integer_print = static_cast(get); + executor.data.integer_print = static_cast(fmtstream.get()); + SF_VERIFY(buf::Manip(fmtstream).forward()); } else if (access.is_equal_to('#')) { - SF_TRY(buf::Manip(fmtstream).forward()); + SF_VERIFY(buf::Manip(fmtstream).forward()); executor.data.prefix_suffix = true; } else if (access.is_equal_to('>')) { - SF_TRY(buf::Manip(fmtstream).forward()); - SF_TRY(parse_format_dataSpecial_ShiftType(detail::ShiftInfo::ShiftType::Right)); + SF_VERIFY(buf::Manip(fmtstream).forward()); + SF_VERIFY(parse_format_data_special_shift_type(detail::ShiftInfo::ShiftType::Right)); } else if (access.is_equal_to('<')) { - SF_TRY(buf::Manip(fmtstream).forward()); - SF_TRY(parse_format_dataSpecial_ShiftType(detail::ShiftInfo::ShiftType::Left)); + SF_VERIFY(buf::Manip(fmtstream).forward()); + SF_VERIFY(parse_format_data_special_shift_type(detail::ShiftInfo::ShiftType::Left)); } else if (access.is_equal_to('^')) { - SF_TRY(buf::Manip(fmtstream).forward()); + SF_VERIFY(buf::Manip(fmtstream).forward()); if (access.is_equal_to('<')) { - SF_TRY(buf::Manip(fmtstream).forward()); - SF_TRY(parse_format_dataSpecial_ShiftType(detail::ShiftInfo::ShiftType::CenterLeft)); + SF_VERIFY(buf::Manip(fmtstream).forward()); + SF_VERIFY(parse_format_data_special_shift_type(detail::ShiftInfo::ShiftType::CenterLeft)); } else { manip.ignore_one_of('>'); - SF_TRY(parse_format_dataSpecial_ShiftType(detail::ShiftInfo::ShiftType::CenterRight)); + SF_VERIFY(parse_format_data_special_shift_type(detail::ShiftInfo::ShiftType::CenterRight)); } } @@ -162,21 +164,21 @@ namespace stream::fmt::context { manip.ignore_every_spaces(); if (access.is_equal_to('\'')) { - SF_TRY(buf::Manip(fmtstream).forward()); + SF_VERIFY(buf::Manip(fmtstream).forward()); std::basic_string_view value = SF_TRY(buf::TestManip(fmtstream).view_until('\'')); - SF_TRY(executor.data.specifiers.concat(detail::FormatSpecifier{name, value})); + SF_VERIFY(executor.data.specifiers.concat(detail::FormatSpecifier{name, value})); } else if (access.is_a_digit()) { std::int32_t value = 0; - SF_TRY(buf::ReadManip(fmtstream).fast_read_integer(value)); - SF_TRY(executor.data.specifiers.concat(detail::FormatSpecifier{name, value})); + SF_VERIFY(buf::ReadManip(fmtstream).fast_read_integer(value)); + SF_VERIFY(executor.data.specifiers.concat(detail::FormatSpecifier{name, value})); } else if (access.is_equal_to('{')) { - SF_TRY(buf::Manip(fmtstream).forward()); - std::int32_t idx = SF_TRY(GetFormatIndex()); + SF_VERIFY(buf::Manip(fmtstream).forward()); + std::int32_t idx = SF_TRY(get_format_index()); // TODO / FIXME // executor.data.specifiers.concat(detail::FormatSpecifier{name, GetTypeAtIndexAuto(idx)}); - SF_TRY(manip.skip_one_of('}')); + SF_VERIFY(manip.skip_one_of('}')); } else if (access.is_equal_to(',', '}')) { - SF_TRY(executor.data.specifiers.concat(detail::FormatSpecifier{name})); + SF_VERIFY(executor.data.specifiers.concat(detail::FormatSpecifier{name})); } return {}; @@ -192,12 +194,12 @@ namespace stream::fmt::context { while (buf::Access(fmtstream).is_end_of_string() == false && buf::FMTParamsManip(fmtstream).is_end_of_parameter() == false) { manip.ignore_every_spaces(); - if (access.IsUpperCase()) { - SF_TRY(parse_format_data_base()); - } else if (!access.IsLowerCase()) { - SF_TRY(parse_format_dataSpecial()); + if (access.is_upper_case()) { + SF_VERIFY(parse_format_data_base()); + } else if (!access.is_lower_case()) { + SF_VERIFY(parse_format_dataSpecial()); } else { - SF_TRY(parse_format_dataCustom()); + SF_VERIFY(parse_format_dataCustom()); } buf::FMTParamsManip(fmtstream).param_go_to(','); @@ -208,9 +210,9 @@ namespace stream::fmt::context { template - [[nodiscard]] std::expected BasicContext::GetFormatIndex_Number() { + [[nodiscard]] std::expected BasicContext::get_format_index_number() { std::int32_t index = -1; - SF_TRY(buf::ReadManip(fmtstream).fast_read_integer(index)); + SF_VERIFY(buf::ReadManip(fmtstream).fast_read_integer(index)); if (buf::TestAccess(fmtstream).is_equal_to(':') || buf::TestAccess(fmtstream).is_equal_to('}')) { if (index >= 0 && index < args_interface.size()) { @@ -221,7 +223,7 @@ namespace stream::fmt::context { return std::unexpected(FMTResult::Context_ArgumentIndexResolution); } template - [[nodiscard]] std::expected BasicContext::GetFormatIndex_Name() { + [[nodiscard]] std::expected BasicContext::get_format_index_name() { std::int32_t index = SF_TRY(args_interface.get_index_of_current_named_arg(fmtstream)); if (buf::TestAccess(fmtstream).is_equal_to(':') || buf::TestAccess(fmtstream).is_equal_to('}')) { if (index >= 0 && index < args_interface.size()) { @@ -232,19 +234,19 @@ namespace stream::fmt::context { return std::unexpected(FMTResult::Context_ArgumentIndexResolution); } template - [[nodiscard]] std::expected BasicContext::GetFormatIndex_SubIndex() { + [[nodiscard]] std::expected BasicContext::get_format_index_sub_index() { buf::TestAccess access(fmtstream); buf::TestManip manip(fmtstream); if (access.is_equal_to('{')) { - SF_TRY(buf::Manip(fmtstream).forward()); - std::int32_t recIndex = SF_TRY(GetFormatIndex()); - if (access.is_equal_to('}') && recIndex >= 0 && recIndex < args_interface.size()) { - SF_TRY(buf::Manip(fmtstream).forward()); + SF_VERIFY(buf::Manip(fmtstream).forward()); + std::int32_t rec_index = SF_TRY(get_format_index()); + if (access.is_equal_to('}') && rec_index >= 0 && rec_index < args_interface.size()) { + SF_VERIFY(buf::Manip(fmtstream).forward()); manip.ignore_every_spaces(); if (access.is_equal_to(':', '}')) { - std::int32_t finalRecIndex = (std::int32_t)SF_TRY(args_interface.get_int_at(recIndex)); - if (finalRecIndex >= 0 && finalRecIndex < args_interface.size()) return finalRecIndex; + std::int32_t final_rec_index = (std::int32_t)SF_TRY(args_interface.get_int_at(rec_index)); + if (final_rec_index >= 0 && final_rec_index < args_interface.size()) return final_rec_index; } } } @@ -252,7 +254,7 @@ namespace stream::fmt::context { } template - [[nodiscard]] std::expected BasicContext::GetFormatIndex() { + [[nodiscard]] std::expected BasicContext::get_format_index() { buf::TestAccess access(fmtstream); // I : if there is no number specified : ':' or '}' @@ -263,43 +265,43 @@ namespace stream::fmt::context { // II: A number(idx) if (access.is_a_digit()) { - return SF_FORWARD(GetFormatIndex_Number()); + return get_format_index_number(); } // III : A name - if (access.IsLowerCase() || access.IsUpperCase()) { - return SF_FORWARD(GetFormatIndex_Name()); + if (access.is_lower_case() || access.is_upper_case()) { + return get_format_index_name(); } // VI : { which is a idx to an argument if (access.is_equal_to('{')) { const TChar* oldPos = fmtstream.current_pos; - std::expected res = GetFormatIndex_SubIndex(); + std::expected res = get_format_index_sub_index(); if (res.has_value() == false && res.error() == FMTResult::Context_ArgumentIndexResolution) { fmtstream.current_pos = oldPos; return std::unexpected(FMTResult::Context_ArgumentIndexResolution); } - return SF_FORWARD(res); + return res; } return std::unexpected(FMTResult::Context_ArgumentIndexResolution); } template - [[nodiscard]] std::expected BasicContext::ParseVariable(std::int32_t formatIdx) { + [[nodiscard]] std::expected BasicContext::parse_variable(std::int32_t formatIdx) { detail::FormatData saveFormatData = executor.data; executor.data = detail::FormatData{}; detail::TextProperties::Properties saveTextProperties = executor.text_manager.save(); if (buf::TestAccess(fmtstream).is_equal_to(':', '{')) { - SF_TRY(buf::Manip(fmtstream).forward()); - SF_TRY(parse_format_data()); + SF_VERIFY(buf::Manip(fmtstream).forward()); + SF_VERIFY(parse_format_data()); } - SF_TRY(args_interface.run_type_at(formatIdx)); + SF_VERIFY(args_interface.run_type_at(formatIdx)); if (executor.data.keep_new_style == false) { - SF_TRY(executor.text_manager.reload(saveTextProperties)); + SF_VERIFY(executor.text_manager.reload(saveTextProperties)); } executor.data = saveFormatData; @@ -311,20 +313,20 @@ namespace stream::fmt::context { [[nodiscard]] std::expected BasicContext::parse() { buf::Manip(fmtstream).forward(); // Ignore { - if (buf::TestAccess(fmtstream).IsUpperCase()) { - SF_TRY(parse_format_data()); + if (buf::TestAccess(fmtstream).is_upper_case()) { + SF_VERIFY(parse_format_data()); return buf::FMTParamsManip(fmtstream).param_go_to_forward(); // Ignore } } - auto formatIdx = GetFormatIndex(); + auto formatIdx = get_format_index(); if (formatIdx.has_value()) { if (formatIdx.value() >= 0 && formatIdx.value() < args_interface.size()) { - SF_TRY(ParseVariable(formatIdx.value())); + SF_VERIFY(parse_variable(formatIdx.value())); return buf::FMTParamsManip(fmtstream).param_go_to_forward(); // Ignore } } } - SF_TRY(executor.exec_raw_string("{")); + SF_VERIFY(executor.exec_raw_string("{")); return {}; } } // namespace stream::fmt::context diff --git a/src/stream/fmt/context/basic_context/text_properties_manager.cxx b/src/stream/fmt/context/basic_context/text_properties_manager.cxx index 185649eb..3c552a4e 100644 --- a/src/stream/fmt/context/basic_context/text_properties_manager.cxx +++ b/src/stream/fmt/context/basic_context/text_properties_manager.cxx @@ -56,46 +56,46 @@ namespace stream::fmt::detail { // NOLINTBEGIN(readability-function-cognitive-complexity) [[nodiscard]] std::expected TextPropertiesapplyManager::reload_style(const TextProperties::TextStyle::Style& target) { if (target.intensity != current_context_properties_.style.intensity) { - SF_TRY(apply_style(target.intensity)); + SF_VERIFY(apply_style(target.intensity)); current_context_properties_.style.intensity = target.intensity; } if (target.italic != current_context_properties_.style.italic) { - SF_TRY(apply_style(target.italic)); + SF_VERIFY(apply_style(target.italic)); current_context_properties_.style.italic = target.italic; } if (target.blink != current_context_properties_.style.blink) { - SF_TRY(apply_style(target.blink)); + SF_VERIFY(apply_style(target.blink)); current_context_properties_.style.blink = target.blink; } if (target.inverted != current_context_properties_.style.inverted) { - SF_TRY(apply_style(target.inverted)); + SF_VERIFY(apply_style(target.inverted)); current_context_properties_.style.inverted = target.inverted; } if (target.ideogram != current_context_properties_.style.ideogram) { - SF_TRY(apply_style(target.ideogram)); + SF_VERIFY(apply_style(target.ideogram)); current_context_properties_.style.ideogram = target.ideogram; } if (target.script != current_context_properties_.style.script) { - SF_TRY(apply_style(target.script)); + SF_VERIFY(apply_style(target.script)); current_context_properties_.style.script = target.script; } if (target.underline != current_context_properties_.style.underline) { - SF_TRY(apply_style(target.underline)); + SF_VERIFY(apply_style(target.underline)); current_context_properties_.style.underline = target.underline; } if (target.underline_color.type != current_context_properties_.style.underline_color.type) { switch (target.underline_color.type) { case TextProperties::TextStyle::UnderlineColor::ColorType::Default: - SF_TRY(apply_style(TextProperties::TextStyle::UnderlineColor::ColorCube{TextProperties::TextStyle::UnderlineColor::ColorCube::Default})); + SF_VERIFY(apply_style(TextProperties::TextStyle::UnderlineColor::ColorCube{TextProperties::TextStyle::UnderlineColor::ColorCube::Default})); break; case TextProperties::TextStyle::UnderlineColor::ColorType::ColorCube: - SF_TRY(apply_style(target.underline_color.data.color_cube)); + SF_VERIFY(apply_style(target.underline_color.data.color_cube)); current_context_properties_.style.underline_color.data.color_cube = target.underline_color.data.color_cube; break; case TextProperties::TextStyle::UnderlineColor::ColorType::Color24b: - SF_TRY(apply_style(target.underline_color.data.color24b)); + SF_VERIFY(apply_style(target.underline_color.data.color24b)); current_context_properties_.style.underline_color.data.color24b = target.underline_color.data.color24b; break; } @@ -106,13 +106,13 @@ namespace stream::fmt::detail { break; case TextProperties::TextStyle::UnderlineColor::ColorType::ColorCube: if (current_context_properties_.style.underline_color.data.color_cube != target.underline_color.data.color_cube) { - SF_TRY(apply_style(target.underline_color.data.color_cube)); + SF_VERIFY(apply_style(target.underline_color.data.color_cube)); current_context_properties_.style.underline_color.data.color_cube = target.underline_color.data.color_cube; } break; case TextProperties::TextStyle::UnderlineColor::ColorType::Color24b: if (current_context_properties_.style.underline_color.data.color24b != target.underline_color.data.color24b) { - SF_TRY(apply_style(target.underline_color.data.color24b)); + SF_VERIFY(apply_style(target.underline_color.data.color24b)); current_context_properties_.style.underline_color.data.color24b = target.underline_color.data.color24b; } break; @@ -125,7 +125,7 @@ namespace stream::fmt::detail { [[nodiscard]] std::expected TextPropertiesapplyManager::reload_front(const TextProperties::TextFront::Front& target) { if (current_context_properties_.front == target) return {}; - SF_TRY(apply_front(target.CurrentID)); + SF_VERIFY(apply_front(target.current_id)); current_context_properties_.front = target; return {}; } diff --git a/src/stream/fmt/context/basic_context/text_properties_manager.hxx b/src/stream/fmt/context/basic_context/text_properties_manager.hxx index 950e6e4c..12ef5939 100644 --- a/src/stream/fmt/context/basic_context/text_properties_manager.hxx +++ b/src/stream/fmt/context/basic_context/text_properties_manager.hxx @@ -37,8 +37,8 @@ namespace stream::fmt::detail { } [[nodiscard]] std::expected all_properties_reset() { - SF_TRY(apply_color_reset()); - SF_TRY(apply_style_reset()); + SF_VERIFY(apply_color_reset()); + SF_VERIFY(apply_style_reset()); return apply_front_reset(); } [[nodiscard]] std::expected apply_color_reset() { @@ -61,12 +61,12 @@ namespace stream::fmt::detail { public: [[nodiscard]] std::expected reload_default() { - SF_TRY(reload_default_color()); - SF_TRY(reload_default_style()); + SF_VERIFY(reload_default_color()); + SF_VERIFY(reload_default_style()); return reload_default_front(); } [[nodiscard]] std::expected reload_default_color() { - SF_TRY(reload_default_color_fg()); + SF_VERIFY(reload_default_color_fg()); return reload_default_color_bg(); } [[nodiscard]] std::expected reload_default_color_fg() { @@ -83,12 +83,12 @@ namespace stream::fmt::detail { } [[nodiscard]] std::expected reload(const detail::TextProperties::Properties& target) { - SF_TRY(reload_color(target.color)); - SF_TRY(reload_style(target.style)); + SF_VERIFY(reload_color(target.color)); + SF_VERIFY(reload_style(target.style)); return reload_front(target.front); } [[nodiscard]] std::expected reload_color(const detail::TextProperties::TextColor::Color& target) { - SF_TRY(reload_color_fg(target.fg)); + SF_VERIFY(reload_color_fg(target.fg)); return reload_color_bg(target.bg); } @@ -202,7 +202,6 @@ namespace stream::fmt::detail { bool bright = SF_TRY(buf::TestManip(format).is_equal_to_forward('+')); std::uint8_t step = static_cast(bright ? T::BaseBStep : T::BaseStep); std::uint8_t code = (std::uint8_t)SF_TRY(buf::UtilsManip(format).get_word_from_list(colorCode)); - ; return static_cast(code + step); } } // namespace stream::fmt::detail diff --git a/src/stream/fmt/context/basic_context/text_properties_manager_impl.hxx b/src/stream/fmt/context/basic_context/text_properties_manager_impl.hxx index bed27981..b1f185b0 100644 --- a/src/stream/fmt/context/basic_context/text_properties_manager_impl.hxx +++ b/src/stream/fmt/context/basic_context/text_properties_manager_impl.hxx @@ -11,37 +11,37 @@ namespace stream::fmt::detail { template [[nodiscard]] std::expected detail::TextPropertiesManager::apply_colorOnIndex(context::BasicContext& context, std::int32_t index) { - SF_TRY(context.args_interface.template run_func_from_type_at( + SF_VERIFY(context.args_interface.template run_func_from_type_at( index, [this](const detail::TextProperties::TextColor::Color& data) -> std::expected { this->reload_color(data); return {}; })); - SF_TRY(context.args_interface.template run_func_from_type_at( + SF_VERIFY(context.args_interface.template run_func_from_type_at( index, [this](const detail::TextProperties::TextColor::BasicColorFG& data) -> std::expected { this->ask_apply_color(data); return {}; })); - SF_TRY(context.args_interface.template run_func_from_type_at( + SF_VERIFY(context.args_interface.template run_func_from_type_at( index, [this](const detail::TextProperties::TextColor::BasicColorBG& data) -> std::expected { this->ask_apply_color(data); return {}; })); - SF_TRY(context.args_interface.template run_func_from_type_at( + SF_VERIFY(context.args_interface.template run_func_from_type_at( index, [this](const detail::TextProperties::TextColor::ColorCubeFG& data) -> std::expected { this->ask_apply_color(data); return {}; })); - SF_TRY(context.args_interface.template run_func_from_type_at( + SF_VERIFY(context.args_interface.template run_func_from_type_at( index, [this](const detail::TextProperties::TextColor::ColorCubeBG& data) -> std::expected { this->ask_apply_color(data); return {}; })); - SF_TRY(context.args_interface.template run_func_from_type_at( + SF_VERIFY(context.args_interface.template run_func_from_type_at( index, [this](const detail::TextProperties::TextColor::Color24bFG& data) -> std::expected { this->ask_apply_color(data); return {}; })); - SF_TRY(context.args_interface.template run_func_from_type_at( + SF_VERIFY(context.args_interface.template run_func_from_type_at( index, [this](const detail::TextProperties::TextColor::Color24bBG& data) -> std::expected { this->ask_apply_color(data); return {}; @@ -51,12 +51,12 @@ namespace stream::fmt::detail { template [[nodiscard]] std::expected detail::TextPropertiesManager::apply_frontOnIndex(context::BasicContext& context, std::int32_t index) { - SF_TRY(context.args_interface.template run_func_from_type_at( + SF_VERIFY(context.args_interface.template run_func_from_type_at( index, [this](const detail::TextProperties::TextFront::Front& data) -> std::expected { this->reload_front(data); return {}; })); - SF_TRY(context.args_interface.template run_func_from_type_at( + SF_VERIFY(context.args_interface.template run_func_from_type_at( index, [this](const detail::TextProperties::TextFront::FrontID& data) -> std::expected { this->ask_apply_front(data); return {}; @@ -66,53 +66,53 @@ namespace stream::fmt::detail { template [[nodiscard]] std::expected detail::TextPropertiesManager::apply_styleOnIndex(context::BasicContext& context, std::int32_t index) { - SF_TRY(context.args_interface.template run_func_from_type_at( + SF_VERIFY(context.args_interface.template run_func_from_type_at( index, [this](const detail::TextProperties::TextStyle::Style& data) -> std::expected { return this->reload_style(data); return {}; })); - SF_TRY(context.args_interface.template run_func_from_type_at( + SF_VERIFY(context.args_interface.template run_func_from_type_at( index, [this](const detail::TextProperties::TextStyle::Intensity& data) -> std::expected { return this->ask_apply_style(data); return {}; })); - SF_TRY(context.args_interface.template run_func_from_type_at( + SF_VERIFY(context.args_interface.template run_func_from_type_at( index, [this](const detail::TextProperties::TextStyle::Italic& data) -> std::expected { return this->ask_apply_style(data); return {}; })); - SF_TRY(context.args_interface.template run_func_from_type_at( + SF_VERIFY(context.args_interface.template run_func_from_type_at( index, [this](const detail::TextProperties::TextStyle::Underline& data) -> std::expected { return this->ask_apply_style(data); return {}; })); - SF_TRY(context.args_interface.template run_func_from_type_at( + SF_VERIFY(context.args_interface.template run_func_from_type_at( index, [this](const detail::TextProperties::TextStyle::Blink& data) -> std::expected { return this->ask_apply_style(data); return {}; })); - SF_TRY(context.args_interface.template run_func_from_type_at( + SF_VERIFY(context.args_interface.template run_func_from_type_at( index, [this](const detail::TextProperties::TextStyle::Inverted& data) -> std::expected { return this->ask_apply_style(data); return {}; })); - SF_TRY(context.args_interface.template run_func_from_type_at( + SF_VERIFY(context.args_interface.template run_func_from_type_at( index, [this](const detail::TextProperties::TextStyle::Ideogram& data) -> std::expected { return this->ask_apply_style(data); return {}; })); - SF_TRY(context.args_interface.template run_func_from_type_at( + SF_VERIFY(context.args_interface.template run_func_from_type_at( index, [this](const detail::TextProperties::TextStyle::Script& data) -> std::expected { return this->ask_apply_style(data); return {}; })); - SF_TRY(context.args_interface.template run_func_from_type_at( + SF_VERIFY(context.args_interface.template run_func_from_type_at( index, [this](const detail::TextProperties::TextStyle::UnderlineColor::ColorCube& data) -> std::expected { this->ask_apply_style(data); return {}; })); - SF_TRY(context.args_interface.template run_func_from_type_at( + SF_VERIFY(context.args_interface.template run_func_from_type_at( index, [this](const detail::TextProperties::TextStyle::UnderlineColor::Color24b& data) -> std::expected { this->ask_apply_style(data); return {}; @@ -123,18 +123,18 @@ namespace stream::fmt::detail { template [[nodiscard]] std::expected detail::TextPropertiesManager::parse_color(context::BasicContext& context) { if (buf::TestAccess(context.fmtstream).is_equal_to(':')) { - SF_TRY(buf::Manip(context.fmtstream).forward()); + SF_VERIFY(buf::Manip(context.fmtstream).forward()); buf::TestManip(context.fmtstream).ignore_every_spaces(); if (buf::TestAccess(context.fmtstream).is_equal_to('{')) { - SF_TRY(buf::Manip(context.fmtstream).forward()); - std::int32_t idx = SF_TRY(context.GetFormatIndex()); - SF_TRY(apply_colorOnIndex(context, idx)); - SF_TRY(buf::TestManip(context.fmtstream).skip_one_of('}')); + SF_VERIFY(buf::Manip(context.fmtstream).forward()); + std::int32_t idx = SF_TRY(context.get_format_index()); + SF_VERIFY(apply_colorOnIndex(context, idx)); + SF_VERIFY(buf::TestManip(context.fmtstream).skip_one_of('}')); } else { auto color_fg = get_color_code(context.fmtstream); buf::FMTParamsManip(context.fmtstream).param_go_to('-', ','); if (buf::TestAccess(context.fmtstream).is_equal_to('-')) { - SF_TRY(buf::Manip(context.fmtstream).forward()); + SF_VERIFY(buf::Manip(context.fmtstream).forward()); buf::TestManip(context.fmtstream).ignore_every_spaces(); auto color_bg = get_color_code(context.fmtstream); if (color_bg.has_value() && color_fg.has_value()) { @@ -159,21 +159,22 @@ namespace stream::fmt::detail { template [[nodiscard]] std::expected detail::TextPropertiesManager::parse_style(context::BasicContext& context) { if (buf::TestAccess(context.fmtstream).is_equal_to(':')) { - SF_TRY(buf::Manip(context.fmtstream).forward()); + SF_VERIFY(buf::Manip(context.fmtstream).forward()); if (!buf::TestAccess(context.fmtstream).is_equal_to('}', ',')) { bool loop = true; while (loop) { buf::TestManip(context.fmtstream).ignore_every_spaces(); if (buf::TestAccess(context.fmtstream).is_equal_to('{')) { - SF_TRY(buf::Manip(context.fmtstream).forward()); - std::int32_t idx = SF_TRY(context.GetFormatIndex()); + SF_VERIFY(buf::Manip(context.fmtstream).forward()); + std::int32_t idx = SF_TRY(context.get_format_index()); apply_styleOnIndex(context, idx); buf::TestManip(context.fmtstream).skip_one_of('}'); } else { parse_style_named(context.fmtstream); } buf::FMTParamsManip(context.fmtstream).param_go_to('|', ','); - loop = SF_TRY(buf::TestManip(context.fmtstream).is_equal_to_forward('|')); + loop = buf::TestAccess(context.fmtstream).is_equal_to('|'); + SF_VERIFY(buf::Manip(context.fmtstream).forward()); buf::TestManip(context.fmtstream).ignore_every_spaces(); } } else { @@ -250,8 +251,9 @@ namespace stream::fmt::detail { code = (std::uint8_t)SF_TRY(buf::UtilsManip(format).get_word_from_dict_pairs(styleUnderline)); if (code != 255) { if (code == (std::uint8_t)detail::TextProperties::TextStyle::Underline::SelectUnderlinedColor) { - detail::TextProperties::TextStyle::UnderlineColor::ColorCube underlineColor = SF_TRY(select_underlined_color_style(format)); - return apply_style(underlineColor); + auto underlineColor = select_underlined_color_style(format); + if (underlineColor.has_value()) return std::unexpected(underlineColor.error()); + return apply_style(detail::TextProperties::TextStyle::UnderlineColor::ColorCube{underlineColor.value()}); } return apply_style(detail::TextProperties::TextStyle::Underline{code}); } @@ -271,11 +273,12 @@ namespace stream::fmt::detail { static constexpr std::string_view frontCode[] = {"default", "front0", "front1", "front2", "front3", "front4", "front5", "front6", "front7", "front8", "front9"}; if (buf::TestAccess(context.fmtstream).is_equal_to(':')) { - SF_TRY(buf::Manip(context.fmtstream).forward()); + SF_VERIFY(buf::Manip(context.fmtstream).forward()); buf::TestManip(context.fmtstream).ignore_every_spaces(); - detail::TextProperties::TextFront::FrontID frontID = (std::uint8_t)SF_TRY(buf::UtilsManip(context.fmtstream).get_word_from_list(frontCode)); - return apply_front(frontID); + auto front_id = buf::UtilsManip(context.fmtstream).get_word_from_list(frontCode); + if (front_id.has_value()) return std::unexpected(front_id.error()); + return apply_front(detail::TextProperties::TextFront::FrontID{front_id.value()}); } else return reload_default_front(); return {}; diff --git a/src/stream/fmt/context/formatter_executor/basic_formatter_executor.hxx b/src/stream/fmt/context/formatter_executor/basic_formatter_executor.hxx index 65a0e179..fd5e8721 100644 --- a/src/stream/fmt/context/formatter_executor/basic_formatter_executor.hxx +++ b/src/stream/fmt/context/formatter_executor/basic_formatter_executor.hxx @@ -55,9 +55,9 @@ namespace stream::fmt::context { template [[nodiscard]] inline std::expected write_type(Type&& type, Rest&&... rest) { auto&& formatErr = FormatterType>::type, M_Type>::format(std::forward(type), *this); - SF_TRY(formatErr); + SF_VERIFY(formatErr); if constexpr (sizeof...(rest) > 0) { - SF_TRY(write_type(std::forward(rest)...)); + SF_VERIFY(write_type(std::forward(rest)...)); } return {}; } @@ -78,7 +78,7 @@ namespace stream::fmt::context { // End char not included in buffer manager context to deduce size correctly auto res = buf::ManipIO(ostream).pushback('\0'); if (EndOfStringChar == EndOfStringCharMode::Forced) { - SF_TRY(res); + SF_VERIFY(res); } return {}; @@ -99,7 +99,7 @@ namespace stream::fmt::context { detail::TextProperties::Properties saveTextProperties = text_manager.save(); context::BasicContext context(*this, format, args_interface); - SF_TRY(context.run()); + SF_VERIFY(context.run()); return text_manager.reload(saveTextProperties); } diff --git a/src/stream/fmt/context/formatter_executor/format_basics_impl.hxx b/src/stream/fmt/context/formatter_executor/format_basics_impl.hxx index 547c7764..11265c0c 100644 --- a/src/stream/fmt/context/formatter_executor/format_basics_impl.hxx +++ b/src/stream/fmt/context/formatter_executor/format_basics_impl.hxx @@ -14,9 +14,9 @@ namespace stream::fmt { [[nodiscard]] static std::expected format(const typename FormatterExecutor::detail::template FormatSpecifier& specifier, FormatterExecutor& executor) { if (specifier.ValueIsText) { - SF_TRY(executor.run("{ '{}', '{}' }", specifier.name, specifier.as_text)); + SF_VERIFY(executor.run("{ '{}', '{}' }", specifier.name, specifier.as_text)); } else { - SF_TRY(executor.run("{ '{}', '{}' }", specifier.name, specifier.as_number)); + SF_VERIFY(executor.run("{ '{}', '{}' }", specifier.name, specifier.as_number)); } return {}; } @@ -39,7 +39,7 @@ namespace stream::fmt { return std::unexpected(FMTResult::GivenArgs_UnableToDeduceSize); } - SF_TRY(buf::WriteManip(executor.ostream).fast_write_string(executor.data.specifiers.get_as_text("begin", STDEnumerableUtility::DefaultBegin))); + SF_VERIFY(buf::WriteManip(executor.ostream).fast_write_string(executor.data.specifiers.get_as_text("begin", STDEnumerableUtility::DefaultBegin))); std::basic_string_view join = executor.data.specifiers.get_as_text("join", STDEnumerableUtility::DefaultJoin); @@ -51,9 +51,9 @@ namespace stream::fmt { if (first) { first = false; } else { - SF_TRY(buf::FMTWriteManip(executor.ostream).write_indent_string(join)); + SF_VERIFY(buf::FMTWriteManip(executor.ostream).write_indent_string(join)); } - SF_TRY(executor.write_type(*itbegin++)); + SF_VERIFY(executor.write_type(*itbegin++)); } return buf::WriteManip(executor.ostream).fast_write_string(executor.data.specifiers.get_as_text("end", STDEnumerableUtility::DefaultEnd)); @@ -76,17 +76,17 @@ namespace stream::fmt { if (executor.data.specifiers.has("indent")) return buf::FMTWriteManip(executor.ostream).write_indent_char_ptr(begin, size); if (executor.data.prefix_suffix) { - SF_TRY(buf::ManipIO(executor.ostream).pushback('\"')); + SF_VERIFY(buf::ManipIO(executor.ostream).pushback('\"')); } if (executor.data.has_spec == false) { - SF_TRY(buf::WriteManip(executor.ostream).fast_write_char_array(begin, size)); + SF_VERIFY(buf::WriteManip(executor.ostream).fast_write_char_array(begin, size)); } else { - SF_TRY(buf::FMTWriteManip(executor.ostream).write_char_ptr(begin, size, executor.data.shift)); + SF_VERIFY(buf::FMTWriteManip(executor.ostream).write_char_ptr(begin, size, executor.data.shift)); } if (executor.data.prefix_suffix) { - SF_TRY(buf::ManipIO(executor.ostream).pushback('\"')); + SF_VERIFY(buf::ManipIO(executor.ostream).pushback('\"')); } return {}; diff --git a/src/stream/fmt/context/formatter_executor/format_text_properties_impl.hxx b/src/stream/fmt/context/formatter_executor/format_text_properties_impl.hxx index 6d6f1666..630abc90 100644 --- a/src/stream/fmt/context/formatter_executor/format_text_properties_impl.hxx +++ b/src/stream/fmt/context/formatter_executor/format_text_properties_impl.hxx @@ -29,8 +29,8 @@ namespace stream::fmt { }; template - struct FormatterType { - [[nodiscard]] static std::expected format(const detail::TextProperties::TextFront::reset_front, FormatterExecutor& executor) { + struct FormatterType { + [[nodiscard]] static std::expected format(const detail::TextProperties::TextFront::ResetFront, FormatterExecutor& executor) { return executor.text_manager.apply_front_reset(); } }; diff --git a/src/stream/fmt/context/formatter_executor/formatter_text_properties_executor/formatter_text_properties_executor_ansi.hxx b/src/stream/fmt/context/formatter_executor/formatter_text_properties_executor/formatter_text_properties_executor_ansi.hxx index 54a2b933..286e8f16 100644 --- a/src/stream/fmt/context/formatter_executor/formatter_text_properties_executor/formatter_text_properties_executor_ansi.hxx +++ b/src/stream/fmt/context/formatter_executor/formatter_text_properties_executor/formatter_text_properties_executor_ansi.hxx @@ -68,7 +68,7 @@ namespace stream::fmt::detail { } [[nodiscard]] std::expected execute_front(const detail::TextProperties::TextFront::FrontID& t) override { NoStrideFunction no_stride(*buffer); - return buf::WriteManip(*buffer).basic_write_type("\033[", t.ID, "m"); + return buf::WriteManip(*buffer).basic_write_type("\033[", t.id, "m"); } public: diff --git a/src/stream/fmt/context/formatter_executor/std_enumerable.hxx b/src/stream/fmt/context/formatter_executor/std_enumerable.hxx index b5194290..daeee638 100644 --- a/src/stream/fmt/context/formatter_executor/std_enumerable.hxx +++ b/src/stream/fmt/context/formatter_executor/std_enumerable.hxx @@ -57,8 +57,8 @@ namespace stream::fmt { template struct FormatterType, FormatterExecutor> { [[nodiscard]] static std::expected format(const STDEnumerable& enumerable, FormatterExecutor& executor) { - SF_TRY(executor.ostream.write_indent_string_view(enumerable.get_str_begin())); - SF_TRY(executor.ostream.add_indent(enumerable.get_str_begin().size())); + SF_VERIFY(executor.ostream.write_indent_string_view(enumerable.get_str_begin())); + SF_VERIFY(executor.ostream.add_indent(enumerable.get_str_begin().size())); { // TODO: Why ? ... @@ -69,15 +69,15 @@ namespace stream::fmt { if (first) { first = false; } else { - SF_TRY(executor.ostream.write_indent_string_view(enumerable.get_str_join())); + SF_VERIFY(executor.ostream.write_indent_string_view(enumerable.get_str_join())); } - SF_TRY(executor.write_type(element)); + SF_VERIFY(executor.write_type(element)); }); } executor.ostream.remove_indent(enumerable.get_str_begin().size()); - SF_TRY(executor.ostream.write_indent_string_view(enumerable.get_str_end())); + SF_VERIFY(executor.ostream.write_indent_string_view(enumerable.get_str_end())); } }; diff --git a/src/stream/fmt/context/formatter_executor/utility_functions.hxx b/src/stream/fmt/context/formatter_executor/utility_functions.hxx index f3419aca..a2fd6d05 100644 --- a/src/stream/fmt/context/formatter_executor/utility_functions.hxx +++ b/src/stream/fmt/context/formatter_executor/utility_functions.hxx @@ -22,8 +22,8 @@ namespace stream::fmt { detail::FormatterTextPropertiesExecutorANSI text_properties_executor; buf::FMTStreamIO ostream = SF_TRY(buf::FMTStreamIO::create(ostream_manager)); context::BasicFormatterExecutor executor(ostream, text_properties_executor); - SF_TRY(executor.run(format, std::forward(args)...)); - if (newline) SF_TRY(buf::ManipIO(ostream).pushback('\n')); + SF_VERIFY(executor.run(format, std::forward(args)...)); + if (newline) SF_VERIFY(buf::ManipIO(ostream).pushback('\n')); return executor.terminate(); } @@ -35,8 +35,8 @@ namespace stream::fmt { detail::FormatterTextPropertiesExecutorANSI text_properties_executor; buf::FMTStreamIO ostream = SF_TRY(buf::FMTStreamIO::create(ostream_manager)); context::BasicFormatterExecutor executor(ostream, text_properties_executor); - SF_TRY(executor.write_type(std::forward(t))); - if (newline) SF_TRY(buf::ManipIO(ostream).pushback('\n')); + SF_VERIFY(executor.write_type(std::forward(t))); + if (newline) SF_VERIFY(buf::ManipIO(ostream).pushback('\n')); return executor.terminate(); } } // namespace detail @@ -59,7 +59,7 @@ namespace stream::fmt { requires(detail::IsCharType::value && buf::convertible_to_buffer_info_view) [[nodiscard]] std::expected cfile_print(FILE* stream, Format&& format_input, Args&&... args) { buf::DynamicStreamIOManager ostream_manager(256); - SF_TRY(detail::format_in_manager(ostream_manager, false, buf::StreamView{format_input}, std::forward(args)...)); + SF_VERIFY(detail::format_in_manager(ostream_manager, false, buf::StreamView{format_input}, std::forward(args)...)); std::fwrite(ostream_manager.get_buffer(), ostream_manager.get_last_generated_data_size(), 1, stream); std::fflush(stream); @@ -70,7 +70,7 @@ namespace stream::fmt { requires(detail::IsCharType::value && buf::convertible_to_buffer_info_view) [[nodiscard]] std::expected cfile_println(FILE* stream, Format&& format_input, Args&&... args) { buf::DynamicStreamIOManager ostream_manager(256); - SF_TRY(detail::format_in_manager(ostream_manager, true, buf::StreamView{format_input}, std::forward(args)...)); + SF_VERIFY(detail::format_in_manager(ostream_manager, true, buf::StreamView{format_input}, std::forward(args)...)); std::fwrite(ostream_manager.get_buffer(), ostream_manager.get_last_generated_data_size(), 1, stream); std::fflush(stream); @@ -81,7 +81,7 @@ namespace stream::fmt { requires(detail::IsCharType::value && buf::convertible_to_buffer_info_view) [[nodiscard]] std::expected file_print(std::basic_ostream& stream, Format&& format_input, Args&&... args) { buf::DynamicStreamIOManager ostream_manager(256); - SF_TRY(detail::format_in_manager(ostream_manager, false, buf::StreamView{format_input}, std::forward(args)...)); + SF_VERIFY(detail::format_in_manager(ostream_manager, false, buf::StreamView{format_input}, std::forward(args)...)); stream.write(ostream_manager.get_buffer(), ostream_manager.get_last_generated_data_size()); stream.flush(); @@ -92,7 +92,7 @@ namespace stream::fmt { requires(detail::IsCharType::value && buf::convertible_to_buffer_info_view) [[nodiscard]] std::expected file_println(std::basic_ostream& stream, Format&& format_input, Args&&... args) { buf::DynamicStreamIOManager ostream_manager(256); - SF_TRY(detail::format_in_manager(ostream_manager, true, buf::StreamView{format_input}, std::forward(args)...)); + SF_VERIFY(detail::format_in_manager(ostream_manager, true, buf::StreamView{format_input}, std::forward(args)...)); stream.write(ostream_manager.get_buffer(), ostream_manager.get_last_generated_data_size()); stream.flush(); @@ -103,7 +103,7 @@ namespace stream::fmt { requires(detail::IsCharType::value && buf::convertible_to_buffer_info_view) [[nodiscard]] std::expected format_in_string(std::basic_string& str, Format&& format_input, Args&&... args) { buf::DynamicStreamIOManager ostream_manager(256); - SF_TRY(detail::format_in_manager(ostream_manager, false, buf::StreamView{format_input}, std::forward(args)...)); + SF_VERIFY(detail::format_in_manager(ostream_manager, false, buf::StreamView{format_input}, std::forward(args)...)); str = ostream_manager.get_last_generated_string_view(); return {}; } @@ -112,7 +112,7 @@ namespace stream::fmt { requires(detail::IsCharType::value && buf::convertible_to_buffer_info_view) [[nodiscard]] inline std::expected, FMTResult> format_string(Format&& format_input, Args&&... args) { buf::DynamicStreamIOManager ostream_manager(256); - SF_TRY(detail::format_in_manager(ostream_manager, false, buf::StreamView{format_input}, std::forward(args)...)); + SF_VERIFY(detail::format_in_manager(ostream_manager, false, buf::StreamView{format_input}, std::forward(args)...)); return std::basic_string{ostream_manager.get_last_generated_string_view()}; } @@ -136,7 +136,7 @@ namespace stream::fmt { requires(detail::IsCharType::value) [[nodiscard]] std::expected cfile_print(FILE* stream, T&& t) { buf::DynamicStreamIOManager ostream_manager(32); - SF_TRY(detail::format_in_manager(ostream_manager, false, std::forward(t))); + SF_VERIFY(detail::format_in_manager(ostream_manager, false, std::forward(t))); std::fwrite(ostream_manager.get_buffer(), static_cast(ostream_manager.get_last_generated_data_size()), 1, stream); std::fflush(stream); @@ -147,7 +147,7 @@ namespace stream::fmt { requires(detail::IsCharType::value) [[nodiscard]] std::expected cfile_println(FILE* stream, T&& t) { buf::DynamicStreamIOManager ostream_manager(32); - SF_TRY(detail::format_in_manager(ostream_manager, true, std::forward(t))); + SF_VERIFY(detail::format_in_manager(ostream_manager, true, std::forward(t))); std::fwrite(ostream_manager.get_buffer(), static_cast(ostream_manager.get_last_generated_data_size()), 1, stream); std::fflush(stream); @@ -158,7 +158,7 @@ namespace stream::fmt { requires(detail::IsCharType::value) [[nodiscard]] std::expected file_print(std::basic_ostream& stream, T&& t) { buf::DynamicStreamIOManager ostream_manager(32); - SF_TRY(detail::format_in_manager(ostream_manager, false, std::forward(t))); + SF_VERIFY(detail::format_in_manager(ostream_manager, false, std::forward(t))); stream.write(ostream_manager.get_buffer(), static_cast(ostream_manager.get_last_generated_data_size())); stream.flush(); @@ -169,7 +169,7 @@ namespace stream::fmt { requires(detail::IsCharType::value) [[nodiscard]] std::expected file_println(std::basic_ostream& stream, T&& t) { buf::DynamicStreamIOManager ostream_manager(32); - SF_TRY(detail::format_in_manager(ostream_manager, true, std::forward(t))); + SF_VERIFY(detail::format_in_manager(ostream_manager, true, std::forward(t))); stream.write(ostream_manager.get_buffer(), static_cast(ostream_manager.get_last_generated_data_size())); stream.flush(); @@ -180,7 +180,7 @@ namespace stream::fmt { requires(detail::IsCharType::value) [[nodiscard]] std::expected format_in_string(std::basic_string& str, T&& t) { buf::DynamicStreamIOManager ostream_manager(32); - SF_TRY(detail::format_in_manager(ostream_manager, false, std::forward(t))); + SF_VERIFY(detail::format_in_manager(ostream_manager, false, std::forward(t))); str = ostream_manager.get_last_generated_string_view(); return {}; } @@ -189,7 +189,7 @@ namespace stream::fmt { requires(detail::IsCharType::value) [[nodiscard]] inline std::expected, FMTResult> format_string(T&& t) { buf::DynamicStreamIOManager ostream_manager(32); - SF_TRY(detail::format_in_manager(ostream_manager, false, std::forward(t))); + SF_VERIFY(detail::format_in_manager(ostream_manager, false, std::forward(t))); return std::string{ostream_manager.get_last_generated_string_view()}; } } // namespace stream::fmt diff --git a/src/stream/fmt/context/parser_executor/basic_parser_executor.hxx b/src/stream/fmt/context/parser_executor/basic_parser_executor.hxx index 46340832..6b9b0c3e 100644 --- a/src/stream/fmt/context/parser_executor/basic_parser_executor.hxx +++ b/src/stream/fmt/context/parser_executor/basic_parser_executor.hxx @@ -35,7 +35,7 @@ namespace stream::fmt::context { protected: [[nodiscard]] std::expected exec_raw_string(std::basic_string_view sv) override { - SF_TRY(buf::TestManip(istream).is_same_forward(sv.data(), sv.size())); + SF_VERIFY(buf::TestManip(istream).is_same_forward(sv.data(), sv.size())); return {}; } [[nodiscard]] std::expected exec_settings() override { @@ -52,8 +52,8 @@ namespace stream::fmt::context { template [[nodiscard]] inline std::expected read_type(Type& type, Rest&... rest) { auto&& parseErr = ParserType>::type, M_Type>::parse(type, *this); - SF_TRY(parseErr); - if constexpr (sizeof...(rest) > 0) SF_TRY(read_type(std::forward(rest)...)); + SF_VERIFY(parseErr); + if constexpr (sizeof...(rest) > 0) SF_VERIFY(read_type(std::forward(rest)...)); return {}; } }; @@ -78,7 +78,7 @@ namespace stream::fmt::context { detail::TextProperties::Properties saveTextProperties = text_manager.save(); context::BasicContext context(*this, format, args_interface); - SF_TRY(context.run()); + SF_VERIFY(context.run()); return text_manager.reload(saveTextProperties); } diff --git a/src/stream/fmt/context/parser_executor/parse_basics_impl.hxx b/src/stream/fmt/context/parser_executor/parse_basics_impl.hxx index 70b6f4ae..d54c987c 100644 --- a/src/stream/fmt/context/parser_executor/parse_basics_impl.hxx +++ b/src/stream/fmt/context/parser_executor/parse_basics_impl.hxx @@ -17,24 +17,24 @@ namespace stream::fmt { [[nodiscard]] static std::expected parse(bool& t, ParserExecutor& executor) { if (!executor.data.prefix_suffix) { if (buf::TestAccess(executor.istream).is_equal_to('t', 'T')) { - SF_TRY(buf::Manip(executor.istream).forward()); + SF_VERIFY(buf::Manip(executor.istream).forward()); if (buf::TestAccess(executor.istream).is_same("rue")) { - SF_TRY(buf::Manip(executor.istream).forward()); + SF_VERIFY(buf::Manip(executor.istream).forward(3)); t = true; } } else if (buf::TestAccess(executor.istream).is_equal_to('f', 'F')) { - SF_TRY(buf::Manip(executor.istream).forward()); + SF_VERIFY(buf::Manip(executor.istream).forward()); if (buf::TestAccess(executor.istream).is_same("alse")) { - SF_TRY(buf::Manip(executor.istream).forward()); + SF_VERIFY(buf::Manip(executor.istream).forward(4)); t = false; } } } else { if (buf::TestAccess(executor.istream).is_equal_to('1')) { - SF_TRY(buf::Manip(executor.istream).forward()); + SF_VERIFY(buf::Manip(executor.istream).forward()); t = true; } else if (buf::TestAccess(executor.istream).is_equal_to('0')) { - SF_TRY(buf::Manip(executor.istream).forward()); + SF_VERIFY(buf::Manip(executor.istream).forward()); t = false; } } diff --git a/src/stream/fmt/context/parser_executor/parse_text_properties_impl.hxx b/src/stream/fmt/context/parser_executor/parse_text_properties_impl.hxx index 6272e3f7..9fea0316 100644 --- a/src/stream/fmt/context/parser_executor/parse_text_properties_impl.hxx +++ b/src/stream/fmt/context/parser_executor/parse_text_properties_impl.hxx @@ -29,8 +29,8 @@ namespace stream::fmt { }; template - struct ParserType { - [[nodiscard]] static inline std::expected parse(detail::TextProperties::TextFront::reset_front, ParserExecutor& executor) { + struct ParserType { + [[nodiscard]] static inline std::expected parse(detail::TextProperties::TextFront::ResetFront, ParserExecutor& executor) { return executor.text_manager.apply_front_reset(); } }; diff --git a/src/stream/fmt/context/parser_executor/parser_text_properties_executor/parser_text_properties_executor_ansi.hxx b/src/stream/fmt/context/parser_executor/parser_text_properties_executor/parser_text_properties_executor_ansi.hxx index de071b57..ac641c1b 100644 --- a/src/stream/fmt/context/parser_executor/parser_text_properties_executor/parser_text_properties_executor_ansi.hxx +++ b/src/stream/fmt/context/parser_executor/parser_text_properties_executor/parser_text_properties_executor_ansi.hxx @@ -66,7 +66,7 @@ namespace stream::fmt::detail { } [[nodiscard]] std::expected execute_front(const detail::TextProperties::TextFront::FrontID&) override { return std::unexpected(FMTResult::FunctionNotImpl); - /*ReadManip(buffer).BasicReadType('\033', '[', t.ID, 'm');*/ + /*ReadManip(buffer).BasicReadType('\033', '[', t.id, 'm');*/ } public: diff --git a/src/stream/fmt/context/parser_executor/utility_functions.hxx b/src/stream/fmt/context/parser_executor/utility_functions.hxx index 4421c02b..f64055e2 100644 --- a/src/stream/fmt/context/parser_executor/utility_functions.hxx +++ b/src/stream/fmt/context/parser_executor/utility_functions.hxx @@ -16,7 +16,7 @@ namespace stream::fmt { detail::ParserNOTextPropertiesExecutor> text_properties_executor; context::BasicParserExecutor> executor(buffer, text_properties_executor); - SF_TRY(executor.run(format, std::forward(args)...)); + SF_VERIFY(executor.run(format, std::forward(args)...)); return executor.terminate(); } } // namespace stream::fmt diff --git a/src/stream/fmt/serializers/compilation_data.hxx b/src/stream/fmt/serializers/compilation_data.hxx index e13f9cb9..603612e2 100644 --- a/src/stream/fmt/serializers/compilation_data.hxx +++ b/src/stream/fmt/serializers/compilation_data.hxx @@ -33,8 +33,8 @@ namespace stream::fmt { template struct FormatterType { [[nodiscard]] static inline std::expected format(const detail::FileLocation& t, FormatterExecutor& executor) { - SF_TRY(executor.write_type(t.file_name)); - SF_TRY(executor.ostream.pushback(':')); + SF_VERIFY(executor.write_type(t.file_name)); + SF_VERIFY(executor.ostream.pushback(':')); return executor.write_type(t.file_line); } }; @@ -42,8 +42,8 @@ namespace stream::fmt { template struct FormatterType { [[nodiscard]] static inline std::expected format(const detail::FunctionProperties& t, FormatterExecutor& executor) { - SF_TRY(executor.write_type(t.location)); - SF_TRY(executor.ostream.write_char_array(" @ ")); + SF_VERIFY(executor.write_type(t.location)); + SF_VERIFY(executor.ostream.write_char_array(" @ ")); return executor.write_type(t.function_name); } }; diff --git a/src/stream/fmt/serializers/format_chrono.hxx b/src/stream/fmt/serializers/format_chrono.hxx index 7d391269..93c55ef0 100644 --- a/src/stream/fmt/serializers/format_chrono.hxx +++ b/src/stream/fmt/serializers/format_chrono.hxx @@ -28,44 +28,44 @@ namespace stream::fmt::detail { if (mode == TimePrintMode::Mod && shift.size < 0) shift.size = 3; if (buf::TestAccess(pattern).is_same("ns", 2)) { - SF_TRY(buf::Manip(pattern).forward()); + SF_VERIFY(buf::Manip(pattern).forward(2)); std::uint32_t ns = static_cast(std::chrono::time_point_cast(value).time_since_epoch().count()); if (mode == TimePrintMode::Mod) ns = ns % 1000; - SF_TRY(buf::FMTWriteManip(buffer).write_integer(static_cast(ns) % 1000, shift)); + SF_VERIFY(buf::FMTWriteManip(buffer).write_integer(static_cast(ns) % 1000, shift)); } else if (buf::TestAccess(pattern).is_same("us", 2)) { - SF_TRY(buf::Manip(pattern).forward()); + SF_VERIFY(buf::Manip(pattern).forward(2)); std::uint32_t us = static_cast(std::chrono::time_point_cast(value).time_since_epoch().count()); if (mode == TimePrintMode::Mod) us = us % 1000; else if (mode == TimePrintMode::Sub) us = us / 1000; - SF_TRY(buf::FMTWriteManip(buffer).write_integer(static_cast(us) % 1000, shift)); + SF_VERIFY(buf::FMTWriteManip(buffer).write_integer(static_cast(us) % 1000, shift)); } else if (buf::TestAccess(pattern).is_same("ms", 2)) { - SF_TRY(buf::Manip(pattern).forward()); + SF_VERIFY(buf::Manip(pattern).forward(2)); std::uint32_t ms = static_cast(std::chrono::time_point_cast(value).time_since_epoch().count()); if (mode == TimePrintMode::Mod) ms = ms % 1000; else if (mode == TimePrintMode::Sub) ms = ms / 1000000; - SF_TRY(buf::FMTWriteManip(buffer).write_integer(static_cast(ms) % 1000, shift)); + SF_VERIFY(buf::FMTWriteManip(buffer).write_integer(static_cast(ms) % 1000, shift)); } else if (buf::TestAccess(pattern).is_equal_to('s')) { - SF_TRY(buf::Manip(pattern).forward()); + SF_VERIFY(buf::Manip(pattern).forward()); std::uint32_t sec = static_cast(std::chrono::time_point_cast(value).time_since_epoch().count()); if (mode == TimePrintMode::Mod) sec = sec % 60; else if (mode == TimePrintMode::Sub) sec = sec / 1000000000; - SF_TRY(buf::FMTWriteManip(buffer).write_integer(static_cast(sec) % 1000, shift)); + SF_VERIFY(buf::FMTWriteManip(buffer).write_integer(static_cast(sec) % 1000, shift)); } else if (buf::TestAccess(pattern).is_equal_to('m')) { - SF_TRY(buf::Manip(pattern).forward()); + SF_VERIFY(buf::Manip(pattern).forward()); std::uint32_t min = static_cast(std::chrono::time_point_cast(value).time_since_epoch().count()); if (mode == TimePrintMode::Mod) min = min % 60; - SF_TRY(buf::FMTWriteManip(buffer).write_integer(static_cast(min) % 1000, shift)); + SF_VERIFY(buf::FMTWriteManip(buffer).write_integer(static_cast(min) % 1000, shift)); } else if (buf::TestAccess(pattern).is_equal_to('h')) { - SF_TRY(buf::Manip(pattern).forward()); + SF_VERIFY(buf::Manip(pattern).forward()); std::uint32_t min = static_cast(std::chrono::time_point_cast(value).time_since_epoch().count()); if (mode == TimePrintMode::Mod) min = min % 24; - SF_TRY(buf::FMTWriteManip(buffer).write_integer(static_cast(min) % 1000, shift)); + SF_VERIFY(buf::FMTWriteManip(buffer).write_integer(static_cast(min) % 1000, shift)); } return {}; @@ -77,7 +77,7 @@ namespace stream::fmt::detail { buf::FMTParamsManip(pattern).param_go_to('%', '#', '/'); return {}; })); - SF_TRY(buf::WriteManip(buffer).fast_write_string(view)); + SF_VERIFY(buf::WriteManip(buffer).fast_write_string(view)); while (!buf::Access(pattern).is_end_of_string()) { TimePrintMode mode; @@ -88,14 +88,14 @@ namespace stream::fmt::detail { else if (buf::TestAccess(pattern).is_equal_to('/')) mode = TimePrintMode::Sub; - SF_TRY(buf::Manip(pattern).forward()); - SF_TRY(write_sub_time_(value, pattern, buffer, mode)); + SF_VERIFY(buf::Manip(pattern).forward()); + SF_VERIFY(write_sub_time_(value, pattern, buffer, mode)); auto view = SF_TRY(buf::TestManip(pattern).ViewExec([&] -> std::expected { buf::FMTParamsManip(pattern).param_go_to('%', '#', '/'); return {}; })); - SF_TRY(buf::WriteManip(buffer).fast_write_string(view)); + SF_VERIFY(buf::WriteManip(buffer).fast_write_string(view)); } return {}; @@ -117,20 +117,20 @@ namespace stream::fmt { return detail::WriteTime(std::chrono::time_point>(t), buf::StreamView(executor.data.specifiers.get_as_text("pattern", "%h:%m:%s.%ms")), executor.ostream); } - SF_TRY(buf::WriteManip(executor.ostream).fast_write_integer(t.count())); + SF_VERIFY(buf::WriteManip(executor.ostream).fast_write_integer(t.count())); if constexpr (std::is_same_v, std::chrono::seconds>) { - SF_TRY(buf::ManipIO(executor.ostream).pushback('s')); + SF_VERIFY(buf::ManipIO(executor.ostream).pushback('s')); } else if constexpr (std::is_same_v, std::chrono::minutes>) { - SF_TRY(buf::ManipIO(executor.ostream).pushback('m')); + SF_VERIFY(buf::ManipIO(executor.ostream).pushback('m')); } else if constexpr (std::is_same_v, std::chrono::hours>) { - SF_TRY(buf::ManipIO(executor.ostream).pushback('h')); + SF_VERIFY(buf::ManipIO(executor.ostream).pushback('h')); } else if constexpr (std::is_same_v, std::chrono::milliseconds>) { - SF_TRY(buf::ManipIO(executor.ostream).pushback('m', 's')); + SF_VERIFY(buf::ManipIO(executor.ostream).pushback('m', 's')); } else if constexpr (std::is_same_v, std::chrono::microseconds>) { - SF_TRY(buf::ManipIO(executor.ostream).pushback('u', 's')); + SF_VERIFY(buf::ManipIO(executor.ostream).pushback('u', 's')); } else if constexpr (std::is_same_v, std::chrono::nanoseconds>) { - SF_TRY(buf::ManipIO(executor.ostream).pushback('n', 's')); + SF_VERIFY(buf::ManipIO(executor.ostream).pushback('n', 's')); } return {}; diff --git a/src/stream/fmt/serializers/std_container/tuple.hxx b/src/stream/fmt/serializers/std_container/tuple.hxx index 8dcf3e0f..7a7b0758 100644 --- a/src/stream/fmt/serializers/std_container/tuple.hxx +++ b/src/stream/fmt/serializers/std_container/tuple.hxx @@ -26,9 +26,9 @@ namespace stream::fmt::tuple_detail { template [[nodiscard]] static inline std::expected tuple_format_rec(FormatterExecutor& executor, const T& t, Args&&... args) { - SF_TRY(executor.write_type(t)); - SF_TRY(executor.ostream.pushback(',')); - SF_TRY(executor.ostream.pushback(' ')); + SF_VERIFY(executor.write_type(t)); + SF_VERIFY(executor.ostream.pushback(',')); + SF_VERIFY(executor.ostream.pushback(' ')); return tuple_format_rec(executor, args...); } } // namespace stream::fmt::tuple_detail @@ -37,7 +37,7 @@ namespace stream::fmt { template struct FormatterType, FormatterExecutor> { [[nodiscard]] static std::expected format(const std::tuple& t, FormatterExecutor& executor) { - SF_TRY(executor.ostream.pushback('<')); + SF_VERIFY(executor.ostream.pushback('<')); std::expected err = {}; std::apply([&context_executor, &err](auto&&... args) { auto&& res = tuple_detail::tuple_format_rec(context_executor, args...); @@ -45,18 +45,18 @@ namespace stream::fmt { err = res.error(); } }, t); - SF_TRY(executor.ostream.pushback('>')); + SF_VERIFY(executor.ostream.pushback('>')); } }; template struct FormatterType, FormatterExecutor> { [[nodiscard]] static std::expected format(const std::pair& t, FormatterExecutor& executor) { - SF_TRY(executor.ostream.pushback('<')); - SF_TRY(executor.write_type(t.first)); - SF_TRY(executor.ostream.pushback(':')); - SF_TRY(executor.write_type(t.second)); - SF_TRY(executor.ostream.pushback('>')); + SF_VERIFY(executor.ostream.pushback('<')); + SF_VERIFY(executor.write_type(t.first)); + SF_VERIFY(executor.ostream.pushback(':')); + SF_VERIFY(executor.write_type(t.second)); + SF_VERIFY(executor.ostream.pushback('>')); return {}; } diff --git a/src/stream/fmt/text_properties/text_properties_front.hxx b/src/stream/fmt/text_properties/text_properties_front.hxx index 28f0991f..2157ed45 100644 --- a/src/stream/fmt/text_properties/text_properties_front.hxx +++ b/src/stream/fmt/text_properties/text_properties_front.hxx @@ -4,7 +4,7 @@ namespace stream::fmt::detail { struct TextProperties::TextFront { - struct reset_front {}; + struct ResetFront {}; struct FrontID; struct Front; @@ -17,17 +17,17 @@ namespace stream::fmt::detail { static inline constexpr std::uint8_t MaxFrontID = 19; public: - std::uint8_t ID; + std::uint8_t id; - constexpr FrontID() : ID(DefaultFrontID) {} - constexpr FrontID(std::uint8_t id) : ID(id) {} + constexpr FrontID() : id(DefaultFrontID) {} + constexpr FrontID(std::uint8_t id_) : id(id_) {} public: constexpr bool operator==(const TextProperties::TextFront::FrontID& other) const { - return ID == other.ID; + return id == other.id; } - constexpr bool IsValid() const { - return ID > MinFrontID && ID < MaxFrontID; + constexpr bool is_valid() const { + return id > MinFrontID && id < MaxFrontID; } }; @@ -35,41 +35,41 @@ namespace stream::fmt::detail { struct TextProperties::TextFront::Front { public: - constexpr Front(const TextProperties::TextFront::FrontID frontId = TextProperties::TextFront::FrontID::DefaultFrontID) - : CurrentID(frontId.IsValid() ? frontId : TextProperties::TextFront::FrontID::DefaultFrontID) {} + constexpr Front(const TextProperties::TextFront::FrontID front_id = TextProperties::TextFront::FrontID::DefaultFrontID) + : current_id(front_id.is_valid() ? front_id : TextProperties::TextFront::FrontID::DefaultFrontID) {} public: - FrontID CurrentID; + FrontID current_id; public: void modify_reset() { *this = Front{}; } - void apply(const TextProperties::TextFront::reset_front&) { + void apply(const TextProperties::TextFront::ResetFront&) { modify_reset(); } void apply(const TextProperties::TextFront::Front& given) { *this = given; } void apply(const TextProperties::TextFront::FrontID& given) { - CurrentID = given; + current_id = given; } public: - bool need_modif(const TextProperties::TextFront::reset_front&) { + bool need_modif(const TextProperties::TextFront::ResetFront&) { return true; } bool need_modif(const TextProperties::TextFront::Front& given) { return *this != given; } bool need_modif(const TextProperties::TextFront::FrontID& given) { - return CurrentID != given; + return current_id != given; } }; inline bool operator==(const TextProperties::TextFront::Front& lhs, const TextProperties::TextFront::Front& rhs) { - return lhs.CurrentID == rhs.CurrentID; + return lhs.current_id == rhs.current_id; } template @@ -78,7 +78,7 @@ namespace stream::fmt::detail { template struct TextPropertiesFrontIsapplyType { using BaseType = get_base_type; - static constexpr bool value = std::is_same_v || std::is_same_v || + static constexpr bool value = std::is_same_v || std::is_same_v || std::is_same_v; }; diff --git a/src/stream/tester/test_suite/test_suite.hxx b/src/stream/tester/test_suite/test_suite.hxx index d389878b..d3112613 100644 --- a/src/stream/tester/test_suite/test_suite.hxx +++ b/src/stream/tester/test_suite/test_suite.hxx @@ -169,9 +169,9 @@ namespace stream::fmt { template struct FormatterType { [[nodiscard]] static std::expected format(const stream::tester::detail::Test& t, FormatterExecutor& executor) { - SF_TRY(buf::WriteManip(executor.ostream).fast_write_string(t.link.name)); - SF_TRY(buf::WriteManip(executor.ostream).fast_write_string_literal("::")); - SF_TRY(buf::WriteManip(executor.ostream).fast_write_string(t.name)); + SF_VERIFY(buf::WriteManip(executor.ostream).fast_write_string(t.link.name)); + SF_VERIFY(buf::WriteManip(executor.ostream).fast_write_string_literal("::")); + SF_VERIFY(buf::WriteManip(executor.ostream).fast_write_string(t.name)); return {}; } }; @@ -194,28 +194,28 @@ namespace stream::fmt { template struct FormatterType { [[nodiscard]] static std::expected format(const stream::tester::detail::TestStatusBank& status_bank, FormatterExecutor& executor) { - SF_TRY(buf::WriteManip(executor.ostream).fast_write_string_literal("tests_done ")); - SF_TRY(executor.run("{:C:white}", status_bank.tests_done)); + SF_VERIFY(buf::WriteManip(executor.ostream).fast_write_string_literal("tests_done ")); + SF_VERIFY(executor.run("{:C:white}", status_bank.tests_done)); - SF_TRY(buf::WriteManip(executor.ostream).fast_write_string_literal(" | testsOK ")); + SF_VERIFY(buf::WriteManip(executor.ostream).fast_write_string_literal(" | testsOK ")); if (status_bank.tests_ok == status_bank.tests_done) { - SF_TRY(executor.run("{:C:green}", status_bank.tests_ok)); + SF_VERIFY(executor.run("{:C:green}", status_bank.tests_ok)); } else { - SF_TRY(executor.run("{:C:yellow}", status_bank.tests_ok)); + SF_VERIFY(executor.run("{:C:yellow}", status_bank.tests_ok)); } - SF_TRY(buf::WriteManip(executor.ostream).fast_write_string_literal(" | testsFAIL ")); + SF_VERIFY(buf::WriteManip(executor.ostream).fast_write_string_literal(" | testsFAIL ")); if (status_bank.tests_failed == 0) { - SF_TRY(executor.run("{:C:green}", status_bank.tests_failed)); + SF_VERIFY(executor.run("{:C:green}", status_bank.tests_failed)); } else { - SF_TRY(executor.run("{:C:red}", status_bank.tests_failed)); + SF_VERIFY(executor.run("{:C:red}", status_bank.tests_failed)); } - SF_TRY(buf::WriteManip(executor.ostream).fast_write_string_literal(" | TestCrash ")); + SF_VERIFY(buf::WriteManip(executor.ostream).fast_write_string_literal(" | TestCrash ")); if (status_bank.tests_crash == 0) { - SF_TRY(executor.run("{:C:green}", status_bank.tests_crash)); + SF_VERIFY(executor.run("{:C:green}", status_bank.tests_crash)); } else { - SF_TRY(executor.run("{:C:magenta}", status_bank.tests_crash)); + SF_VERIFY(executor.run("{:C:magenta}", status_bank.tests_crash)); } return {}; diff --git a/tests/BUILD.bazel b/tests/BUILD.bazel index bb2a239d..7009bb0c 100644 --- a/tests/BUILD.bazel +++ b/tests/BUILD.bazel @@ -6,7 +6,7 @@ cc_test( name = "units", srcs = [ "tests.cxx" ] + glob([ "fmt/*.hxx", "fmt/*.cxx" ]), copts = select({ - "@rules_cc//cc/compiler:msvc-cl": ["/std:latest"], + "@rules_cc//cc/compiler:msvc-cl": ["/std:c++latest"], "//conditions:default": [ "-std=c++23", "-Wall", "-Wextra", "-Wpedantic", From 1a9c5f8854c8106ce9b82967879141a4122d330b Mon Sep 17 00:00:00 2001 From: Sacha Bellier Date: Mon, 24 Mar 2025 20:52:14 +0100 Subject: [PATCH 29/42] feat: remove expected :( `need c++23; slower perf; exception aren't too bad finally...` --- .buildkite/linux_amd64.yml | 4 +- BUILD.bazel | 2 +- README.md | 2 +- examples/hello/BUILD.bazel | 2 +- src/stream/core/prelude.hxx | 25 +- src/stream/flog/backends/basic_logger.hxx | 96 ++++---- .../flog/backends/logger_multi_sink_fast.hxx | 17 +- .../flog/backends/logger_multi_sink_safe.hxx | 25 +- src/stream/flog/detail/detail.hxx | 12 +- src/stream/flog/frontends/xlogger.hxx | 31 ++- src/stream/flog/sinks/file_sink.hxx | 26 +- src/stream/flog/sinks/logger_sink.hxx | 51 ++-- src/stream/fmt/buf/fmt_manip_io.hxx | 36 +-- src/stream/fmt/buf/fmt_read_manip.hxx | 87 ++++--- src/stream/fmt/buf/fmt_write_manip.hxx | 82 +++---- src/stream/fmt/buf/manip.hxx | 52 ++-- src/stream/fmt/buf/manip_io.hxx | 40 ++- src/stream/fmt/buf/read_manip.hxx | 34 ++- src/stream/fmt/buf/stream.hxx | 30 ++- src/stream/fmt/buf/streamio.hxx | 21 +- .../basic_streamio_manager.hxx | 18 +- .../dynamic_streamio_manager.hxx | 38 ++- .../given_streamio_manager.hxx | 4 +- .../static_streamio_manager.hxx | 4 +- src/stream/fmt/buf/test_manip.hxx | 51 ++-- .../fmt/buf/utils/buffer_globber_manip.hxx | 42 ++-- .../fmt/buf/utils/buffer_shift_manip.hxx | 35 ++- src/stream/fmt/buf/utils/buffer_utils.hxx | 62 +++-- src/stream/fmt/buf/write_manip.hxx | 62 ++--- .../basic_context/basic_args_interface.hxx | 44 ++-- .../context/basic_context/basic_context.hxx | 62 +++-- .../basic_context_parse_impl.hxx | 215 ++++++++-------- .../text_properties_executor.hxx | 48 ++-- .../basic_context/text_properties_manager.cxx | 40 ++- .../basic_context/text_properties_manager.hxx | 116 ++++----- .../text_properties_manager_impl.hxx | 230 +++++++----------- .../basic_formatter_executor.hxx | 42 ++-- .../formatter_executor/format_basics_impl.hxx | 89 +++---- .../format_text_properties_impl.hxx | 14 +- .../formatter_executor/formatter_args.hxx | 48 ++-- .../formatter_text_properties_executor.hxx | 48 ++-- ...ormatter_text_properties_executor_ansi.hxx | 48 ++-- .../formatter_executor/formatter_type.hxx | 27 +- .../context/formatter_executor/index_args.hxx | 8 +- .../context/formatter_executor/named_args.hxx | 8 +- .../formatter_executor/std_enumerable.hxx | 44 ++-- .../formatter_executor/utility_functions.hxx | 135 +++------- .../parser_executor/basic_parser_executor.hxx | 33 +-- .../parser_executor/parse_basics_impl.hxx | 33 ++- .../parse_text_properties_impl.hxx | 14 +- .../context/parser_executor/parser_args.hxx | 48 ++-- .../parser_text_properties_executor.hxx | 94 ++----- .../parser_text_properties_executor_ansi.hxx | 96 ++++---- .../parser_executor/utility_functions.hxx | 4 +- src/stream/fmt/detail/fmt_result.hxx | 44 ---- src/stream/fmt/detail/indent_handlers.hxx | 4 +- src/stream/fmt/detail/prelude.hxx | 1 - src/stream/fmt/detail/specifiers.hxx | 12 +- .../fmt/serializers/compilation_data.hxx | 12 +- src/stream/fmt/serializers/format_chrono.hxx | 91 ++++--- src/stream/fmt/serializers/format_stdlib.hxx | 16 +- .../fmt/serializers/std_container/array.hxx | 2 +- .../fmt/serializers/std_container/deque.hxx | 2 +- .../std_container/forward_list.hxx | 2 +- .../fmt/serializers/std_container/list.hxx | 2 +- .../fmt/serializers/std_container/map.hxx | 4 +- .../fmt/serializers/std_container/queue.hxx | 4 +- .../fmt/serializers/std_container/set.hxx | 4 +- .../fmt/serializers/std_container/stack.hxx | 2 +- .../fmt/serializers/std_container/tuple.hxx | 36 ++- .../std_container/unordered_map.hxx | 4 +- .../std_container/unordered_set.hxx | 4 +- .../fmt/serializers/std_container/vector.hxx | 2 +- .../text_properties/text_properties_color.hxx | 16 +- src/stream/json/detail.hxx | 20 +- src/stream/json/json_factory.hxx | 4 +- src/stream/json/json_formatter.hxx | 6 +- src/stream/json/json_objects.hxx | 25 +- src/stream/json/json_parser.cxx | 4 +- src/stream/json/json_serializer.hxx | 86 ++++--- src/stream/profiler/event.hxx | 2 +- src/stream/profiler/profiler_factory.cxx | 2 +- src/stream/tester/test_suite/basic_test.hxx | 47 +--- src/stream/tester/test_suite/test_suite.cxx | 10 +- src/stream/tester/test_suite/test_suite.hxx | 40 ++- tests/BUILD.bazel | 2 +- tests/fmt/complex_pattern.cxx | 2 +- tests/fmt/globber.cxx | 26 +- tests/fmt/limits.cxx | 52 ++-- tests/fmt/text_properties.cxx | 4 +- 90 files changed, 1383 insertions(+), 1792 deletions(-) delete mode 100644 src/stream/fmt/detail/fmt_result.hxx diff --git a/.buildkite/linux_amd64.yml b/.buildkite/linux_amd64.yml index fa315d22..a3563f8b 100644 --- a/.buildkite/linux_amd64.yml +++ b/.buildkite/linux_amd64.yml @@ -4,8 +4,8 @@ agents: steps: - label: ":bazel: Build and Test on gcc (W asan)" commands: - - CC=gcc-14 bazelisk build --features=asan //tests:units - - CC=gcc-14 bazelisk test --features=asan //tests:units + - CC=gcc bazelisk build --features=asan //tests:units + - CC=gcc bazelisk test --features=asan //tests:units - label: ":bazel: Build and Test on Clang (W asan)" commands: diff --git a/BUILD.bazel b/BUILD.bazel index 4cdfc025..6fd2d7ba 100644 --- a/BUILD.bazel +++ b/BUILD.bazel @@ -9,7 +9,7 @@ cc_library( includes = [ "src/" ], copts = select({ "@rules_cc//cc/compiler:msvc-cl": ["/std:c++latest"], - "//conditions:default": ["-std=c++23"], + "//conditions:default": ["-std=c++20"], }), strip_include_prefix = "src", include_prefix = "stream", diff --git a/README.md b/README.md index fd4e2b5a..9cf86239 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ # stream -stream is a C++23 String Formatter, like [<fmt>](https://github.com/fmtlib/fmt) +stream is a C++20 String Formatter, like [<fmt>](https://github.com/fmtlib/fmt) Using this formatter, it define others functionalities: - Logger like [spdlog](https://github.com/gabime/spdlog) - Json Serializer diff --git a/examples/hello/BUILD.bazel b/examples/hello/BUILD.bazel index c8b359b7..dbcd0d36 100644 --- a/examples/hello/BUILD.bazel +++ b/examples/hello/BUILD.bazel @@ -8,7 +8,7 @@ cc_binary( includes = [ "" ], copts = select({ "@rules_cc//cc/compiler:msvc-cl": ["/std:c++latest"], - "//conditions:default": ["-std=c++23"], + "//conditions:default": ["-std=c++20"], }), linkopts = select({ "@rules_cc//cc/compiler:msvc-cl": [""], diff --git a/src/stream/core/prelude.hxx b/src/stream/core/prelude.hxx index fa2f477c..c8822796 100644 --- a/src/stream/core/prelude.hxx +++ b/src/stream/core/prelude.hxx @@ -29,29 +29,6 @@ #define STREAMFORMAT_DEBUGBREAK() #endif -// https://github.com/SerenityOS/serenity/blob/50642f85ac547a3caee353affcb08872cac49456/AK/Try.h #include -#include +#include #include - -namespace stream::detail { - template - T forward_error(T t) { - return std::forward(t); - } -} // namespace stream::detail - -#define SF_TRY(exp) \ - ({ \ - auto __expected = exp; \ - if (not __expected) [[unlikely]] \ - return std::unexpected(stream::detail::forward_error(__expected.error())); \ - __expected.value(); \ - }); - -#define SF_VERIFY(exp) \ - { \ - auto __expected = exp; \ - if (not __expected) [[unlikely]] \ - return std::unexpected(stream::detail::forward_error(__expected.error())); \ - } diff --git a/src/stream/flog/backends/basic_logger.hxx b/src/stream/flog/backends/basic_logger.hxx index 808e20ad..7794bd35 100644 --- a/src/stream/flog/backends/basic_logger.hxx +++ b/src/stream/flog/backends/basic_logger.hxx @@ -13,101 +13,91 @@ namespace stream::flog::detail { using SeverityValueType = typename Severity::Value; public: - BasicLoggerImpl() : name_("logger_"), m_Severity(Severity::Value::DefaultSeverity), m_Stream(std::cout), start_time_(std::chrono::high_resolution_clock::now()) { - ResetPattern(); + BasicLoggerImpl() : name_("logger_"), severity_(Severity::Value::DefaultSeverity), stream_(std::cout), start_time_(std::chrono::high_resolution_clock::now()) { + reset_pattern(); } explicit BasicLoggerImpl(const std::string_view& name, typename Severity::Value severity = Severity::Value::DefaultSeverity, std::ostream& stream = std::cout) : name_(name), - m_Severity(severity), - m_Stream(stream), - preFormatStreamIOManager(64), - fullFormatStreamIOManager(64), + severity_(severity), + stream_(stream), + pre_format_stream_io_manager_(64), + full_format_stream_io_manager_(64), start_time_(std::chrono::high_resolution_clock::now()) { - ResetPattern(); + reset_pattern(); } explicit BasicLoggerImpl(const std::string_view& name, const std::string_view& format, typename Severity::Value severity = Severity::Value::DefaultSeverity, std::ostream& stream = std::cout) : name_(name), - m_Severity(severity), - m_Stream(stream), - preFormatStreamIOManager(64), - fullFormatStreamIOManager(64), + severity_(severity), + stream_(stream), + pre_format_stream_io_manager_(64), + full_format_stream_io_manager_(64), start_time_(std::chrono::high_resolution_clock::now()) { - SetPattern(format); + set_pattern(format); } virtual ~BasicLoggerImpl() = default; public: void set_severity(const SeverityValueType& severity) { - m_Severity = severity; + severity_ = severity; } - void set_name(const std::string& name) { - name_ = name; - } - void set_name(std::string&& name) { + void set_name(std::string name) { name_ = std::move(name); } - void SetRealPattern(std::string_view pattern) { - m_Pattern = pattern; - } - void set_real_pattern_strmv(std::string&& pattern) { - m_Pattern = std::move(pattern); + void set_real_pattern(std::string pattern) { + pattern_ = std::move(pattern); } - void SetPattern(std::string_view pattern) { - m_Pattern = "{color}"; - m_Pattern += pattern; + void set_pattern(std::string_view pattern) { + pattern_ = "{color}"; + pattern_ += pattern; } - void ResetPattern() { - SetPattern("[{time:pattern='%h:%m:%s:%ms'}] {name} >> {data}"); + void reset_pattern() { + set_pattern("[{logtime:pattern='default'}] {name} >> {data}"); } private: std::string name_; - SeverityValueType m_Severity; - std::ostream& m_Stream; - std::string m_Pattern; - fmt::buf::DynamicStreamIOManager preFormatStreamIOManager; - fmt::buf::DynamicStreamIOManager fullFormatStreamIOManager; + SeverityValueType severity_; + std::ostream& stream_; + std::string pattern_; + fmt::buf::DynamicStreamIOManager pre_format_stream_io_manager_; + fmt::buf::DynamicStreamIOManager full_format_stream_io_manager_; std::chrono::time_point start_time_; public: void NewLine() { - m_Stream.write("\n", 1); + stream_.write("\n", 1); } template requires fmt::buf::convertible_to_buffer_info_view - [[nodiscard]] std::expected log(const SeverityValueType& severity, Format&& format, Args&&... args) { - if (severity < m_Severity) return {}; + void log(const SeverityValueType& severity, Format&& format, Args&&... args) { + if (severity < severity_) return; - std::chrono::nanoseconds logTime = std::chrono::high_resolution_clock::now() - start_time_; + std::chrono::nanoseconds log_time = std::chrono::high_resolution_clock::now() - start_time_; - SF_VERIFY(fmt::detail::format_in_manager(preFormatStreamIOManager, false, fmt::buf::StreamView(m_Pattern), FORMAT_SV("time", logTime), FORMAT_SV("name", name_), - FORMAT_SV("data", flog::AddIndentInFormat(format)))); + fmt::detail::format_in_manager(pre_format_stream_io_manager_, false, fmt::buf::StreamView(pattern_), FORMAT_SV("logtime", log_time), FORMAT_SV("name", name_), + FORMAT_SV("data", flog::AddIndentInFormat(format))); - SF_VERIFY(fmt::detail::format_in_manager(fullFormatStreamIOManager, true, preFormatStreamIOManager.get_last_generated_buffer_info_view(), std::forward(args)..., - FORMAT_SV("color", severity))); - m_Stream.write(fullFormatStreamIOManager.get_buffer(), static_cast(fullFormatStreamIOManager.get_last_generated_data_size())); - m_Stream.flush(); - - return {}; + fmt::detail::format_in_manager(full_format_stream_io_manager_, true, pre_format_stream_io_manager_.get_last_generated_buffer_info_view(), std::forward(args)..., + FORMAT_SV("color", severity)); + stream_.write(full_format_stream_io_manager_.get_buffer(), static_cast(full_format_stream_io_manager_.get_last_generated_data_size())); + stream_.flush(); } template - [[nodiscard]] std::expected log(const SeverityValueType& severity, T&& t) { - if (severity < m_Severity) return {}; - - std::chrono::nanoseconds logTime = std::chrono::high_resolution_clock::now() - start_time_; + void log(const SeverityValueType& severity, T&& t) { + if (severity < severity_) return; - SF_VERIFY(fmt::detail::format_in_manager(fullFormatStreamIOManager, true, fmt::buf::StreamView(m_Pattern), FORMAT_SV("data", t), FORMAT_SV("color", severity), - FORMAT_SV("time", logTime), FORMAT_SV("name", name_))); - m_Stream.write(fullFormatStreamIOManager.get_buffer(), static_cast(fullFormatStreamIOManager.get_last_generated_data_size())); - m_Stream.flush(); + std::chrono::nanoseconds log_time = std::chrono::high_resolution_clock::now() - start_time_; - return {}; + fmt::detail::format_in_manager(full_format_stream_io_manager_, true, fmt::buf::StreamView(pattern_), FORMAT_SV("data", t), FORMAT_SV("color", severity), + FORMAT_SV("logtime", log_time), FORMAT_SV("name", name_)); + stream_.write(full_format_stream_io_manager_.get_buffer(), static_cast(full_format_stream_io_manager_.get_last_generated_data_size())); + stream_.flush(); } }; } // namespace stream::flog::detail diff --git a/src/stream/flog/backends/logger_multi_sink_fast.hxx b/src/stream/flog/backends/logger_multi_sink_fast.hxx index b057f48d..f8f752e4 100644 --- a/src/stream/flog/backends/logger_multi_sink_fast.hxx +++ b/src/stream/flog/backends/logger_multi_sink_fast.hxx @@ -34,38 +34,33 @@ namespace stream::flog::detail { public: template requires fmt::buf::convertible_to_buffer_info_view - [[nodiscard]] std::expected log(const SeverityValueType& severity, const Format& format, Args&&... args) { - std::chrono::nanoseconds logTime = std::chrono::high_resolution_clock::now() - start_time_; + void log(const SeverityValueType& severity, const Format& format, Args&&... args) { + std::chrono::nanoseconds log_time = std::chrono::high_resolution_clock::now() - start_time_; fmt::buf::DynamicStreamIOManager manager(256); auto format_buffer = fmt::detail::format_in_manager(manager, false, format, std::forward(args)...); - if (format_buffer.has_value() == false) return std::unexpected(format_buffer.error()); for (auto& sink : sinks_) if (sink->need_to_log(severity)) { - SF_VERIFY(sink->format_and_write_to_sink(sink->get_pattern(severity), logTime, name_, static_cast>(*format_buffer.value()))); + sink->format_and_write_to_sink(sink->get_pattern(severity), log_time, name_, static_cast>(*format_buffer)); } await(severity); - return {}; } template - [[nodiscard]] std::expected log(const SeverityValueType& severity, T&& t) { - std::chrono::nanoseconds logTime = std::chrono::high_resolution_clock::now() - start_time_; + void log(const SeverityValueType& severity, T&& t) { + std::chrono::nanoseconds log_time = std::chrono::high_resolution_clock::now() - start_time_; fmt::buf::DynamicStreamIOManager manager(256); auto format_buffer = fmt::detail::format_in_manager(manager, false, std::forward(t)); - if (format_buffer.has_value() == false) return std::unexpected(format_buffer.error()); for (auto& sink : sinks_) if (sink->need_to_log(severity)) { - SF_VERIFY(sink->format_and_write_to_sink(sink->get_pattern(severity), logTime, name_, static_cast>(*format_buffer.value()))); + sink->format_and_write_to_sink(sink->get_pattern(severity), log_time, name_, static_cast>(*format_buffer)); } await(severity); - - return {}; } }; } // namespace stream::flog::detail diff --git a/src/stream/flog/backends/logger_multi_sink_safe.hxx b/src/stream/flog/backends/logger_multi_sink_safe.hxx index 54f2ea8a..a3e70190 100644 --- a/src/stream/flog/backends/logger_multi_sink_safe.hxx +++ b/src/stream/flog/backends/logger_multi_sink_safe.hxx @@ -34,8 +34,8 @@ namespace stream::flog::detail { public: template requires fmt::buf::convertible_to_buffer_info_view - [[nodiscard]] std::expected log(const SeverityValueType& severity, const Format& format, Args&&... args) { - std::chrono::nanoseconds logTime = std::chrono::high_resolution_clock::now() - start_time_; + void log(const SeverityValueType& severity, const Format& format, Args&&... args) { + std::chrono::nanoseconds log_time = std::chrono::high_resolution_clock::now() - start_time_; // FIXME maybe add : name ; indent ??? for (auto& sink : sinks_) { @@ -44,36 +44,31 @@ namespace stream::flog::detail { fmt::buf::DynamicStreamIOManager manager_format(256); auto format_pattern_str = - fmt::detail::format_in_manager(manager_pattern, false, std::string_view(sink->get_pattern(severity)), FORMAT_SV("time", logTime), + fmt::detail::format_in_manager(manager_pattern, false, std::string_view(sink->get_pattern(severity)), FORMAT_SV("logtime", log_time), FORMAT_SV("name", FutureConcatNameAndSinkName(name_)), FORMAT_SV("data", flog::AddIndentInFormat(format))); - if (format_pattern_str.has_value() == false) return std::unexpected(format_pattern_str.error()); - auto format_format_str = fmt::detail::format_in_manager(manager_format, false, static_cast(*format_pattern_str.value()), - std::forward(args)..., FORMAT_SV("sink", sink->get_name()), FORMAT_SV("color", severity)); - if (format_format_str.has_value() == false) return std::unexpected(format_format_str.error()); - SF_VERIFY(sink->WriteToSink(static_cast>(*format_format_str.value()))); + auto format_format_str = fmt::detail::format_in_manager(manager_format, false, static_cast(*format_pattern_str), std::forward(args)..., + FORMAT_SV("sink", sink->get_name()), FORMAT_SV("color", severity)); + sink->WriteToSink(static_cast>(*format_format_str)); } } await(severity); - return {}; } template - [[nodiscard]] std::expected log(const SeverityValueType& severity, T&& t) { - std::chrono::nanoseconds logTime = std::chrono::high_resolution_clock::now() - start_time_; + void log(const SeverityValueType& severity, T&& t) { + std::chrono::nanoseconds log_time = std::chrono::high_resolution_clock::now() - start_time_; for (auto& sink : sinks_) { if (sink->need_to_log(severity)) { fmt::buf::DynamicStreamIOManager manager(256); - auto format_buffer = fmt::detail::format_in_manager(manager, false, std::string_view(sink->get_pattern(severity)), FORMAT_SV("time", logTime), + auto format_buffer = fmt::detail::format_in_manager(manager, false, std::string_view(sink->get_pattern(severity)), FORMAT_SV("logtime", log_time), FORMAT_SV("name", ConcatNameAndSinkName(name_, sink->get_name())), FORMAT_SV("data", t)); - if (format_buffer.has_value() == false) return std::unexpected(format_buffer.error()); - SF_VERIFY(sink->WriteToSink(static_cast>(*format_buffer.value()))); + sink->WriteToSink(static_cast>(*format_buffer)); } } await(severity); - return {}; } }; } // namespace stream::flog::detail diff --git a/src/stream/flog/detail/detail.hxx b/src/stream/flog/detail/detail.hxx index 2be1a146..aa4a2117 100644 --- a/src/stream/flog/detail/detail.hxx +++ b/src/stream/flog/detail/detail.hxx @@ -14,14 +14,14 @@ namespace stream::flog { template struct ConcatNameAndSinkName { - ConcatNameAndSinkName(const std::basic_string& loggerName, const std::basic_string& sinkName) : LoggerName(loggerName), SinkName(sinkName) {} + ConcatNameAndSinkName(const std::basic_string& logger_name, const std::basic_string& sinkName) : LoggerName(logger_name), SinkName(sinkName) {} const std::basic_string& LoggerName; const std::basic_string& SinkName; }; template struct FutureConcatNameAndSinkName { - FutureConcatNameAndSinkName(const std::basic_string& loggerName) : LoggerName(loggerName) {} + FutureConcatNameAndSinkName(const std::basic_string& logger_name) : LoggerName(logger_name) {} const std::basic_string& LoggerName; }; } // namespace stream::flog @@ -29,22 +29,22 @@ namespace stream::flog { namespace stream::fmt { template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static std::expected format(const stream::flog::AddIndentInFormat& format, FormatterExecutor& executor) { - SF_VERIFY(buf::WriteManip(executor.ostream).fast_write_string_literal("{K:indent}")); + static void format(const stream::flog::AddIndentInFormat& format, FormatterExecutor& executor) { + buf::WriteManip(executor.ostream).fast_write_string_literal("{K:indent}"); return executor.write_type(format.format); } }; template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static std::expected format(const stream::flog::ConcatNameAndSinkName& names, FormatterExecutor& executor) { + static void format(const stream::flog::ConcatNameAndSinkName& names, FormatterExecutor& executor) { return executor.run(names.LoggerName, FORMAT_SV("sink", names.SinkName)); } }; template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static std::expected format(const stream::flog::FutureConcatNameAndSinkName& names, FormatterExecutor& executor) { + static void format(const stream::flog::FutureConcatNameAndSinkName& names, FormatterExecutor& executor) { return executor.run(names.LoggerName, "sink"); } }; diff --git a/src/stream/flog/frontends/xlogger.hxx b/src/stream/flog/frontends/xlogger.hxx index bd7d8e22..614b68b8 100644 --- a/src/stream/flog/frontends/xlogger.hxx +++ b/src/stream/flog/frontends/xlogger.hxx @@ -77,12 +77,12 @@ namespace stream::flog::detail { public: template requires fmt::buf::convertible_to_buffer_info_view - [[nodiscard]] std::expected log(Severity status, Format&& format, Args&&... args) { + void log(Severity status, Format&& format, Args&&... args) { return Master::template log(status, format, std::forward(args)...); } template - [[nodiscard]] std::expected log(Severity status, T&& t) { + void log(Severity status, T&& t) { return Master::template log(status, std::forward(t)); } @@ -90,58 +90,58 @@ namespace stream::flog::detail { /////---------- logger Severity with array as format ----------///// template requires fmt::buf::convertible_to_buffer_info_view - inline std::expected trace(Format&& format, Args&&... args) { + inline void trace(Format&& format, Args&&... args) { return log(LogSeverity::Trace, format, std::forward(args)...); } template requires fmt::buf::convertible_to_buffer_info_view - inline std::expected debug(Format&& format, Args&&... args) { + inline void debug(Format&& format, Args&&... args) { return log(LogSeverity::Debug, format, std::forward(args)...); } template requires fmt::buf::convertible_to_buffer_info_view - inline std::expected info(Format&& format, Args&&... args) { + inline void info(Format&& format, Args&&... args) { return log(LogSeverity::Info, format, std::forward(args)...); } template requires fmt::buf::convertible_to_buffer_info_view - inline std::expected warn(Format&& format, Args&&... args) { + inline void warn(Format&& format, Args&&... args) { return log(LogSeverity::Warn, format, std::forward(args)...); } template requires fmt::buf::convertible_to_buffer_info_view - inline std::expected error(Format&& format, Args&&... args) { + inline void error(Format&& format, Args&&... args) { return log(LogSeverity::Error, format, std::forward(args)...); } template requires fmt::buf::convertible_to_buffer_info_view - inline std::expected fatal(Format&& format, Args&&... args) { + inline void fatal(Format&& format, Args&&... args) { return log(LogSeverity::Fatal, format, std::forward(args)...); } /////---------- NO-FORMAT logger Severity ----------///// template - inline std::expected trace(T&& t) { + inline void trace(T&& t) { return log(LogSeverity::Trace, std::forward(t)); } template - inline std::expected debug(T&& t) { + inline void debug(T&& t) { return log(LogSeverity::Debug, std::forward(t)); } template - inline std::expected info(T&& t) { + inline void info(T&& t) { return log(LogSeverity::Info, std::forward(t)); } template - inline std::expected warn(T&& t) { + inline void warn(T&& t) { return log(LogSeverity::Warn, std::forward(t)); } template - inline std::expected error(T&& t) { + inline void error(T&& t) { return log(LogSeverity::Error, std::forward(t)); } template - inline std::expected fatal(T&& t) { + inline void fatal(T&& t) { return log(LogSeverity::Fatal, std::forward(t)); } }; @@ -150,7 +150,7 @@ namespace stream::flog::detail { namespace stream::fmt { template struct FormatterType { - [[nodiscard]] static std::expected format(const stream::flog::LogSeverity::Value t, FormatterExecutor& executor) { + static void format(const stream::flog::LogSeverity::Value t, FormatterExecutor& executor) { executor.data.keep_new_style = true; switch (t) { case stream::flog::LogSeverity::Trace: @@ -172,7 +172,6 @@ namespace stream::fmt { return FormatterType::format(detail::TextProperties::TextColor::BasicColorFG::BrightMagenta, executor); } - return {}; } }; } // namespace stream::fmt diff --git a/src/stream/flog/sinks/file_sink.hxx b/src/stream/flog/sinks/file_sink.hxx index 9d9d55f9..9b729483 100644 --- a/src/stream/flog/sinks/file_sink.hxx +++ b/src/stream/flog/sinks/file_sink.hxx @@ -16,26 +16,26 @@ namespace stream::flog::Sinks { using typename Base::PatternType; public: - BasicConsoleSink(std::basic_ostream& stream, NameType&& name) : Base(std::forward(name)), m_Stream(stream) {} + BasicConsoleSink(std::basic_ostream& stream, NameType&& name) : Base(std::forward(name)), stream_(stream) {} - BasicConsoleSink(std::basic_ostream& stream, NameType&& name, detail::AsyncSink isAsync) : Base(std::forward(name), isAsync), m_Stream(stream) {} + BasicConsoleSink(std::basic_ostream& stream, NameType&& name, detail::AsyncSink isAsync) : Base(std::forward(name), isAsync), stream_(stream) {} ~BasicConsoleSink() override = default; public: std::basic_ostream& GetStream() { - return m_Stream; + return stream_; } protected: void WriteImpl(const BufferType& bufferToPrint) override { - m_Stream.write(bufferToPrint.data(), bufferToPrint.size()); - m_Stream.write("\n", 1); - m_Stream.flush(); + stream_.write(bufferToPrint.data(), bufferToPrint.size()); + stream_.write("\n", 1); + stream_.flush(); } private: - std::basic_ostream& m_Stream; + std::basic_ostream& stream_; }; template @@ -48,23 +48,23 @@ namespace stream::flog::Sinks { public: BasicFileSink(const std::filesystem::path& filePath, NameType&& name, detail::AsyncSink isAsync) - : Base(std::forward(name), isAsync), m_Stream(filePath, std::ios::out) {} + : Base(std::forward(name), isAsync), stream_(filePath, std::ios::out) {} ~BasicFileSink() override = default; public: std::basic_ostream& GetStream() { - return m_Stream; + return stream_; } protected: void WriteImpl(const BufferType& bufferToPrint) override { - m_Stream.write(bufferToPrint.data(), bufferToPrint.size()); - m_Stream.write("\n", 1); - m_Stream.flush(); + stream_.write(bufferToPrint.data(), bufferToPrint.size()); + stream_.write("\n", 1); + stream_.flush(); } private: - std::basic_ofstream m_Stream; + std::basic_ofstream stream_; }; } // namespace stream::flog::Sinks diff --git a/src/stream/flog/sinks/logger_sink.hxx b/src/stream/flog/sinks/logger_sink.hxx index 8728c086..00ec0d7a 100644 --- a/src/stream/flog/sinks/logger_sink.hxx +++ b/src/stream/flog/sinks/logger_sink.hxx @@ -21,25 +21,24 @@ namespace stream::flog::detail { using SeverityValueType = typename Severity::Value; public: - BasicLoggerSink(NameType&& name) : name(std::forward(name)), IsAsync(AsyncSink::Sync) {} - - BasicLoggerSink(NameType&& name, AsyncSink isAsync) : name(std::forward(name)), IsAsync(isAsync) {} + BasicLoggerSink(NameType name) : name(std::move(name)), is_async(AsyncSink::Sync) {} + BasicLoggerSink(NameType name, AsyncSink isAsync) : name(std::move(name)), is_async(isAsync) {} virtual ~BasicLoggerSink() = default; public: NameType name = ""; - PatternType Pattern = "[{time:pattern='%h:%m:%s:%ms'}] {name} >> {data}"; - SeverityValueType SinkSeverity{SeverityValueType::DefaultSeverity}; - typename Severity::PatternOverride SeverityPatternOverride; - AsyncSink IsAsync; + PatternType pattern = "[{logtime:pattern='default'}] {name} >> {data}"; + SeverityValueType sink_severity{SeverityValueType::DefaultSeverity}; + typename Severity::PatternOverride severity_pattern_override; + AsyncSink is_async; protected: - std::future m_AsyncWaiter; + std::future async_waiter_; public: bool need_to_log(const SeverityValueType& severity) { - return severity >= SinkSeverity; + return severity >= sink_severity; } void WriteToSink(const SeverityValueType& severity, const BufferType& bufferToPrint) { if (need_to_log(severity)) WriteToSink(bufferToPrint); @@ -47,8 +46,8 @@ namespace stream::flog::detail { public: PatternTransferType get_pattern(const typename Severity::Value& severity) const { - PatternTransferType customPattern = SeverityPatternOverride.get_pattern(severity); - if (customPattern.data() == nullptr || customPattern.size() == 0) return Pattern; + PatternTransferType customPattern = severity_pattern_override.get_pattern(severity); + if (customPattern.data() == nullptr || customPattern.size() == 0) return pattern; return customPattern; } @@ -60,11 +59,11 @@ namespace stream::flog::detail { WriteImpl(bufferToPrint); } void WriteToSinkAsync(const BufferType& bufferToPrint) { - m_AsyncWaiter = std::async(std::launch::async, &BasicLoggerSink::WriteToSinkSync, this, bufferToPrint); + async_waiter_ = std::async(std::launch::async, &BasicLoggerSink::WriteToSinkSync, this, bufferToPrint); } void WriteToSink(const BufferType& bufferToPrint) { - if (IsAsync == AsyncSink::Sync) + if (is_async == AsyncSink::Sync) WriteToSinkSync(bufferToPrint); else WriteToSinkAsync(bufferToPrint); @@ -72,32 +71,26 @@ namespace stream::flog::detail { public: void wait_until_finished_to_write() { - if (IsAsync == AsyncSink::Async) return m_AsyncWaiter.get(); + if (is_async == AsyncSink::Async) return async_waiter_.get(); } - [[nodiscard]] std::expected FormatAndWriteToSinkSync(PatternTransferType pattern, const std::chrono::nanoseconds& logTime, const NameType& loggerName, - const BufferType& format_buffer) { + void FormatAndWriteToSinkSync(PatternTransferType pattern, const std::chrono::nanoseconds& log_time, const NameType& logger_name, const BufferType& format_buffer) { fmt::buf::DynamicStreamIOManager manager(256); - auto format_pattern_str = fmt::detail::format_in_manager(manager, false, pattern, FORMAT_SV("time", logTime), - FORMAT_SV("name", ConcatNameAndSinkName(loggerName, name)), FORMAT_SV("data", format_buffer)); - if (format_pattern_str.has_value() == false) return format_pattern_str.error(); - BufferType buffer(*format_pattern_str.value()); + auto format_pattern_str = fmt::detail::format_in_manager(manager, false, pattern, FORMAT_SV("logtime", log_time), + FORMAT_SV("name", ConcatNameAndSinkName(logger_name, name)), FORMAT_SV("data", format_buffer)); + BufferType buffer(*format_pattern_str); WriteToSinkSync(buffer); - return {}; } - [[nodiscard]] std::expected FormatAndWriteToSinkAsync(PatternTransferType pattern, const std::chrono::nanoseconds& logTime, - const NameType& loggerName, const BufferType& format_buffer) { + void FormatAndWriteToSinkAsync(PatternTransferType pattern, const std::chrono::nanoseconds& log_time, const NameType& logger_name, const BufferType& format_buffer) { // TODO - m_AsyncWaiter = std::async(std::launch::async, &BasicLoggerSink::FormatAndWriteToSinkSync, this, pattern, logTime, loggerName, format_buffer); - return {}; + async_waiter_ = std::async(std::launch::async, &BasicLoggerSink::FormatAndWriteToSinkSync, this, pattern, log_time, logger_name, format_buffer); } - [[nodiscard]] std::expected format_and_write_to_sink(PatternTransferType pattern, const std::chrono::nanoseconds& logTime, const NameType& loggerName, - const BufferType& format_buffer) { - if (IsAsync == AsyncSink::Sync) return FormatAndWriteToSinkSync(pattern, logTime, loggerName, format_buffer); - return FormatAndWriteToSinkAsync(pattern, logTime, loggerName, format_buffer); + void format_and_write_to_sink(PatternTransferType pattern, const std::chrono::nanoseconds& log_time, const NameType& logger_name, const BufferType& format_buffer) { + if (is_async == AsyncSink::Sync) return FormatAndWriteToSinkSync(pattern, log_time, logger_name, format_buffer); + return FormatAndWriteToSinkAsync(pattern, log_time, logger_name, format_buffer); } }; } // namespace stream::flog::detail diff --git a/src/stream/fmt/buf/fmt_manip_io.hxx b/src/stream/fmt/buf/fmt_manip_io.hxx index 2f7c78c1..7bc36ff7 100644 --- a/src/stream/fmt/buf/fmt_manip_io.hxx +++ b/src/stream/fmt/buf/fmt_manip_io.hxx @@ -15,22 +15,28 @@ namespace stream::fmt::buf { using StreamIO::buffer_end; using StreamIO::get; + using StreamIO::get_buffer_total_size; + using StreamIO::get_buffer_current_size; + using StreamIO::get_buffer_remaining_size; + using StreamIO::is_out_of_bound; + using StreamIO::is_empty; + using StreamIO::is_end_of_string; - using StreamIO::Manager; + using StreamIO::manager; protected: FMTStreamIO(BasicStreamIOManager& ostream_manager) noexcept : StreamIO(ostream_manager) {} public: - [[nodiscard]] static std::expected, FMTResult> create(BasicStreamIOManager& ostream_manager) { + static FMTStreamIO create(BasicStreamIOManager& ostream_manager) { FMTStreamIO res(ostream_manager); - SF_VERIFY(StreamIO::init(res)); + StreamIO::init(res); return res; } public: - std::size_t NoStride = 0; - std::size_t indent = 0; + std::size_t no_stride = 0; + std::size_t indent = 0; }; template @@ -43,7 +49,7 @@ namespace stream::fmt::buf { public: constexpr inline void add_no_stride(const std::size_t no_stride) noexcept { - buffer.NoStride += no_stride; + buffer.no_stride += no_stride; } constexpr inline void add_indent(const std::size_t indent) noexcept { @@ -53,21 +59,20 @@ namespace stream::fmt::buf { buffer.indent -= indent; } constexpr inline void set_indent() noexcept { - buffer.indent = Manip(buffer).get_buffer_current_size() - buffer.NoStride; + buffer.indent = buffer.get_buffer_current_size() - buffer.no_stride; } public: - [[nodiscard]] constexpr inline std::expected new_line_indent() { - SF_VERIFY(ManipIO(buffer).pushback('\n')); + constexpr inline void new_line_indent() { + ManipIO(buffer).pushback('\n'); return ManipIO(buffer).pushback(' ', buffer.indent); } - [[nodiscard]] constexpr inline std::expected pushback_check_indent(const TChar c) { - SF_VERIFY(ManipIO(buffer).pushback(c)); + constexpr inline void pushback_check_indent(const TChar c) { + ManipIO(buffer).pushback(c); if (c == '\n') { return ManipIO(buffer).pushback(' ', buffer.indent); } - return {}; } }; @@ -85,7 +90,7 @@ namespace stream::fmt::buf { TestManip(buffer).GoTo(ele..., '}'); } template - [[nodiscard]] inline std::expected param_go_to_forward(const CharToTest... ele) { + void param_go_to_forward(const CharToTest... ele) { return TestManip(buffer).go_to_forward(ele..., '}'); } @@ -98,15 +103,14 @@ namespace stream::fmt::buf { public: template - [[nodiscard]] std::expected next_is_named_args(const std::basic_string_view& sv) { + bool next_is_named_args(const std::basic_string_view& sv) { TestAccess access(buffer); TestManip manip(buffer); TChar* const oldpos = buffer.current_pos; auto is_same = manip.is_same_forward(sv); - if (is_same.has_value() == false) return std::unexpected(is_same.error()); - if (is_same.value() && (access.is_equal_to(':') || access.is_equal_to('}'))) { + if (is_same && (access.is_equal_to(':') || access.is_equal_to('}'))) { return true; } buffer.current_pos = oldpos; diff --git a/src/stream/fmt/buf/fmt_read_manip.hxx b/src/stream/fmt/buf/fmt_read_manip.hxx index 0bee31cb..c1fb9ece 100644 --- a/src/stream/fmt/buf/fmt_read_manip.hxx +++ b/src/stream/fmt/buf/fmt_read_manip.hxx @@ -17,65 +17,63 @@ namespace stream::fmt::buf { public: template - [[nodiscard]] std::expected read_integer(T& i, detail::ShiftInfo shift = detail::ShiftInfo{}) { + void read_integer(T& i, detail::ShiftInfo shift = detail::ShiftInfo{}) { ShiftReadManip shift_manip(buffer); buf::TestManip manip(buffer); - SF_VERIFY(shift_manip.ignore_shift_begin_space(shift)); + shift_manip.ignore_shift_begin_space(shift); bool sign = false; if constexpr (std::is_signed_v) { - sign = SF_TRY(manip.is_equal_to_forward('-')); - if (sign) --shift.size; + sign = manip.is_equal_to_forward('-'); + if (manip.is_equal_to_forward('-')) --shift.size; } TestAccess(buffer).is_a_digit(); T res = (T)0; while (TestAccess(buffer).is_a_digit()) { - char c = SF_TRY(Manip(buffer).get_and_forward()); - res = res * 10 + (c - '0'); + res = res * 10 + (Manip(buffer).get_and_forward() - '0'); --shift.size; } - SF_VERIFY(shift_manip.ignore_shift_end(shift)); + shift_manip.ignore_shift_end(shift); i = sign ? -res : res; - return {}; } public: template - [[nodiscard]] std::expected read_float(T& t, std::int32_t float_precision = -1, detail::ShiftInfo shift = detail::ShiftInfo{}) { + void read_float(T& t, std::int32_t float_precision = -1, detail::ShiftInfo shift = detail::ShiftInfo{}) { ShiftReadManip shift_manip(buffer); buf::TestAccess access(buffer); buf::TestManip manip(buffer); - SF_VERIFY(shift_manip.ignore_shift_begin_space(shift)); + shift_manip.ignore_shift_begin_space(shift); - bool sign = SF_TRY(manip.is_equal_to_forward('-')); + bool sign = manip.is_equal_to_forward('-'); if (sign) --shift.size; T intpart = static_cast(0); if (access.is_a_digit()) { while (access.is_a_digit()) { intpart = intpart * 10 + (buffer.get() - '0'); - SF_VERIFY(Manip(buffer).forward()); + Manip(buffer).forward(); --shift.size; } } else if (access.is_equal_to('.')) { - SF_VERIFY(buf::Manip(buffer).forward()); + buf::Manip(buffer).forward(); } else { - return std::unexpected(FMTResult::Parse_NonValidDigit); + throw std::runtime_error("fmt error: Parse_NonValidDigit"); } if (float_precision <= 0) - while (access.is_a_digit() && access.is_end_of_string() == false) { + while (access.is_a_digit() && buffer.is_end_of_string() == false) { Manip(buffer).forward_force(); --shift.size; } else { - while (Access(buffer).is_a_digit() && float_precision > 0 && Access(buffer).is_end_of_string() == false) { + while (Access(buffer).is_a_digit() && float_precision > 0 && buffer.is_end_of_string() == false) { Manip(buffer).forward_force(); float_precision--; --shift.size; @@ -90,16 +88,15 @@ namespace stream::fmt::buf { dec /= 10; } - SF_VERIFY(shift_manip.ignore_shift_end(shift)); + shift_manip.ignore_shift_end(shift); t = sign ? -intpart - dec : intpart + dec; - return {}; } public: template - [[nodiscard]] std::expected read_integer_h(T& i, std::uint8_t digitSize, std::uint8_t (&digit_lut)(TChar), TChar base_prefix = '\0', - detail::ShiftInfo shift = detail::ShiftInfo{}) { + void read_integer_h(T& i, std::uint8_t digitSize, std::optional (&digit_lut)(TChar), TChar base_prefix = '\0', + detail::ShiftInfo shift = detail::ShiftInfo{}) { ShiftReadManip shift_manip(buffer); buf::TestAccess access(buffer); buf::TestManip manip(buffer); @@ -107,54 +104,55 @@ namespace stream::fmt::buf { shift.size -= sizeof(T) * 8; if (base_prefix != '\0') shift.size -= 2; - SF_VERIFY(shift_manip.ignore_shift_begin_space(shift)); + shift_manip.ignore_shift_begin_space(shift); if (base_prefix != '\0') { - SF_VERIFY(manip.skip_one_of('0')); - SF_VERIFY(manip.skip_one_of(base_prefix)); + manip.skip_one_of('0'); + manip.skip_one_of(base_prefix); } - T res = (T)0; - while (digit_lut(buffer.get()) != std::numeric_limits::max()) { + T res = (T)0; + std::optional get_current = digit_lut(buffer.get()); + while (get_current.has_value()) { res = res << digitSize; - res += digit_lut(buffer.get()); + res += get_current.value(); + get_current = digit_lut(buffer.get()); Manip(buffer).forward_force(); } - SF_VERIFY(shift_manip.ignore_shift_end(shift)); + shift_manip.ignore_shift_end(shift); i = res; - return {}; } protected: - static constexpr std::uint8_t digit_lut_bin(TChar in) { + static constexpr std::optional digit_lut_bin(TChar in) { if (in == '0') return 0; if (in == '1') return 1; - return std::numeric_limits::max(); + return std::nullopt; } - static constexpr std::uint8_t digit_lut_oct(TChar in) { + static constexpr std::optional digit_lut_oct(TChar in) { if (in >= '0' && in <= '7') return in - '0'; - return std::numeric_limits::max(); + return std::nullopt; } - static constexpr std::uint8_t digit_lut_dec(TChar in) { + static constexpr std::optional digit_lut_dec(TChar in) { if (in >= '0' && in <= '9') return in - '0'; - return std::numeric_limits::max(); + return std::nullopt; } - static constexpr std::uint8_t digit_lut_hexupper(TChar in) { + static constexpr std::optional digit_lut_hexupper(TChar in) { if (in >= '0' && in <= '9') return in - '0'; if (in >= 'A' && in <= 'F') return in - 'A'; - return std::numeric_limits::max(); + return std::nullopt; } - static constexpr std::uint8_t digit_lut_hexlower(TChar in) { + static constexpr std::optional digit_lut_hexlower(TChar in) { if (in >= '0' && in <= '9') return in - '0'; if (in >= 'a' && in <= 'f') return in - 'a'; - return std::numeric_limits::max(); + return std::nullopt; } public: template - [[nodiscard]] std::expected read_integer_format_data(T& i, const detail::FormatData& formatdata) { + void read_integer_format_data(T& i, const detail::FormatData& formatdata) { if (formatdata.has_spec) { switch (formatdata.integer_print) { case detail::IntegerPrintBase::Dec: @@ -177,7 +175,7 @@ namespace stream::fmt::buf { return ReadManip(buffer).fast_read_integer(i); } template - [[nodiscard]] std::expected read_float_format_data(T& i, const detail::FormatData& formatdata) { + void read_float_format_data(T& i, const detail::FormatData& formatdata) { if (formatdata.has_spec) { if (formatdata.ShiftType == detail::ShiftInfo::ShiftType::Nothing) return ReadManip(buffer).fast_read_float(i, formatdata.float_precision); @@ -189,19 +187,18 @@ namespace stream::fmt::buf { public: template - [[nodiscard]] std::expected read_char_ptr(const CharStr* str, std::size_t sizeContainer, std::size_t sizeToWrite, - detail::ShiftInfo shift = detail::ShiftInfo{}) { + void read_char_ptr(const CharStr* str, std::size_t sizeContainer, std::size_t sizeToWrite, detail::ShiftInfo shift = detail::ShiftInfo{}) { // FIXME // TODO - return std::unexpected(FMTResult::FunctionNotImpl); + throw std::runtime_error("fmt error: FunctionNotImpl"); } template - [[nodiscard]] inline std::expected read_char_array(const CharStr (&str)[SIZE], detail::ShiftInfo shift = detail::ShiftInfo{}) { + void read_char_array(const CharStr (&str)[SIZE], detail::ShiftInfo shift = detail::ShiftInfo{}) { return read_char_ptr(str, SIZE, 0, shift); } template - [[nodiscard]] inline std::expected read_char_bound(const CharStr* begin, const CharStr* end, detail::ShiftInfo shift = detail::ShiftInfo{}) { + void read_char_bound(const CharStr* begin, const CharStr* end, detail::ShiftInfo shift = detail::ShiftInfo{}) { return read_char_ptr(begin, end - begin, 0, shift); } }; diff --git a/src/stream/fmt/buf/fmt_write_manip.hxx b/src/stream/fmt/buf/fmt_write_manip.hxx index 1b544f54..9b2c7fa1 100644 --- a/src/stream/fmt/buf/fmt_write_manip.hxx +++ b/src/stream/fmt/buf/fmt_write_manip.hxx @@ -19,7 +19,7 @@ namespace stream::fmt::buf { public: template - [[nodiscard]] std::expected write_integer(T i, detail::ShiftInfo shift = detail::ShiftInfo{}) { + void write_integer(T i, detail::ShiftInfo shift = detail::ShiftInfo{}) { char old_after = shift.print.after; if (shift.print.after >= '0' && shift.print.after <= '9') shift.print.after = ' '; @@ -33,20 +33,20 @@ namespace stream::fmt::buf { } if (!shift.print.before_is_a_digit()) { - SF_VERIFY(ShiftWriteManip(buffer).write_shift_begin(shift)); + ShiftWriteManip(buffer).write_shift_begin(shift); } if (i < 0) { - SF_VERIFY(ManipIO(buffer).pushback('-')); + ManipIO(buffer).pushback('-'); i = -i; } if (shift.print.before_is_a_digit()) { - SF_VERIFY(ShiftWriteManip(buffer).write_shift_right_all(shift)); + ShiftWriteManip(buffer).write_shift_right_all(shift); } if (i == 0) { - SF_VERIFY(ManipIO(buffer).pushback('0')); + ManipIO(buffer).pushback('0'); } else { - SF_VERIFY(ManipIO(buffer).forward(nb_digit)); + ManipIO(buffer).forward(nb_digit); std::int32_t nb_digit_ = nb_digit; while (nb_digit_ > 0) { Manip(buffer).backward_force(); @@ -54,18 +54,17 @@ namespace stream::fmt::buf { i /= 10; nb_digit_--; } - SF_VERIFY(ManipIO(buffer).forward(nb_digit)); + ManipIO(buffer).forward(nb_digit); } - SF_VERIFY(ShiftWriteManip(buffer).write_shift_end(shift)); + ShiftWriteManip(buffer).write_shift_end(shift); shift.print.after = old_after; - return {}; } public: template - [[nodiscard]] std::expected write_float(T i, std::int32_t float_precision = 2, detail::ShiftInfo shift = detail::ShiftInfo{}) { + void write_float(T i, std::int32_t float_precision = 2, detail::ShiftInfo shift = detail::ShiftInfo{}) { char old_before = shift.print.before; if (shift.print.before >= '0' && shift.print.before <= '9') shift.print.before = ' '; @@ -79,21 +78,21 @@ namespace stream::fmt::buf { } if (!shift.print.before_is_a_digit()) { - SF_VERIFY(ShiftWriteManip(buffer).write_shift_begin(shift)); + ShiftWriteManip(buffer).write_shift_begin(shift); } if (i < 0) { - SF_VERIFY(ManipIO(buffer).pushback('-')); + ManipIO(buffer).pushback('-'); i = -i; } if (shift.print.before_is_a_digit()) { - SF_VERIFY(ShiftWriteManip(buffer).write_shift_right_all(shift)); + ShiftWriteManip(buffer).write_shift_right_all(shift); } T k = std::trunc(i); if (k == 0) { - SF_VERIFY(ManipIO(buffer).pushback('0')); + ManipIO(buffer).pushback('0'); } else { - SF_VERIFY(ManipIO(buffer).forward(nb_digit)); + ManipIO(buffer).forward(nb_digit); std::int32_t nb_digit_ = nb_digit; while (nb_digit_ > 0) { Manip(buffer).backward_force(); @@ -101,27 +100,25 @@ namespace stream::fmt::buf { k /= 10; nb_digit_--; } - SF_VERIFY(ManipIO(buffer).forward(nb_digit)); + ManipIO(buffer).forward(nb_digit); } - SF_VERIFY(ManipIO(buffer).pushback('.')); + ManipIO(buffer).pushback('.'); i -= k; while (float_precision-- != 0) { T decimal = std::trunc(i *= 10); - SF_VERIFY(ManipIO(buffer).pushback((char)decimal + '0')); + ManipIO(buffer).pushback((char)decimal + '0'); i -= decimal; } - SF_VERIFY(ShiftWriteManip(buffer).write_shift_end(shift)); + ShiftWriteManip(buffer).write_shift_end(shift); shift.print.before = old_before; - return {}; } public: template - [[nodiscard]] std::expected write_integer_h(T i, std::uint8_t digitSize, const TChar* const lut, TChar base_prefix = '\0', - detail::ShiftInfo shift = detail::ShiftInfo{}) { + void write_integer_h(T i, std::uint8_t digitSize, const TChar* const lut, TChar base_prefix = '\0', detail::ShiftInfo shift = detail::ShiftInfo{}) { ManipIO manip(buffer); std::int32_t digit_count = sizeof(T) * 8; @@ -138,24 +135,23 @@ namespace stream::fmt::buf { } if (base_prefix != '\0') { - SF_VERIFY(ManipIO(buffer).pushback('0')); - SF_VERIFY(ManipIO(buffer).pushback(base_prefix)); + ManipIO(buffer).pushback('0'); + ManipIO(buffer).pushback(base_prefix); } - SF_VERIFY(manip.forward(digit_count)); + manip.forward(digit_count); std::int32_t k = digit_count + 1; while (--k != 0) { Manip(buffer).backward_force(); buffer.set(lut[i & (0b1 << digitSize)]); i = i >> digitSize; } - SF_VERIFY(manip.forward(digit_count)); - return {}; + manip.forward(digit_count); } public: template - [[nodiscard]] std::expected write_integer_format_data(T i, const detail::FormatData& formatdata) { + void write_integer_format_data(T i, const detail::FormatData& formatdata) { if (formatdata.has_spec) { switch (formatdata.integer_print) { case detail::IntegerPrintBase::Dec: @@ -178,7 +174,7 @@ namespace stream::fmt::buf { return WriteManip(buffer).fast_write_integer(i); } template - [[nodiscard]] std::expected write_float_formatdata(T i, const detail::FormatData& formatdata) { + void write_float_formatdata(T i, const detail::FormatData& formatdata) { if (formatdata.has_spec) { if (formatdata.shift.type != detail::ShiftInfo::ShiftType::Nothing) return write_float(i, formatdata.float_precision, formatdata.shift); } @@ -188,7 +184,7 @@ namespace stream::fmt::buf { public: template - [[nodiscard]] inline std::expected write_indent_char_ptr(const CharStr* str, std::size_t size) { + void write_indent_char_ptr(const CharStr* str, std::size_t size) { while (size > 0) { const CharStr* const begin = str; while (size > 0 && *str != '\n') { @@ -196,50 +192,48 @@ namespace stream::fmt::buf { } const CharStr* const end = str; - SF_VERIFY(WriteManip(buffer).fast_write_char_array(begin, end - begin)); + WriteManip(buffer).fast_write_char_array(begin, end - begin); if (size > 0 && *str == '\n') { - SF_VERIFY(FMTManipIO(buffer).new_line_indent()); + FMTManipIO(buffer).new_line_indent(); ++str; --size; } } - return {}; } template - [[nodiscard]] inline std::expected write_indent_char_bound(const CharStr* begin, const CharStr* end) { + void write_indent_char_bound(const CharStr* begin, const CharStr* end) { return write_indent_char_ptr(begin, end - begin); } template - [[nodiscard]] inline std::expected write_indent_string(std::basic_string_view str) { + void write_indent_string(std::basic_string_view str) { return write_indent_char_ptr(str.data(), str.size()); } template - [[nodiscard]] inline std::expected write_char_ptr(const CharStr* str, std::size_t size, detail::ShiftInfo& shift) { + void write_char_ptr(const CharStr* str, std::size_t size, detail::ShiftInfo& shift) { if (shift.size <= 0) return WriteManip(buffer).fast_write_char_array(str, size); - SF_VERIFY(ManipIO(buffer).reserve(std::max(static_cast(shift.size), size))); + if (ManipIO(buffer).reserve(std::max(static_cast(shift.size), size)) == false) throw std::bad_alloc(); if (static_cast(shift.size) > size) { shift.size -= static_cast(size); - SF_VERIFY(ShiftWriteManip(buffer).write_shift_begin(shift)); + ShiftWriteManip(buffer).write_shift_begin(shift); - SF_VERIFY(WriteManip(buffer).fast_write_char_array(str, size)); + WriteManip(buffer).fast_write_char_array(str, size); - SF_VERIFY(ShiftWriteManip(buffer).write_shift_end(shift)); + ShiftWriteManip(buffer).write_shift_end(shift); } else { - SF_VERIFY(WriteManip(buffer).fast_write_char_array(str, size)); + WriteManip(buffer).fast_write_char_array(str, size); } - return {}; } template - [[nodiscard]] inline std::expected write_char_bound(const CharStr* begin, const CharStr* end, detail::ShiftInfo& shift) { + void write_char_bound(const CharStr* begin, const CharStr* end, detail::ShiftInfo& shift) { return write_char_ptr(begin, end - begin, shift); } template - [[nodiscard]] inline std::expected write_string(std::basic_string_view str, detail::ShiftInfo& shift) { + void write_string(std::basic_string_view str, detail::ShiftInfo& shift) { return write_char_ptr(str.data(), str.size(), shift); } }; diff --git a/src/stream/fmt/buf/manip.hxx b/src/stream/fmt/buf/manip.hxx index fcfb392d..2fb590ae 100644 --- a/src/stream/fmt/buf/manip.hxx +++ b/src/stream/fmt/buf/manip.hxx @@ -11,17 +11,6 @@ namespace stream::fmt::buf { public: const Stream& buffer; - public: - constexpr inline std::size_t get_buffer_total_size() const noexcept { - return static_cast(buffer.buffer_end - buffer.buffer); - } - constexpr inline std::size_t get_buffer_current_size() const noexcept { - return static_cast(buffer.current_pos - buffer.buffer); - } - constexpr inline std::size_t get_buffer_remaining_size() const noexcept { - return static_cast(buffer.buffer_end - buffer.current_pos); - } - public: constexpr inline bool can_move_forward(const std::size_t count = 1) const noexcept { return buffer.current_pos + count <= buffer.buffer_end; @@ -30,22 +19,12 @@ namespace stream::fmt::buf { return buffer.current_pos - count >= buffer.buffer; } - constexpr inline bool is_out_of_bound() const noexcept { - return buffer.current_pos < buffer.buffer || buffer.current_pos >= buffer.buffer_end; - } - constexpr inline bool is_empty() const noexcept { - return buffer.current_pos >= buffer.buffer_end; - } - constexpr inline bool is_end_of_string() const noexcept { - return is_empty() || buffer.get() == 0; - } - - [[nodiscard]] constexpr inline std::expected, FMTResult> get_next(const std::size_t count = 1) const { - if (Access(buffer).can_move_forward(count) == false) return std::unexpected(FMTResult::Buffer_OutOfBoundAccess); + constexpr inline std::remove_cv_t get_next(const std::size_t count = 1) const { + if (Access(buffer).can_move_forward(count) == false) throw std::runtime_error("fmt error: Buffer_OutOfBoundAccess"); return Manip(buffer).get_next_force(count); } - [[nodiscard]] constexpr inline std::expected, FMTResult> get_prev(const std::size_t count = 1) const { - if (Access(buffer).can_move_backward(count) == false) return std::unexpected(FMTResult::Buffer_OutOfBoundAccess); + constexpr inline std::remove_cv_t get_prev(const std::size_t count = 1) const { + if (Access(buffer).can_move_backward(count) == false) throw std::runtime_error("fmt error: Buffer_OutOfBoundAccess"); return Manip(buffer).get_prev_force(count); } constexpr inline TChar get_next_force(const std::size_t count = 1) const noexcept { @@ -70,6 +49,11 @@ namespace stream::fmt::buf { buffer.current_pos = buffer_; buffer.buffer_end = buffer_ + size_; } + constexpr inline void reload(std::basic_string_view sv) noexcept { + buffer.buffer = sv.data(); + buffer.current_pos = sv.data(); + buffer.buffer_end = sv.data() + sv.size(); + } constexpr inline void reload(Stream& buffer_) noexcept { buffer.buffer = buffer_.buffer; @@ -85,27 +69,25 @@ namespace stream::fmt::buf { constexpr inline void forward_force(const std::size_t count = 1) noexcept { buffer.current_pos += count; } - [[nodiscard]] constexpr inline std::expected forward(const std::size_t count = 1) noexcept { - if (!access().can_move_forward(count)) return std::unexpected(FMTResult::Buffer_OutOfBoundAccess); + constexpr inline void forward(const std::size_t count = 1) noexcept { + if (!access().can_move_forward(count)) throw std::runtime_error("fmt error: Buffer_OutOfBoundAccess"); buffer.current_pos += count; - return {}; } constexpr inline void backward_force(const std::size_t count = 1) noexcept { buffer.current_pos -= count; } - [[nodiscard]] constexpr inline std::expected backward(const std::size_t count = 1) noexcept { - if (!access().can_move_backward(count)) return std::unexpected(FMTResult::Buffer_OutOfBoundAccess); + constexpr inline void backward(const std::size_t count = 1) noexcept { + if (!access().can_move_backward(count)) throw std::runtime_error("fmt error: Buffer_OutOfBoundAccess"); buffer.current_pos -= count; - return {}; } - [[nodiscard]] constexpr inline std::expected, FMTResult> get_and_forward() { - if (Access(buffer).can_move_forward(1) == false) return std::unexpected(FMTResult::Buffer_OutOfBoundAccess); + constexpr inline std::remove_cv_t get_and_forward() { + if (Access(buffer).can_move_forward(1) == false) throw std::runtime_error("fmt error: Buffer_OutOfBoundAccess"); return *buffer.current_pos++; } - [[nodiscard]] constexpr inline std::expected, FMTResult> get_and_backward() { - if (Access(buffer).can_move_backward(1) == false) return std::unexpected(FMTResult::Buffer_OutOfBoundAccess); + constexpr inline std::remove_cv_t get_and_backward() { + if (Access(buffer).can_move_backward(1) == false) throw std::runtime_error("fmt error: Buffer_OutOfBoundAccess"); return *buffer.current_pos--; } }; diff --git a/src/stream/fmt/buf/manip_io.hxx b/src/stream/fmt/buf/manip_io.hxx index 3f44cc4b..95c8d04a 100644 --- a/src/stream/fmt/buf/manip_io.hxx +++ b/src/stream/fmt/buf/manip_io.hxx @@ -17,27 +17,26 @@ namespace stream::fmt::buf { public: void compute_generated_size() noexcept { - buffer.Manager.compute_generated_size(Access(buffer).get_buffer_current_size()); + buffer.manager.compute_generated_size(buffer.get_buffer_current_size()); } public: - [[nodiscard]] std::expected add_size(const std::size_t count) noexcept { - std::size_t currentSize = Access(buffer).get_buffer_current_size(); - SF_VERIFY(buffer.Manager.add_size(count)) - Manip(buffer).reload(buffer.Manager.get_buffer(), buffer.Manager.get_buffer_size()); - buffer.current_pos = buffer.Manager.get_buffer() + currentSize; - return {}; + bool add_size(const std::size_t count) noexcept { + std::size_t currentSize = buffer.get_buffer_current_size(); + if (buffer.manager.add_size(count) == false) return false; + Manip(buffer).reload(buffer.manager.get_buffer(), buffer.manager.get_buffer_size()); + buffer.current_pos = buffer.manager.get_buffer() + currentSize; + return true; } - [[nodiscard]] inline std::expected reserve(const std::size_t count = 1) noexcept { - if (buffer.current_pos + count <= buffer.buffer_end) return {}; - return add_size(static_cast(count)); + inline bool reserve(const std::size_t count = 1) noexcept { + if (buffer.current_pos + count <= buffer.buffer_end) return true; + return add_size(count); } - [[nodiscard]] inline std::expected forward(const std::size_t count = 1) noexcept { - SF_VERIFY(reserve(count)); + void forward(const std::size_t count = 1) noexcept { + if (reserve(count) == false) throw std::bad_alloc(); buffer.current_pos += count; - return {}; } public: @@ -45,21 +44,19 @@ namespace stream::fmt::buf { *buffer.current_pos = c; } - [[nodiscard]] inline std::expected pushback(const TChar c) noexcept { - SF_VERIFY(reserve(1)); + void pushback(const TChar c) noexcept { + if (reserve(1) == false) throw std::bad_alloc(); *buffer.current_pos++ = c; - return {}; } inline void pushback_force(const TChar c) noexcept { *buffer.current_pos++ = c; } public: - [[nodiscard]] inline std::expected pushback(const TChar c, auto count) noexcept { - SF_VERIFY(reserve(count)) + void pushback(const TChar c, auto count) noexcept { + if (reserve(count) == false) throw std::bad_alloc(); while (count-- > 0) pushback_force(c); - return {}; } private: @@ -71,10 +68,9 @@ namespace stream::fmt::buf { public: template - [[nodiscard]] inline std::expected pushback_seq(const CharToPush... ele) noexcept { - SF_VERIFY(reserve(sizeof...(ele))) + void pushback_seq(const CharToPush... ele) noexcept { + if (reserve(sizeof...(ele)) == false) throw std::bad_alloc(); pushback_seq_impl(ele...); - return {}; } }; } // namespace stream::fmt::buf diff --git a/src/stream/fmt/buf/read_manip.hxx b/src/stream/fmt/buf/read_manip.hxx index 3a1be547..fb28c7dd 100644 --- a/src/stream/fmt/buf/read_manip.hxx +++ b/src/stream/fmt/buf/read_manip.hxx @@ -16,50 +16,49 @@ namespace stream::fmt::buf { public: template - [[nodiscard]] constexpr std::expected fast_read_integer(T& t) noexcept { + constexpr void fast_read_integer(T& t) noexcept { bool sign = false; if constexpr (std::is_signed_v) { - sign = SF_TRY(TestManip(buffer).is_equal_to_forward('-')); + sign = TestManip(buffer).is_equal_to_forward('-'); } if (!TestAccess(buffer).is_a_digit()) { - return std::unexpected(FMTResult::Parse_NonValidDigit); + throw std::runtime_error("fmt error: Parse_NonValidDigit"); } T value = static_cast(0); while (TestAccess(buffer).is_a_digit()) { value = value * static_cast(10) + static_cast(buffer.get() - static_cast('0')); - SF_VERIFY(Manip(buffer).forward()); + Manip(buffer).forward(); } t = sign ? -value : value; - return {}; } public: template - [[nodiscard]] constexpr inline std::expected fast_read_float(T& t, std::int32_t float_precision = -1) noexcept { + constexpr inline void fast_read_float(T& t, std::int32_t float_precision = -1) noexcept { T intpart = static_cast(0); TestAccess access(buffer); TestManip manip(buffer); - bool sign = SF_TRY(manip.is_equal_to_forward('-')); + bool sign = manip.is_equal_to_forward('-'); if (access.is_a_digit()) { - SF_VERIFY(fast_read_integer(intpart)); + fast_read_integer(intpart); } else if (access.is_equal_to('.')) { - SF_VERIFY(buf::Manip(buffer).forward()); + buf::Manip(buffer).forward(); } else { - return std::unexpected(FMTResult::Parse_NonValidDigit); + throw std::runtime_error("fmt error: Parse_NonValidDigit"); } if (float_precision < 0) { - while (access.is_a_digit() && Access(buffer).is_end_of_string() == false) { + while (access.is_a_digit() && buffer.is_end_of_string() == false) { Manip(buffer).forward_force(); } } else { - while (access.is_a_digit() && float_precision > 0 && Access(buffer).is_end_of_string() == false) { + while (access.is_a_digit() && float_precision > 0 && buffer.is_end_of_string() == false) { Manip(buffer).forward_force(); float_precision--; } @@ -74,14 +73,13 @@ namespace stream::fmt::buf { } t = sign ? -intpart - dec : intpart + dec; - return {}; } public: template - [[nodiscard]] std::expected fast_read_char_ptr(const CharPtr* str, std::size_t size_to_copy, bool is_zero_ended = true) { + void fast_read_char_ptr(const CharPtr* str, std::size_t size_to_copy, bool is_zero_ended = true) { if (Access(buffer).can_move_forward(size_to_copy) == false) { - return ReadManip(buffer).fast_read_char_ptr(str, Access(buffer).get_buffer_remaining_size(), is_zero_ended); + return ReadManip(buffer).fast_read_char_ptr(str, buffer.get_buffer_remaining_size(), is_zero_ended); } std::copy_n(str, size_to_copy, buffer.current_pos); @@ -90,15 +88,13 @@ namespace stream::fmt::buf { if (is_zero_ended) { *str = 0; } - - return {}; } template - [[nodiscard]] inline std::expected fast_read_char_array(const CharStr (&str)[SIZE], bool is_zero_ended = true) { + void fast_read_char_array(const CharStr (&str)[SIZE], bool is_zero_ended = true) { return fast_read_char_ptr(str, SIZE); } template - [[nodiscard]] inline std::expected fast_read_char_bound(const CharStr* begin, const CharStr* end, bool is_zero_ended = true) { + void fast_read_char_bound(const CharStr* begin, const CharStr* end, bool is_zero_ended = true) { return fast_read_char_ptr(begin, end - begin - (is_zero_ended ? 1 : 0), is_zero_ended); } }; diff --git a/src/stream/fmt/buf/stream.hxx b/src/stream/fmt/buf/stream.hxx index 872f0040..1e85ecd6 100644 --- a/src/stream/fmt/buf/stream.hxx +++ b/src/stream/fmt/buf/stream.hxx @@ -13,15 +13,35 @@ namespace stream::fmt::buf { TChar* current_pos; TChar* buffer_end; // Not included + public: + Stream() noexcept : buffer(nullptr), current_pos(nullptr), buffer_end(nullptr) {} + Stream(TChar* const buffer_, const std::size_t size_) noexcept : buffer(buffer_), current_pos(buffer_), buffer_end(buffer_ + size_) {} + public: constexpr inline TChar get() const { return *current_pos; } public: - Stream() noexcept : buffer(nullptr), current_pos(nullptr), buffer_end(nullptr) {} + constexpr inline std::size_t get_buffer_total_size() const noexcept { + return static_cast(buffer_end - buffer); + } + constexpr inline std::size_t get_buffer_current_size() const noexcept { + return static_cast(current_pos - buffer); + } + constexpr inline std::size_t get_buffer_remaining_size() const noexcept { + return static_cast(buffer_end - current_pos); + } - Stream(TChar* const buffer_, const std::size_t size_) noexcept : buffer(buffer_), current_pos(buffer_), buffer_end(buffer_ + size_) {} + constexpr inline bool is_out_of_bound() const noexcept { + return current_pos < buffer || current_pos >= buffer_end; + } + constexpr inline bool is_empty() const noexcept { + return current_pos >= buffer_end; + } + constexpr inline bool is_end_of_string() const noexcept { + return is_empty() || get() == 0; + } }; template @@ -34,6 +54,12 @@ namespace stream::fmt::buf { using Stream::buffer_end; using Stream::get; + using Stream::get_buffer_total_size; + using Stream::get_buffer_current_size; + using Stream::get_buffer_remaining_size; + using Stream::is_out_of_bound; + using Stream::is_empty; + using Stream::is_end_of_string; public: StreamView() noexcept : Stream() {} diff --git a/src/stream/fmt/buf/streamio.hxx b/src/stream/fmt/buf/streamio.hxx index fae0b253..9c748dcf 100644 --- a/src/stream/fmt/buf/streamio.hxx +++ b/src/stream/fmt/buf/streamio.hxx @@ -16,21 +16,26 @@ namespace stream::fmt::buf { using Stream::buffer_end; using Stream::get; + using Stream::get_buffer_total_size; + using Stream::get_buffer_current_size; + using Stream::get_buffer_remaining_size; + using Stream::is_out_of_bound; + using Stream::is_empty; + using Stream::is_end_of_string; protected: - StreamIO(BasicStreamIOManager& ostream_manager) noexcept : Stream(), Manager(ostream_manager) {} + StreamIO(BasicStreamIOManager& ostream_manager) noexcept : Stream(), manager(ostream_manager) {} protected: - [[nodiscard]] static std::expected init(StreamIO& in) { - SF_VERIFY(in.Manager.BeginContext()); - Manip(in).reload(in.Manager.get_buffer(), in.Manager.get_buffer_size()); - return {}; + static void init(StreamIO& in) { + in.manager.begin_context(); + Manip(in).reload(in.manager.get_buffer(), in.manager.get_buffer_size()); } public: - [[nodiscard]] static std::expected, FMTResult> create(BasicStreamIOManager& ostream_manager) { + static StreamIO create(BasicStreamIOManager& ostream_manager) { StreamIO res(ostream_manager); - SF_VERIFY(init(res)); + init(res); return res; } @@ -40,7 +45,7 @@ namespace stream::fmt::buf { } public: - BasicStreamIOManager& Manager; + BasicStreamIOManager& manager; }; template diff --git a/src/stream/fmt/buf/streamio_manager/basic_streamio_manager.hxx b/src/stream/fmt/buf/streamio_manager/basic_streamio_manager.hxx index 3be85b78..489ca0de 100644 --- a/src/stream/fmt/buf/streamio_manager/basic_streamio_manager.hxx +++ b/src/stream/fmt/buf/streamio_manager/basic_streamio_manager.hxx @@ -13,13 +13,11 @@ namespace stream::fmt::buf { BasicStreamIOManager& operator=(BasicStreamIOManager&) = delete; protected: - [[nodiscard]] virtual std::expected begin_context_impl() { - return {}; - } + virtual void begin_context_impl() {} virtual void compute_generated_size_impl(const std::size_t /* totalGeneratedLength */) {} public: - [[nodiscard]] std::expected BeginContext() { + void begin_context() { return begin_context_impl(); } void compute_generated_size(std::size_t totalGeneratedLength) { @@ -33,17 +31,17 @@ namespace stream::fmt::buf { virtual std::size_t get_buffer_size() const = 0; public: - [[nodiscard]] virtual std::expected add_size(const std::size_t count) = 0; + virtual bool add_size(const std::size_t count) = 0; public: StreamView get_last_generated_buffer_info_view() const { - return StreamView(get_buffer(), m_LastGeneratedDataSize); + return StreamView(get_buffer(), last_generated_data_size_); } operator StreamView() const { return get_last_generated_buffer_info_view(); } std::basic_string_view get_last_generated_string_view() const { - return std::basic_string_view(get_buffer(), m_LastGeneratedDataSize); + return std::basic_string_view(get_buffer(), last_generated_data_size_); } operator std::basic_string_view() const { return get_last_generated_string_view(); @@ -51,15 +49,15 @@ namespace stream::fmt::buf { public: std::size_t get_last_generated_data_size() const { - return m_LastGeneratedDataSize; + return last_generated_data_size_; } private: void set_last_generated_data_size(const std::size_t size) { - m_LastGeneratedDataSize = size; + last_generated_data_size_ = size; } protected: - std::size_t m_LastGeneratedDataSize{0}; + std::size_t last_generated_data_size_{0}; }; } // namespace stream::fmt::buf diff --git a/src/stream/fmt/buf/streamio_manager/dynamic_streamio_manager.hxx b/src/stream/fmt/buf/streamio_manager/dynamic_streamio_manager.hxx index 5a553109..d978ab0b 100644 --- a/src/stream/fmt/buf/streamio_manager/dynamic_streamio_manager.hxx +++ b/src/stream/fmt/buf/streamio_manager/dynamic_streamio_manager.hxx @@ -10,7 +10,7 @@ namespace stream::fmt::buf { template class DynamicStreamIOManager : public BasicStreamIOManager { public: - DynamicStreamIOManager(std::size_t beginSize = DEFAULT_BEGIN_SIZE) : buffer_size_(beginSize) {} + DynamicStreamIOManager(std::size_t begin_size = DEFAULT_BEGIN_SIZE) : buffer_size_(begin_size) {} ~DynamicStreamIOManager() override = default; DynamicStreamIOManager(DynamicStreamIOManager&) = delete; @@ -34,19 +34,18 @@ namespace stream::fmt::buf { } public: - [[nodiscard]] std::expected begin_context_impl() final { - if (buffer_ != nullptr) return {}; + void begin_context_impl() final { + if (buffer_ != nullptr) return; CharType* alloc = new CharType[buffer_size_]; - if (alloc == nullptr) return std::unexpected(FMTResult::Manager_AllocationFailed); + if (alloc == nullptr) throw std::runtime_error("fmt error: Manager_AllocationFailed"); buffer_.reset(alloc); - return {}; } - [[nodiscard]] std::expected add_size(const std::size_t count) override { + bool add_size(const std::size_t count) override { return resize(count + buffer_size_); } - [[nodiscard]] std::expected resize(const std::size_t target_buffer_size); + bool resize(const std::size_t target_buffer_size); protected: std::unique_ptr buffer_ = nullptr; @@ -74,7 +73,7 @@ namespace stream::fmt::buf { static constexpr float MEAN_CALCFACT_LAST = 1; public: - ShrinkDynamicStreamIOManager(std::size_t beginSize = DEFAULT_BEGIN_SIZE) : Base(beginSize), m_MeanGeneratedSize(beginSize) {} + ShrinkDynamicStreamIOManager(std::size_t begin_size = DEFAULT_BEGIN_SIZE) : Base(begin_size), mean_generated_size_(begin_size) {} ~ShrinkDynamicStreamIOManager() override = default; ShrinkDynamicStreamIOManager(ShrinkDynamicStreamIOManager&) = delete; ShrinkDynamicStreamIOManager& operator=(ShrinkDynamicStreamIOManager&) = delete; @@ -82,21 +81,21 @@ namespace stream::fmt::buf { protected: void compute_generated_size_impl(std::size_t totalGeneratedLength) override { // WTF - m_MeanGeneratedSize = (m_MeanGeneratedSize * MEAN_CALCFACT_OLD + totalGeneratedLength * MEAN_CALCFACT_LAST) / (MEAN_CALCFACT_OLD + MEAN_CALCFACT_LAST); + mean_generated_size_ = (mean_generated_size_ * MEAN_CALCFACT_OLD + totalGeneratedLength * MEAN_CALCFACT_LAST) / (MEAN_CALCFACT_OLD + MEAN_CALCFACT_LAST); } public: - [[nodiscard]] std::expected shrink_if_needed() { - if (buffer_size_ > static_cast(m_MeanGeneratedSize * MEAN_SIZE_OVERFLOW)) return resize(static_cast(m_MeanGeneratedSize * MEAN_SIZE_RESIZE)); - return {}; + void shrink_if_needed() { + if (buffer_size_ > static_cast(mean_generated_size_ * MEAN_SIZE_OVERFLOW)) + return resize(static_cast(mean_generated_size_ * MEAN_SIZE_RESIZE)); } private: - std::size_t m_MeanGeneratedSize = 0; + std::size_t mean_generated_size_ = 0; }; template - [[nodiscard]] std::expected DynamicStreamIOManager::resize(const std::size_t target_buffer_size) { + bool DynamicStreamIOManager::resize(const std::size_t target_buffer_size) { std::size_t new_buffer_size = target_buffer_size; if (buffer_size_ < target_buffer_size) { @@ -105,16 +104,15 @@ namespace stream::fmt::buf { new_buffer_size *= GROW_UP_BUFFER_SIZE; } - CharType* newBuffer = new CharType[new_buffer_size]; - if (newBuffer == nullptr) return std::unexpected(FMTResult::Manager_AllocationFailed); + CharType* new_buffer = new CharType[new_buffer_size]; + if (new_buffer == nullptr) return false; - std::memcpy(newBuffer, buffer_.get(), std::min(new_buffer_size, buffer_size_)); + std::memcpy(new_buffer, buffer_.get(), std::min(new_buffer_size, buffer_size_)); if constexpr (DEBUG_RESIZE) std::cout << "resize from " << buffer_size_ << " to " << new_buffer_size << std::endl; - buffer_.reset(newBuffer); + buffer_.reset(new_buffer); buffer_size_ = new_buffer_size; - - return {}; + return true; } } // namespace stream::fmt::buf diff --git a/src/stream/fmt/buf/streamio_manager/given_streamio_manager.hxx b/src/stream/fmt/buf/streamio_manager/given_streamio_manager.hxx index c02dce2d..920bde10 100644 --- a/src/stream/fmt/buf/streamio_manager/given_streamio_manager.hxx +++ b/src/stream/fmt/buf/streamio_manager/given_streamio_manager.hxx @@ -28,8 +28,8 @@ namespace stream::fmt::buf { } public: - [[nodiscard]] std::expected add_size(const std::size_t /* count */) override { - return std::unexpected(FMTResult::Manager_StaticMemory); + bool add_size(const std::size_t /* count */) override { + return false; } private: diff --git a/src/stream/fmt/buf/streamio_manager/static_streamio_manager.hxx b/src/stream/fmt/buf/streamio_manager/static_streamio_manager.hxx index bbaa4f3c..83a73d3f 100644 --- a/src/stream/fmt/buf/streamio_manager/static_streamio_manager.hxx +++ b/src/stream/fmt/buf/streamio_manager/static_streamio_manager.hxx @@ -22,8 +22,8 @@ namespace stream::fmt::buf { } public: - [[nodiscard]] std::expected add_size(const std::size_t) override { - return std::unexpected(FMTResult::Manager_StaticMemory); + bool add_size(const std::size_t) override { + return false; } private: diff --git a/src/stream/fmt/buf/test_manip.hxx b/src/stream/fmt/buf/test_manip.hxx index ddc1c065..372ff95d 100644 --- a/src/stream/fmt/buf/test_manip.hxx +++ b/src/stream/fmt/buf/test_manip.hxx @@ -41,8 +41,11 @@ namespace stream::fmt::buf { public: template - constexpr bool is_same(const CharToTest* str, std::size_t size) const noexcept { - if (size > Access(buffer).get_buffer_remaining_size()) { + constexpr bool is_same(const CharToTest* str, std::size_t size, bool exact = false) const noexcept { + if (exact == true && size != buffer.get_buffer_remaining_size()) { + return false; + } + if (size > buffer.get_buffer_remaining_size()) { return false; } @@ -58,8 +61,8 @@ namespace stream::fmt::buf { return is_same; } template - constexpr inline bool is_same(std::basic_string_view sv) const noexcept { - return is_same(sv.data(), sv.size()); + constexpr inline bool is_same(std::basic_string_view sv, bool exact = false) const noexcept { + return is_same(sv.data(), sv.size(), false); } }; @@ -80,17 +83,17 @@ namespace stream::fmt::buf { public: template - [[nodiscard]] constexpr inline std::expected is_equal_to_forward(const CharToTest... ele) noexcept { + constexpr inline bool is_equal_to_forward(const CharToTest... ele) noexcept { if (access().is_equal_to(ele...)) { - SF_VERIFY(Manip(buffer).forward()); + Manip(buffer).forward(); return true; } return false; } template - [[nodiscard]] constexpr inline std::expected is_not_equal_forward(const CharToTest... ele) noexcept { + constexpr inline bool is_not_equal_forward(const CharToTest... ele) noexcept { if (access().is_not_equal_to(ele...)) { - SF_VERIFY(Manip(buffer).forward()); + Manip(buffer).forward(); return true; } return false; @@ -98,17 +101,17 @@ namespace stream::fmt::buf { public: template - [[nodiscard]] constexpr std::expected is_same_forward(const CharToTest* str, std::size_t size) noexcept { + constexpr bool is_same_forward(const CharToTest* str, std::size_t size) noexcept { if (access().is_same(str, size)) { - SF_VERIFY(Manip(buffer).forward(size)); + Manip(buffer).forward(size); return true; } return false; } template - [[nodiscard]] constexpr inline std::expected is_same_forward(std::basic_string_view sv) noexcept { + constexpr inline bool is_same_forward(std::basic_string_view sv) noexcept { if (access().is_same(sv)) { - SF_VERIFY(Manip(buffer).forward(sv.size())); + Manip(buffer).forward(sv.size()); return true; } return false; @@ -116,12 +119,11 @@ namespace stream::fmt::buf { public: template - [[nodiscard]] inline std::expected skip_one_of(const CharToTest... ele) noexcept { + void skip_one_of(const CharToTest... ele) noexcept { if (access().is_equal_to(ele...)) { - SF_VERIFY(Manip(buffer).forward()); - return {}; + Manip(buffer).forward(); } - return std::unexpected(FMTResult::Parse_TokenNotExpected); + throw std::runtime_error("fmt error: Parse_TokenNotExpected"); } template @@ -139,10 +141,10 @@ namespace stream::fmt::buf { } public: - [[nodiscard]] inline void IgnoreOneSpace() noexcept { + void IgnoreOneSpace() noexcept { return ignore_one_of(' ', '\t'); } - [[nodiscard]] inline void IgnoreOneBlank() noexcept { + void IgnoreOneBlank() noexcept { return ignore_one_of(' ', '\t', '\n', '\r', '\v'); } @@ -160,26 +162,23 @@ namespace stream::fmt::buf { Manip(buffer).forward_force(); } template - [[nodiscard]] inline std::expected go_to_forward(const CharToTest... ele) noexcept { + void go_to_forward(const CharToTest... ele) noexcept { GoTo(ele...); return Manip(buffer).forward(); } public: template - [[nodiscard]] std::expected, FMTResult> ViewExec(Func&& func) { + std::basic_string_view view_exec(Func&& func) { TChar* begin = buffer.current_pos; - SF_VERIFY(func()); + func(); TChar* end = buffer.current_pos; return std::basic_string_view(begin, end - begin); } template - [[nodiscard]] inline std::expected, FMTResult> view_until(CharToTest&&... c) { - return ViewExec([&] -> std::expected { - TestManip(buffer).GoTo(std::forward(c)...); - return {}; - }); + inline std::basic_string_view view_until(CharToTest&&... c) { + return view_exec([&] -> void { TestManip(buffer).GoTo(std::forward(c)...); }); } }; } // namespace stream::fmt::buf diff --git a/src/stream/fmt/buf/utils/buffer_globber_manip.hxx b/src/stream/fmt/buf/utils/buffer_globber_manip.hxx index 85ee160a..d8ffd346 100644 --- a/src/stream/fmt/buf/utils/buffer_globber_manip.hxx +++ b/src/stream/fmt/buf/utils/buffer_globber_manip.hxx @@ -13,40 +13,40 @@ namespace stream::fmt::buf { }; private: - [[nodiscard]] static std::expected buffer_exec_glob_(Stream& istream, Stream& glob) { - if (Access(glob).is_end_of_string()) { + static const TChar* buffer_exec_glob_(Stream& istream, Stream& glob) { + if (glob.is_end_of_string()) { return istream.current_pos; } - if (Access(istream).is_end_of_string()) { + if (istream.is_end_of_string()) { return nullptr; } if (TestAccess(glob).is_equal_to('?')) { - SF_VERIFY(Manip(glob).forward()); - SF_VERIFY(Manip(istream).forward()); + Manip(glob).forward(); + Manip(istream).forward(); return buffer_exec_glob_(istream, glob); } else if (TestAccess(glob).is_equal_to('*')) { - SF_VERIFY(Manip(glob).forward()); - const TChar* further = SF_TRY(buffer_exec_glob_(istream, glob)); + Manip(glob).forward(); + const TChar* further = buffer_exec_glob_(istream, glob); while (Access(istream).can_move_forward()) { - SF_VERIFY(Manip(istream).forward()); - const TChar* last = SF_TRY(buffer_exec_glob_(istream, glob)); + Manip(istream).forward(); + const TChar* last = buffer_exec_glob_(istream, glob); if (last > further || further == nullptr) further = last; } return further; } else if (TestAccess(glob).is_equal_to('[')) { - SF_VERIFY(Manip(istream).forward()); + Manip(istream).forward(); const TChar* begin = glob.current_pos; - SF_VERIFY(TestManip(glob).go_to_forward(']')); + TestManip(glob).go_to_forward(']'); const TChar* end = glob.current_pos; StreamView charSet(begin, end - begin); bool is_inverted = TestAccess(glob).is_equal_to('!'); TChar toMatch = istream.get(); - SF_VERIFY(Manip(glob).forward()); - SF_VERIFY(Manip(istream).forward()); + Manip(glob).forward(); + Manip(istream).forward(); bool found = false; while (found == false && Access(charSet).can_move_forward()) { @@ -75,19 +75,17 @@ namespace stream::fmt::buf { } if (istream.get() == glob.get()) { - SF_VERIFY(Manip(glob).forward()); - SF_VERIFY(Manip(istream).forward()); + Manip(glob).forward(); + Manip(istream).forward(); return buffer_exec_glob_(istream, glob); } return nullptr; } public: - [[nodiscard]] static std::expected buffer_exec_glob(Stream& istream, Stream& glob, - [[maybe_unused]] PatternMatchType patternMatchtype = PatternMatchType::MatchBiggest) { - const TChar* furtherPointMatched = SF_TRY(buffer_exec_glob_(istream, glob)); + static void buffer_exec_glob(Stream& istream, Stream& glob, [[maybe_unused]] PatternMatchType patternMatchtype = PatternMatchType::MatchBiggest) { + const TChar* furtherPointMatched = buffer_exec_glob_(istream, glob); if (furtherPointMatched != nullptr) istream.current_pos = furtherPointMatched; - return {}; } }; @@ -100,7 +98,7 @@ namespace stream::fmt::buf { Stream& buffer; public: - [[nodiscard]] std::expected fast_read_char_ptrGlobber(std::basic_string_view globPattern, TChar* str, std::size_t size_to_copy) { + void fast_read_char_ptrGlobber(std::basic_string_view globPattern, TChar* str, std::size_t size_to_copy) { Stream globber(globPattern); const TChar* begin = buffer.current_pos; Globber::buffer_exec_glob(*this, globber); @@ -110,8 +108,8 @@ namespace stream::fmt::buf { return ReadManip(subContext).fast_read_char_ptr(str, size_to_copy); } - [[nodiscard]] std::expected fast_read_char_ptrRegex(std::basic_string_view regexPattern, TChar* str, std::size_t size_to_copy) { - return std::unexpected(FMTResult::FunctionNotImpl); + void fast_read_char_ptrRegex(std::basic_string_view regexPattern, TChar* str, std::size_t size_to_copy) { + throw std::runtime_error("fmt error: FunctionNotImpl"); } }; } // namespace stream::fmt::buf diff --git a/src/stream/fmt/buf/utils/buffer_shift_manip.hxx b/src/stream/fmt/buf/utils/buffer_shift_manip.hxx index 76a05b1f..31ad6b34 100644 --- a/src/stream/fmt/buf/utils/buffer_shift_manip.hxx +++ b/src/stream/fmt/buf/utils/buffer_shift_manip.hxx @@ -13,40 +13,35 @@ namespace stream::fmt::buf { StreamIO& buffer; public: - [[nodiscard]] inline std::expected WriteShiftCenterBegin(detail::ShiftInfo& shift) { + void WriteShiftCenterBegin(detail::ShiftInfo& shift) { if (shift.type == detail::ShiftInfo::ShiftType::CenterRight || shift.type == detail::ShiftInfo::ShiftType::CenterLeft) { std::int32_t shift_ = shift.size / 2; if (shift.type == detail::ShiftInfo::ShiftType::CenterLeft) shift_ = (shift.size + 1) / 2; - SF_VERIFY(ManipIO(buffer).pushback(shift.print.before, shift.size - shift_)); + ManipIO(buffer).pushback(shift.print.before, shift.size - shift_); shift.size = shift_; } - - return {}; } - [[nodiscard]] inline std::expected WriteShiftCenterEnd(detail::ShiftInfo& shift) { + void WriteShiftCenterEnd(detail::ShiftInfo& shift) { if (shift.type == detail::ShiftInfo::ShiftType::CenterRight || shift.type == detail::ShiftInfo::ShiftType::CenterLeft) return ManipIO(buffer).pushback(shift.print.after, shift.size); - return {}; } - [[nodiscard]] inline std::expected write_shift_right_all(detail::ShiftInfo& shift) { + void write_shift_right_all(detail::ShiftInfo& shift) { if (shift.type == detail::ShiftInfo::ShiftType::Right) return ManipIO(buffer).pushback(shift.print.before, shift.size); - return {}; } - [[nodiscard]] inline std::expected WriteShiftLeftAll(detail::ShiftInfo& shift) { + void WriteShiftLeftAll(detail::ShiftInfo& shift) { if (shift.type == detail::ShiftInfo::ShiftType::Left) return ManipIO(buffer).pushback(shift.print.after, shift.size); - return {}; } - [[nodiscard]] inline std::expected write_shift_begin(detail::ShiftInfo& shift) { - SF_VERIFY(WriteShiftCenterBegin(shift)); + void write_shift_begin(detail::ShiftInfo& shift) { + WriteShiftCenterBegin(shift); return write_shift_right_all(shift); } - [[nodiscard]] inline std::expected write_shift_end(detail::ShiftInfo& shift) { - SF_VERIFY(WriteShiftLeftAll(shift)); + void write_shift_end(detail::ShiftInfo& shift) { + WriteShiftLeftAll(shift); return WriteShiftCenterEnd(shift); } }; @@ -60,27 +55,25 @@ namespace stream::fmt::buf { Stream& buffer; public: - [[nodiscard]] std::expected ignore_shift_begin_space(detail::ShiftInfo& shift) { - if (shift.print.before_is_a_digit() == false) return {}; + void ignore_shift_begin_space(detail::ShiftInfo& shift) { + if (shift.print.before_is_a_digit() == false) return; if (shift.type == detail::ShiftInfo::ShiftType::Right || shift.type == detail::ShiftInfo::ShiftType::CenterLeft || shift.type == detail::ShiftInfo::ShiftType::CenterRight) { while (buffer.get() == ' ') { - SF_VERIFY(Manip(buffer).forward()); + Manip(buffer).forward(); --shift.size; } } - return {}; } - [[nodiscard]] std::expected ignore_shift_end(detail::ShiftInfo& shift) { + void ignore_shift_end(detail::ShiftInfo& shift) { if (shift.type == detail::ShiftInfo::ShiftType::Left || shift.type == detail::ShiftInfo::ShiftType::CenterLeft || shift.type == detail::ShiftInfo::ShiftType::CenterRight) { while (buffer.get() == ' ' && shift.size > 0) { - SF_VERIFY(Manip(buffer).forward()); + Manip(buffer).forward(); --shift.size; } } - return {}; } }; } // namespace stream::fmt::buf diff --git a/src/stream/fmt/buf/utils/buffer_utils.hxx b/src/stream/fmt/buf/utils/buffer_utils.hxx index bbe06ab0..836390f7 100644 --- a/src/stream/fmt/buf/utils/buffer_utils.hxx +++ b/src/stream/fmt/buf/utils/buffer_utils.hxx @@ -23,12 +23,12 @@ namespace stream::fmt::buf { public: template - [[nodiscard]] std::expected get_word_from_list(const std::basic_string_view (&data)[SIZE]) { + std::optional get_word_from_list(const std::basic_string_view (&data)[SIZE]) { for (std::size_t idx = 0; idx < SIZE; ++idx) { - bool found = SF_TRY(TestManip(buffer).is_same_forward(data[idx])); + bool found = TestManip(buffer).is_same_forward(data[idx]); if (found) return idx; } - return std::unexpected(FMTResult::Specifiers_Invalid); + return std::nullopt; } // TODO: use static map ? @@ -36,83 +36,79 @@ namespace stream::fmt::buf { using DictPairs = std::pair, T>; template - [[nodiscard]] std::expected get_word_from_dict_pairs(const DictPairs (&data)[SIZE]) { + T get_word_from_dict_pairs(const DictPairs (&data)[SIZE]) { for (std::size_t idx = 0; idx < SIZE; ++idx) { - bool found = SF_TRY(TestManip(buffer).is_same_forward(data[idx].first)); + bool found = TestManip(buffer).is_same_forward(data[idx].first); if (found) return data[idx].second; } - return std::unexpected(FMTResult::Specifiers_Invalid); + throw std::runtime_error("fmt error: Specifiers_Invalid"); } }; namespace utils { template - [[nodiscard]] static std::expected parse_escaped_quoted_string(buf::Stream& buffer, buf::StreamIO& stringOut) { - SF_VERIFY(buf::TestManip(buffer).skip_one_of('"')); - while (buf::Access(buffer).is_end_of_string() == false) { - auto view = SF_TRY(buf::TestManip(buffer).view_until('"', '\\')); - SF_VERIFY(buf::WriteManip(stringOut).fast_write_string(view)); + static void parse_escaped_quoted_string(buf::Stream& buffer, buf::StreamIO& stringOut) { + buf::TestManip(buffer).skip_one_of('"'); + while (buffer.is_end_of_string() == false) { + auto view = buf::TestManip(buffer).view_until('"', '\\'); + buf::WriteManip(stringOut).fast_write_string(view); if (buf::TestAccess(buffer).is_equal_to('"')) { break; } - SF_VERIFY(buf::TestManip(buffer).skip_one_of('\\')); + buf::TestManip(buffer).skip_one_of('\\'); switch (buffer.get()) { // TODO : Do all others escape char case '"': - SF_VERIFY(buf::ManipIO(stringOut).pushback('"')); + buf::ManipIO(stringOut).pushback('"'); break; case 't': - SF_VERIFY(buf::ManipIO(stringOut).pushback('\t')); + buf::ManipIO(stringOut).pushback('\t'); break; case 'r': - SF_VERIFY(buf::ManipIO(stringOut).pushback('\r')); + buf::ManipIO(stringOut).pushback('\r'); break; case 'n': - SF_VERIFY(buf::ManipIO(stringOut).pushback('\n')); + buf::ManipIO(stringOut).pushback('\n'); break; default: break; } } - SF_VERIFY(buf::TestManip(buffer).skip_one_of('"')); - - return {}; + buf::TestManip(buffer).skip_one_of('"'); } template - [[nodiscard]] static std::expected format_escaped_quoted_string(buf::StreamIO& buffer, buf::Stream& string_in) { - SF_VERIFY(buf::ManipIO(buffer).pushback('"')); - while (buf::Access(string_in).is_end_of_string() == false) { - auto view = SF_TRY(buf::TestManip(string_in).view_until('\\')); - SF_VERIFY(buf::WriteManip(buffer).fast_write_string(view)); + static void format_escaped_quoted_string(buf::StreamIO& buffer, buf::Stream& string_in) { + buf::ManipIO(buffer).pushback('"'); + while (string_in.is_end_of_string() == false) { + auto view = buf::TestManip(string_in).view_until('\\'); + buf::WriteManip(buffer).fast_write_string(view); - if (buf::Access(string_in).is_end_of_string()) break; + if (string_in.is_end_of_string()) break; // TODO - SF_VERIFY(buf::TestManip(string_in).skip_one_of('\\')); + buf::TestManip(string_in).skip_one_of('\\'); switch (string_in.get()) { // TODO : Do all others escape char case '"': - SF_VERIFY(buf::ManipIO(buffer).pushback('"')); + buf::ManipIO(buffer).pushback('"'); break; case 't': - SF_VERIFY(buf::ManipIO(buffer).pushback('\t')); + buf::ManipIO(buffer).pushback('\t'); break; case 'r': - SF_VERIFY(buf::ManipIO(buffer).pushback('\r')); + buf::ManipIO(buffer).pushback('\r'); break; case 'n': - SF_VERIFY(buf::ManipIO(buffer).pushback('\n')); + buf::ManipIO(buffer).pushback('\n'); break; default: break; } } - SF_VERIFY(buf::ManipIO(buffer).pushback('"')); - - return {}; + buf::ManipIO(buffer).pushback('"'); } }; // namespace utils } // namespace stream::fmt::buf diff --git a/src/stream/fmt/buf/write_manip.hxx b/src/stream/fmt/buf/write_manip.hxx index 3b19a99f..0463073f 100644 --- a/src/stream/fmt/buf/write_manip.hxx +++ b/src/stream/fmt/buf/write_manip.hxx @@ -51,52 +51,50 @@ namespace stream::fmt::buf { public: template requires std::is_integral_v - [[nodiscard]] constexpr std::expected fast_write_integer(T i) { + constexpr void fast_write_integer(T i) { ManipIO manip(buffer); if (i == 0) { - SF_VERIFY(manip.pushback('0')); - return {}; + manip.pushback('0'); + return; } if constexpr (std::is_signed_v) { if (i < 0) { - SF_VERIFY(manip.pushback('-')); + manip.pushback('-'); i = -i; } } std::int32_t nb_digit = WriteUtils::get_number_of_digit_dec(i); - SF_VERIFY(manip.forward(nb_digit)); + manip.forward(nb_digit); while (i > 0) { Manip(buffer).backward_force(); ManipIO(buffer).set(i % 10 + '0'); i /= 10; } - SF_VERIFY(manip.forward(nb_digit)); - - return {}; + manip.forward(nb_digit); } public: template requires std::is_floating_point_v - [[nodiscard]] constexpr std::expected fast_write_float(T i, std::int32_t float_precision = 2) { + constexpr void fast_write_float(T i, std::int32_t float_precision = 2) { ManipIO manip(buffer); if (i == 0) { - SF_VERIFY(manip.pushback('0')); - return {}; + manip.pushback('0'); + return; } if (i < 0) { - SF_VERIFY(manip.pushback('-')); + manip.pushback('-'); i = -i; } T k = std::trunc(i); i = i - k; std::int32_t nb_digit = WriteUtils::get_number_of_digit_dec(k); - SF_VERIFY(manip.forward(nb_digit)); + manip.forward(nb_digit); std::int32_t nb_digit_ = nb_digit; while (nb_digit_ > 0) { Manip(buffer).backward_force(); @@ -104,40 +102,35 @@ namespace stream::fmt::buf { k /= 10; nb_digit_--; } - SF_VERIFY(manip.forward(nb_digit)); - SF_VERIFY(manip.pushback('.')); + manip.forward(nb_digit); + manip.pushback('.'); while (float_precision-- >= 0) { TChar intPart = static_cast(std::trunc(i *= 10)); - SF_VERIFY(manip.pushback(intPart + '0')); + manip.pushback(intPart + '0'); i -= intPart; } - - return {}; } public: template - [[nodiscard]] constexpr std::expected fast_write_char_array(const CharInput* str, std::size_t size) { - if (size == 0) return {}; + constexpr void fast_write_char_array(const CharInput* str, std::size_t size) { + if (size == 0) return; - auto reserve = ManipIO(buffer).reserve(size); - if (reserve.has_value() == false) return fast_write_char_array(str, Access(buffer).get_buffer_remaining_size()); + if (ManipIO(buffer).reserve(size) == false) return fast_write_char_array(str, buffer.get_buffer_remaining_size()); std::copy_n(str, size, buffer.current_pos); buffer.current_pos += size; - - return {}; } template - [[nodiscard]] inline constexpr std::expected fast_write_string(std::basic_string_view sv) { + inline constexpr void fast_write_string(std::basic_string_view sv) { return fast_write_char_array(sv.data(), sv.size()); } - [[nodiscard]] inline std::expected fast_write_string(std::basic_string_view sv) { + void fast_write_string(std::basic_string_view sv) { return fast_write_char_array(sv.data(), sv.size()); } template - [[nodiscard]] inline std::expected fast_write_string_literal(CharInput (&str)[SIZE]) { + void fast_write_string_literal(CharInput (&str)[SIZE]) { std::size_t size = SIZE; while (str[size - 1] == 0) { --size; @@ -147,29 +140,28 @@ namespace stream::fmt::buf { public: template - [[nodiscard]] inline std::expected basic_write_type(std::basic_string_view str) { + void basic_write_type(std::basic_string_view str) { return fast_write_string(str); } template - [[nodiscard]] inline std::expected basic_write_type(CharInput (&str)[SIZE]) { + void basic_write_type(CharInput (&str)[SIZE]) { return fast_write_string_literal(str); } template requires std::is_integral_v - [[nodiscard]] inline std::expected basic_write_type(T t) { + void basic_write_type(T t) { return fast_write_integer(t); } template requires std::is_floating_point_v - [[nodiscard]] inline std::expected basic_write_type(T t) { + void basic_write_type(T t) { return fast_write_float(t); } template - [[nodiscard]] inline std::expected basic_write_type(Type&& type, Rest&&... rest) { - SF_VERIFY(basic_write_type(type)); - if constexpr (sizeof...(rest) > 0) SF_VERIFY(basic_write_type(std::forward(rest)...)); - return {}; + void basic_write_type(Type&& type, Rest&&... rest) { + basic_write_type(type); + if constexpr (sizeof...(rest) > 0) basic_write_type(std::forward(rest)...); } }; } // namespace stream::fmt::buf diff --git a/src/stream/fmt/context/basic_context/basic_args_interface.hxx b/src/stream/fmt/context/basic_context/basic_args_interface.hxx index e255ad38..4d7231a7 100644 --- a/src/stream/fmt/context/basic_context/basic_args_interface.hxx +++ b/src/stream/fmt/context/basic_context/basic_args_interface.hxx @@ -32,27 +32,26 @@ namespace stream::fmt::detail { virtual size_t size() = 0; public: - [[nodiscard]] virtual std::expected get_pointerid_at(std::int32_t idx) = 0; - [[nodiscard]] virtual std::expected run_type_at(std::int32_t idx) = 0; - [[nodiscard]] virtual std::expected get_index_of_current_named_arg(buf::StreamView& format) = 0; - [[nodiscard]] virtual std::expected, FMTResult> get_string_at(std::int32_t idx) = 0; - [[nodiscard]] virtual std::expected get_int_at(std::int32_t idx) = 0; + virtual PointerID get_pointerid_at(std::int32_t idx) = 0; + virtual void run_type_at(std::int32_t idx) = 0; + virtual std::optional get_index_of_current_named_arg(buf::StreamView& format) = 0; + virtual typename std::basic_string_view get_string_at(std::int32_t idx) = 0; + virtual std::int64_t get_int_at(std::int32_t idx) = 0; public: template - [[nodiscard]] std::expected get_type_at(std::int32_t idx) { - PointerID ptr = SF_TRY(get_pointerid_at(idx)); + const T* get_type_at(std::int32_t idx) { + PointerID ptr = get_pointerid_at(idx); if (ptr.type_info != typeid(T)) { - return std::unexpected(FMTResult::ArgsInterface_InvalidTypeID); + throw std::runtime_error("fmt error: ArgsInterface_InvalidTypeID"); } return reinterpret_cast(ptr.ptr); } template - [[nodiscard]] std::expected run_func_from_type_at(std::int32_t idx, std::function(const T&)> func) { - const T* value = SF_TRY(get_type_at(idx)); - SF_VERIFY(func(*value)); - return {}; + void run_func_from_type_at(std::int32_t idx, std::function func) { + const T* value = get_type_at(idx); + func(*value); } }; @@ -68,20 +67,21 @@ namespace stream::fmt::detail { } public: - [[nodiscard]] std::expected get_pointerid_at(std::int32_t) override { - return std::unexpected(FMTResult::ArgsInterface_Unavaible); + PointerID get_pointerid_at(std::int32_t) override { + throw std::runtime_error("fmt error: ArgsInterface_Unavailble"); } - [[nodiscard]] std::expected run_type_at(std::int32_t) override { - return std::unexpected(FMTResult::ArgsInterface_Unavaible); + PointerID run_type_at(std::int32_t) override { + throw std::runtime_error("fmt error: ArgsInterface_Unavailble"); } - [[nodiscard]] std::expected get_index_of_current_named_arg(buf::StreamView&) override { - return std::unexpected(FMTResult::ArgsInterface_Unavaible); + std::optional get_index_of_current_named_arg(buf::StreamView&) override { + throw std::runtime_error("fmt error: ArgsInterface_Unavailble"); + return std::nullopt; } - [[nodiscard]] std::expected, FMTResult> get_string_at(std::int32_t) override { - return std::unexpected(FMTResult::ArgsInterface_Unavaible); + std::basic_string_view get_string_at(std::int32_t) override { + throw std::runtime_error("fmt error: ArgsInterface_Unavailble"); } - [[nodiscard]] std::expected get_int_at(std::int32_t) override { - return std::unexpected(FMTResult::ArgsInterface_Unavaible); + std::int64_t get_int_at(std::int32_t) override { + throw std::runtime_error("fmt error: ArgsInterface_Unavailble"); } }; } // namespace stream::fmt::detail diff --git a/src/stream/fmt/context/basic_context/basic_context.hxx b/src/stream/fmt/context/basic_context/basic_context.hxx index a61431ce..d108a90b 100644 --- a/src/stream/fmt/context/basic_context/basic_context.hxx +++ b/src/stream/fmt/context/basic_context/basic_context.hxx @@ -25,8 +25,8 @@ namespace stream::fmt::context { virtual ~context_executor() = default; public: - [[nodiscard]] virtual std::expected exec_settings() = 0; - [[nodiscard]] virtual std::expected exec_raw_string(std::basic_string_view) = 0; + virtual void exec_settings() = 0; + virtual void exec_raw_string(std::basic_string_view) = 0; public: detail::FormatData data; @@ -50,32 +50,32 @@ namespace stream::fmt::context { std::int32_t values_index; public: - [[nodiscard]] std::expected run(); + void run(); private: - [[nodiscard]] std::expected get_format_index_number(); - [[nodiscard]] std::expected get_format_index_name(); - [[nodiscard]] std::expected get_format_index_sub_index(); + std::optional get_format_index_number(); + std::optional get_format_index_name(); + std::optional get_format_index_sub_index(); public: - [[nodiscard]] std::expected get_format_index(); + std::optional get_format_index(); template - [[nodiscard]] std::expected format_read_parameter(const T& default_value); + T format_read_parameter(const T& default_value); protected: void formatdata_apply_next_override(); protected: - [[nodiscard]] std::expected, FMTResult> parse_next_override_format_data(); + std::basic_string_view parse_next_override_format_data(); - [[nodiscard]] std::expected parse_format_data_base(); - [[nodiscard]] std::expected parse_format_dataSpecial(); - [[nodiscard]] std::expected parse_format_data_special_shift_type(const detail::ShiftInfo::ShiftType type); - [[nodiscard]] std::expected parse_format_dataCustom(); - [[nodiscard]] std::expected parse_format_data(); + void parse_format_data_base(); + void parse_format_data_special(); + void parse_format_data_special_shift_type(const detail::ShiftInfo::ShiftType type); + void parse_format_dataCustom(); + void parse_format_data(); - [[nodiscard]] std::expected parse_variable(std::int32_t formatIdx); - [[nodiscard]] std::expected parse(); + void parse_variable(std::int32_t format_idx); + void parse(); public: template @@ -95,22 +95,20 @@ namespace stream::fmt::context { : executor(executor), fmtstream{format}, args_interface{args_interface}, values_index{0} {} template - [[nodiscard]] std::expected BasicContext::run() { - while (!buf::Access(fmtstream).is_end_of_string()) { + void BasicContext::run() { + while (!fmtstream.is_end_of_string()) { const TChar* begin_continuous_string = fmtstream.current_pos; std::size_t size_continuous_string = 0; - while (buf::Access(fmtstream).is_end_of_string() == false && buf::TestAccess(fmtstream).is_equal_to('{') == false) { + while (fmtstream.is_end_of_string() == false && buf::TestAccess(fmtstream).is_equal_to('{') == false) { ++size_continuous_string; - SF_VERIFY(buf::Manip(fmtstream).forward()); + buf::Manip(fmtstream).forward(); } - SF_VERIFY(executor.exec_raw_string(std::basic_string_view(begin_continuous_string, size_continuous_string))); + executor.exec_raw_string(std::basic_string_view(begin_continuous_string, size_continuous_string)); - if (buf::Access(fmtstream).is_end_of_string() == false && buf::TestAccess(fmtstream).is_equal_to('{')) { - SF_VERIFY(parse()); + if (fmtstream.is_end_of_string() == false && buf::TestAccess(fmtstream).is_equal_to('{')) { + parse(); } } - - return {}; } template @@ -128,22 +126,22 @@ namespace stream::fmt::context { template template - [[nodiscard]] std::expected BasicContext::format_read_parameter(const T& default_value) { + T BasicContext::format_read_parameter(const T& default_value) { if (!buf::TestAccess(fmtstream).is_equal_to('{')) { T t; - SF_VERIFY(buf::ReadManip(fmtstream).fast_read_integer(t)); + buf::ReadManip(fmtstream).fast_read_integer(t); return t; } // SubIndex - SF_VERIFY(buf::TestManip(fmtstream).skip_one_of('}')); - std::int32_t formatIdx = SF_TRY(get_format_index()); + buf::TestManip(fmtstream).skip_one_of('{'); + std::optional format_idx = get_format_index(); if constexpr (std::is_convertible_v) - return args_interface.get_int_at(formatIdx); + return args_interface.get_int_at(format_idx.value()); else if constexpr (std::is_convertible_v>) - return args_interface.get_string_at(formatIdx); + return args_interface.get_string_at(format_idx.value()); - return std::unexpected(FMTResult::Context_ArgumentIndexExpected); + throw std::runtime_error("fmt error: Context_ArgumentIndexExpected"); } } // namespace stream::fmt::context diff --git a/src/stream/fmt/context/basic_context/basic_context_parse_impl.hxx b/src/stream/fmt/context/basic_context/basic_context_parse_impl.hxx index 7242ec95..40d6c40c 100644 --- a/src/stream/fmt/context/basic_context/basic_context_parse_impl.hxx +++ b/src/stream/fmt/context/basic_context/basic_context_parse_impl.hxx @@ -11,7 +11,7 @@ namespace stream::fmt::context { template - [[nodiscard]] std::expected, FMTResult> BasicContext::parse_next_override_format_data() { + std::basic_string_view BasicContext::parse_next_override_format_data() { // TODO: check that function buf::TestAccess access(fmtstream); buf::TestManip manip(fmtstream); @@ -24,18 +24,18 @@ namespace stream::fmt::context { buf::FMTParamsManip(fmtstream).param_go_to('{'); const TChar* begin = fmtstream.current_pos; - SF_VERIFY(manip.skip_one_of('{')); + manip.skip_one_of('{'); int scopes = 0; while (buf::FMTParamsManip(fmtstream).is_end_of_parameter() == false || scopes > 0) { manip.GoTo('\'', '}', '{'); if (access.is_equal_to('\'')) { - SF_VERIFY(buf::Manip(fmtstream).forward()); + buf::Manip(fmtstream).forward(); manip.go_to_forward('\''); } else if (access.is_equal_to('{')) { - SF_VERIFY(buf::Manip(fmtstream).forward()); + buf::Manip(fmtstream).forward(); scopes++; } else if (scopes > 0 && access.is_equal_to('}')) { - SF_VERIFY(buf::Manip(fmtstream).forward()); + buf::Manip(fmtstream).forward(); scopes--; } } @@ -45,216 +45,210 @@ namespace stream::fmt::context { } template - [[nodiscard]] std::expected BasicContext::parse_format_data_base() { + void BasicContext::parse_format_data_base() { buf::TestAccess access(fmtstream); if (access.is_equal_to('C')) { - SF_VERIFY(buf::Manip(fmtstream).forward()); - SF_VERIFY(executor.text_manager.parse_color(*this)); + buf::Manip(fmtstream).forward(); + executor.text_manager.parse_color(*this); } else if (access.is_equal_to('S')) { - SF_VERIFY(buf::Manip(fmtstream).forward()); - SF_VERIFY(executor.text_manager.parse_style(*this)); + buf::Manip(fmtstream).forward(); + executor.text_manager.parse_style(*this); } else if (access.is_equal_to('F')) { - SF_VERIFY(buf::Manip(fmtstream).forward()); - SF_VERIFY(executor.text_manager.parse_front(*this)); + buf::Manip(fmtstream).forward(); + executor.text_manager.parse_front(*this); } else if (access.is_equal_to('K')) { - SF_VERIFY(buf::Manip(fmtstream).forward()); + buf::Manip(fmtstream).forward(); executor.data.keep_new_style = true; } else if (access.is_equal_to('N')) { - SF_VERIFY(buf::Manip(fmtstream).forward()); - executor.data.next_override = SF_TRY(parse_next_override_format_data()); + buf::Manip(fmtstream).forward(); + executor.data.next_override = parse_next_override_format_data(); } - - return {}; } template - [[nodiscard]] std::expected BasicContext::parse_format_data_special_shift_type(const detail::ShiftInfo::ShiftType type) { + void BasicContext::parse_format_data_special_shift_type(const detail::ShiftInfo::ShiftType type) { executor.data.shift.type = type; - executor.data.shift.size = SF_TRY(format_read_parameter(-1)); + executor.data.shift.size = format_read_parameter(-1); if (buf::TestAccess(fmtstream).is_equal_to(':')) { - SF_VERIFY(buf::Manip(fmtstream).forward()); + buf::Manip(fmtstream).forward(); executor.data.shift.print.before = fmtstream.get(); executor.data.shift.print.after = executor.data.shift.print.before; - SF_VERIFY(buf::Manip(fmtstream).forward()); + buf::Manip(fmtstream).forward(); if (buf::TestAccess(fmtstream).is_equal_to('|')) { - SF_VERIFY(buf::Manip(fmtstream).forward()); + buf::Manip(fmtstream).forward(); executor.data.shift.print.after = fmtstream.get(); - SF_VERIFY(buf::Manip(fmtstream).forward()); + buf::Manip(fmtstream).forward(); } } - return {}; } template - [[nodiscard]] std::expected BasicContext::parse_format_dataSpecial() { + void BasicContext::parse_format_data_special() { buf::TestAccess access(fmtstream); buf::TestManip manip(fmtstream); if (access.is_equal_to('{')) { - SF_VERIFY(buf::Manip(fmtstream).forward()); - std::int32_t formatIndex = SF_TRY(get_format_index()); - bool ableToapply = false; - - auto applyFormatData = SF_TRY(args_interface.template get_type_at>(formatIndex)); - ableToapply |= executor.data.testapply(applyFormatData); - auto applyFormatSpecifier = SF_TRY(args_interface.template get_type_at>(formatIndex)); - ableToapply |= executor.data.testapply(applyFormatSpecifier); - auto applyIntegerPrintBase = SF_TRY(args_interface.template get_type_at(formatIndex)); - ableToapply |= executor.data.testapply(applyIntegerPrintBase); - auto applyShiftInfo = SF_TRY(args_interface.template get_type_at(formatIndex)); - ableToapply |= executor.data.testapply(applyShiftInfo); + buf::Manip(fmtstream).forward(); + std::optional format_index = get_format_index(); + + bool ableToapply = false; + if (format_index.has_value()) { + auto applyFormatData = args_interface.template get_type_at>(format_index.value()); + ableToapply |= executor.data.testapply(applyFormatData); + auto applyFormatSpecifier = args_interface.template get_type_at>(format_index.value()); + ableToapply |= executor.data.testapply(applyFormatSpecifier); + auto applyIntegerPrintBase = args_interface.template get_type_at(format_index.value()); + ableToapply |= executor.data.testapply(applyIntegerPrintBase); + auto applyShiftInfo = args_interface.template get_type_at(format_index.value()); + ableToapply |= executor.data.testapply(applyShiftInfo); + } if (not ableToapply) { - return std::unexpected(FMTResult::Context_CannotapplyType); + throw std::runtime_error("fmt error: Context_CannotapplyType"); } - SF_VERIFY(manip.skip_one_of('}')); + manip.skip_one_of('}'); } else if (access.is_equal_to('.')) { - SF_VERIFY(buf::Manip(fmtstream).forward()); - executor.data.float_precision = SF_TRY(format_read_parameter(-1)); + buf::Manip(fmtstream).forward(); + executor.data.float_precision = format_read_parameter(-1); } else if (access.is_equal_to('d', 'b', 'b', 'o', 'O', 'x', 'X')) { executor.data.integer_print = static_cast(fmtstream.get()); - SF_VERIFY(buf::Manip(fmtstream).forward()); + buf::Manip(fmtstream).forward(); } else if (access.is_equal_to('#')) { - SF_VERIFY(buf::Manip(fmtstream).forward()); + buf::Manip(fmtstream).forward(); executor.data.prefix_suffix = true; } else if (access.is_equal_to('>')) { - SF_VERIFY(buf::Manip(fmtstream).forward()); - SF_VERIFY(parse_format_data_special_shift_type(detail::ShiftInfo::ShiftType::Right)); + buf::Manip(fmtstream).forward(); + parse_format_data_special_shift_type(detail::ShiftInfo::ShiftType::Right); } else if (access.is_equal_to('<')) { - SF_VERIFY(buf::Manip(fmtstream).forward()); - SF_VERIFY(parse_format_data_special_shift_type(detail::ShiftInfo::ShiftType::Left)); + buf::Manip(fmtstream).forward(); + parse_format_data_special_shift_type(detail::ShiftInfo::ShiftType::Left); } else if (access.is_equal_to('^')) { - SF_VERIFY(buf::Manip(fmtstream).forward()); + buf::Manip(fmtstream).forward(); if (access.is_equal_to('<')) { - SF_VERIFY(buf::Manip(fmtstream).forward()); - SF_VERIFY(parse_format_data_special_shift_type(detail::ShiftInfo::ShiftType::CenterLeft)); + buf::Manip(fmtstream).forward(); + parse_format_data_special_shift_type(detail::ShiftInfo::ShiftType::CenterLeft); } else { manip.ignore_one_of('>'); - SF_VERIFY(parse_format_data_special_shift_type(detail::ShiftInfo::ShiftType::CenterRight)); + parse_format_data_special_shift_type(detail::ShiftInfo::ShiftType::CenterRight); } } - - return {}; } template - [[nodiscard]] std::expected BasicContext::parse_format_dataCustom() { + void BasicContext::parse_format_dataCustom() { buf::TestAccess access(fmtstream); buf::TestManip manip(fmtstream); - std::basic_string_view name = SF_TRY(manip.ViewExec([&] -> std::expected { - buf::FMTParamsManip(fmtstream).param_go_to(' ', '=', '\'', '{', ','); - return {}; - })); + std::basic_string_view name = manip.view_exec([&] -> void { buf::FMTParamsManip(fmtstream).param_go_to(' ', '=', '\'', '{', ','); }); buf::FMTParamsManip(fmtstream).param_go_to('=', '\'', '{', ','); manip.ignore_one_of('='); manip.ignore_every_spaces(); if (access.is_equal_to('\'')) { - SF_VERIFY(buf::Manip(fmtstream).forward()); - std::basic_string_view value = SF_TRY(buf::TestManip(fmtstream).view_until('\'')); - SF_VERIFY(executor.data.specifiers.concat(detail::FormatSpecifier{name, value})); + buf::Manip(fmtstream).forward(); + std::basic_string_view value = buf::TestManip(fmtstream).view_until('\''); + executor.data.specifiers.concat(detail::FormatSpecifier{name, value}); } else if (access.is_a_digit()) { std::int32_t value = 0; - SF_VERIFY(buf::ReadManip(fmtstream).fast_read_integer(value)); - SF_VERIFY(executor.data.specifiers.concat(detail::FormatSpecifier{name, value})); + buf::ReadManip(fmtstream).fast_read_integer(value); + executor.data.specifiers.concat(detail::FormatSpecifier{name, value}); } else if (access.is_equal_to('{')) { - SF_VERIFY(buf::Manip(fmtstream).forward()); - std::int32_t idx = SF_TRY(get_format_index()); + buf::Manip(fmtstream).forward(); + std::optional idx = get_format_index(); // TODO / FIXME // executor.data.specifiers.concat(detail::FormatSpecifier{name, GetTypeAtIndexAuto(idx)}); - SF_VERIFY(manip.skip_one_of('}')); + manip.skip_one_of('}'); } else if (access.is_equal_to(',', '}')) { - SF_VERIFY(executor.data.specifiers.concat(detail::FormatSpecifier{name})); + executor.data.specifiers.concat(detail::FormatSpecifier{name}); } - - return {}; } /////---------- Impl ----------///// template - [[nodiscard]] std::expected BasicContext::parse_format_data() { + void BasicContext::parse_format_data() { buf::TestAccess access(fmtstream); buf::TestManip manip(fmtstream); executor.data.has_spec = true; - while (buf::Access(fmtstream).is_end_of_string() == false && buf::FMTParamsManip(fmtstream).is_end_of_parameter() == false) { + while (fmtstream.is_end_of_string() == false && buf::FMTParamsManip(fmtstream).is_end_of_parameter() == false) { manip.ignore_every_spaces(); if (access.is_upper_case()) { - SF_VERIFY(parse_format_data_base()); + parse_format_data_base(); } else if (!access.is_lower_case()) { - SF_VERIFY(parse_format_dataSpecial()); + parse_format_data_special(); } else { - SF_VERIFY(parse_format_dataCustom()); + parse_format_dataCustom(); } buf::FMTParamsManip(fmtstream).param_go_to(','); buf::TestManip(fmtstream).ignore_one_of(','); } - return {}; } template - [[nodiscard]] std::expected BasicContext::get_format_index_number() { + std::optional BasicContext::get_format_index_number() { std::int32_t index = -1; - SF_VERIFY(buf::ReadManip(fmtstream).fast_read_integer(index)); - + buf::ReadManip(fmtstream).fast_read_integer(index); if (buf::TestAccess(fmtstream).is_equal_to(':') || buf::TestAccess(fmtstream).is_equal_to('}')) { if (index >= 0 && index < args_interface.size()) { return index; } } - - return std::unexpected(FMTResult::Context_ArgumentIndexResolution); + return std::nullopt; } template - [[nodiscard]] std::expected BasicContext::get_format_index_name() { - std::int32_t index = SF_TRY(args_interface.get_index_of_current_named_arg(fmtstream)); + std::optional BasicContext::get_format_index_name() { + std::optional index = args_interface.get_index_of_current_named_arg(fmtstream); + if (index.has_value() == false) return std::nullopt; if (buf::TestAccess(fmtstream).is_equal_to(':') || buf::TestAccess(fmtstream).is_equal_to('}')) { if (index >= 0 && index < args_interface.size()) { return index; } } - - return std::unexpected(FMTResult::Context_ArgumentIndexResolution); + return std::nullopt; } template - [[nodiscard]] std::expected BasicContext::get_format_index_sub_index() { + std::optional BasicContext::get_format_index_sub_index() { buf::TestAccess access(fmtstream); buf::TestManip manip(fmtstream); if (access.is_equal_to('{')) { - SF_VERIFY(buf::Manip(fmtstream).forward()); - std::int32_t rec_index = SF_TRY(get_format_index()); + buf::Manip(fmtstream).forward(); + std::optional rec_index = get_format_index(); + if (rec_index.has_value() == false) { + return std::nullopt; + } if (access.is_equal_to('}') && rec_index >= 0 && rec_index < args_interface.size()) { - SF_VERIFY(buf::Manip(fmtstream).forward()); + buf::Manip(fmtstream).forward(); manip.ignore_every_spaces(); if (access.is_equal_to(':', '}')) { - std::int32_t final_rec_index = (std::int32_t)SF_TRY(args_interface.get_int_at(rec_index)); - if (final_rec_index >= 0 && final_rec_index < args_interface.size()) return final_rec_index; + std::int32_t final_rec_index = (std::int32_t)args_interface.get_int_at(rec_index.value()); + if (final_rec_index >= 0 && final_rec_index < args_interface.size()) { + return final_rec_index; + } } } } - return std::unexpected(FMTResult::Context_ArgumentIndexResolution); + return std::nullopt; } template - [[nodiscard]] std::expected BasicContext::get_format_index() { + std::optional BasicContext::get_format_index() { buf::TestAccess access(fmtstream); // I : if there is no number specified : ':' or '}' @@ -275,58 +269,55 @@ namespace stream::fmt::context { // VI : { which is a idx to an argument if (access.is_equal_to('{')) { - const TChar* oldPos = fmtstream.current_pos; - std::expected res = get_format_index_sub_index(); - if (res.has_value() == false && res.error() == FMTResult::Context_ArgumentIndexResolution) { + const TChar* oldPos = fmtstream.current_pos; + std::optional res = get_format_index_sub_index(); + if (res.has_value() == false) { fmtstream.current_pos = oldPos; - return std::unexpected(FMTResult::Context_ArgumentIndexResolution); + return std::nullopt; } return res; } - return std::unexpected(FMTResult::Context_ArgumentIndexResolution); + return std::nullopt; } template - [[nodiscard]] std::expected BasicContext::parse_variable(std::int32_t formatIdx) { + void BasicContext::parse_variable(std::int32_t format_idx) { detail::FormatData saveFormatData = executor.data; executor.data = detail::FormatData{}; detail::TextProperties::Properties saveTextProperties = executor.text_manager.save(); if (buf::TestAccess(fmtstream).is_equal_to(':', '{')) { - SF_VERIFY(buf::Manip(fmtstream).forward()); - SF_VERIFY(parse_format_data()); + buf::Manip(fmtstream).forward(); + parse_format_data(); } - SF_VERIFY(args_interface.run_type_at(formatIdx)); + args_interface.run_type_at(format_idx); if (executor.data.keep_new_style == false) { - SF_VERIFY(executor.text_manager.reload(saveTextProperties)); + executor.text_manager.reload(saveTextProperties); } executor.data = saveFormatData; - - return {}; } template - [[nodiscard]] std::expected BasicContext::parse() { + void BasicContext::parse() { buf::Manip(fmtstream).forward(); // Ignore { if (buf::TestAccess(fmtstream).is_upper_case()) { - SF_VERIFY(parse_format_data()); + parse_format_data(); return buf::FMTParamsManip(fmtstream).param_go_to_forward(); // Ignore } } - auto formatIdx = get_format_index(); - if (formatIdx.has_value()) { - if (formatIdx.value() >= 0 && formatIdx.value() < args_interface.size()) { - SF_VERIFY(parse_variable(formatIdx.value())); + std::optional format_idx = get_format_index(); + if (format_idx.has_value()) { + if (format_idx >= 0 && format_idx < args_interface.size()) { + parse_variable(format_idx.value()); return buf::FMTParamsManip(fmtstream).param_go_to_forward(); // Ignore } } } - SF_VERIFY(executor.exec_raw_string("{")); - return {}; + executor.exec_raw_string("{"); } } // namespace stream::fmt::context diff --git a/src/stream/fmt/context/basic_context/text_properties_executor.hxx b/src/stream/fmt/context/basic_context/text_properties_executor.hxx index a6ee8ad8..19683342 100644 --- a/src/stream/fmt/context/basic_context/text_properties_executor.hxx +++ b/src/stream/fmt/context/basic_context/text_properties_executor.hxx @@ -12,35 +12,35 @@ namespace stream::fmt::detail { virtual void link_to_executor(void* executor) = 0; public: - [[nodiscard]] virtual std::expected all_properties_reset() = 0; + virtual void all_properties_reset() = 0; public: - [[nodiscard]] virtual std::expected reset_color() = 0; - [[nodiscard]] virtual std::expected execute_color(const TextProperties::TextColor::BasicColorFG& t) = 0; - [[nodiscard]] virtual std::expected execute_color(const TextProperties::TextColor::BasicColorBG& t) = 0; - [[nodiscard]] virtual std::expected execute_color(const TextProperties::TextColor::BasicColor& t) = 0; - [[nodiscard]] virtual std::expected execute_color(const TextProperties::TextColor::Color24bFG& t) = 0; - [[nodiscard]] virtual std::expected execute_color(const TextProperties::TextColor::Color24bBG& t) = 0; - [[nodiscard]] virtual std::expected execute_color(const TextProperties::TextColor::Color24b& t) = 0; - [[nodiscard]] virtual std::expected execute_color(const TextProperties::TextColor::ColorCubeFG& t) = 0; - [[nodiscard]] virtual std::expected execute_color(const TextProperties::TextColor::ColorCubeBG& t) = 0; - [[nodiscard]] virtual std::expected execute_color(const TextProperties::TextColor::ColorCube& t) = 0; + virtual void reset_color() = 0; + virtual void execute_color(const TextProperties::TextColor::BasicColorFG& t) = 0; + virtual void execute_color(const TextProperties::TextColor::BasicColorBG& t) = 0; + virtual void execute_color(const TextProperties::TextColor::BasicColor& t) = 0; + virtual void execute_color(const TextProperties::TextColor::Color24bFG& t) = 0; + virtual void execute_color(const TextProperties::TextColor::Color24bBG& t) = 0; + virtual void execute_color(const TextProperties::TextColor::Color24b& t) = 0; + virtual void execute_color(const TextProperties::TextColor::ColorCubeFG& t) = 0; + virtual void execute_color(const TextProperties::TextColor::ColorCubeBG& t) = 0; + virtual void execute_color(const TextProperties::TextColor::ColorCube& t) = 0; public: - [[nodiscard]] virtual std::expected reset_front() = 0; - [[nodiscard]] virtual std::expected execute_front(const TextProperties::TextFront::FrontID& t) = 0; + virtual void reset_front() = 0; + virtual void execute_front(const TextProperties::TextFront::FrontID& t) = 0; public: - [[nodiscard]] virtual std::expected reset_style() = 0; - [[nodiscard]] virtual std::expected execute_style(const TextProperties::TextStyle::Intensity& t) = 0; - [[nodiscard]] virtual std::expected execute_style(const TextProperties::TextStyle::Italic& t) = 0; - [[nodiscard]] virtual std::expected execute_style(const TextProperties::TextStyle::Underline& t) = 0; - [[nodiscard]] virtual std::expected execute_style(const TextProperties::TextStyle::UnderlineColor::Color& t) = 0; - [[nodiscard]] virtual std::expected execute_style(const TextProperties::TextStyle::UnderlineColor::ColorCube& t) = 0; - [[nodiscard]] virtual std::expected execute_style(const TextProperties::TextStyle::UnderlineColor::Color24b& t) = 0; - [[nodiscard]] virtual std::expected execute_style(const TextProperties::TextStyle::Blink& t) = 0; - [[nodiscard]] virtual std::expected execute_style(const TextProperties::TextStyle::Inverted& t) = 0; - [[nodiscard]] virtual std::expected execute_style(const TextProperties::TextStyle::Ideogram& t) = 0; - [[nodiscard]] virtual std::expected execute_style(const TextProperties::TextStyle::Script& t) = 0; + virtual void reset_style() = 0; + virtual void execute_style(const TextProperties::TextStyle::Intensity& t) = 0; + virtual void execute_style(const TextProperties::TextStyle::Italic& t) = 0; + virtual void execute_style(const TextProperties::TextStyle::Underline& t) = 0; + virtual void execute_style(const TextProperties::TextStyle::UnderlineColor::Color& t) = 0; + virtual void execute_style(const TextProperties::TextStyle::UnderlineColor::ColorCube& t) = 0; + virtual void execute_style(const TextProperties::TextStyle::UnderlineColor::Color24b& t) = 0; + virtual void execute_style(const TextProperties::TextStyle::Blink& t) = 0; + virtual void execute_style(const TextProperties::TextStyle::Inverted& t) = 0; + virtual void execute_style(const TextProperties::TextStyle::Ideogram& t) = 0; + virtual void execute_style(const TextProperties::TextStyle::Script& t) = 0; }; } // namespace stream::fmt::detail diff --git a/src/stream/fmt/context/basic_context/text_properties_manager.cxx b/src/stream/fmt/context/basic_context/text_properties_manager.cxx index 3c552a4e..fe5338bf 100644 --- a/src/stream/fmt/context/basic_context/text_properties_manager.cxx +++ b/src/stream/fmt/context/basic_context/text_properties_manager.cxx @@ -1,7 +1,7 @@ #include "text_properties_manager.hxx" namespace stream::fmt::detail { - [[nodiscard]] std::expected TextPropertiesapplyManager::reload_color_fg(const TextProperties::TextColor::ColorFG& target) { + void TextPropertiesapplyManager::reload_color_fg(const TextProperties::TextColor::ColorFG& target) { if (target.type != current_context_properties_.color.fg.type) { switch (target.type) { case TextProperties::TextColor::ColorType::BasicColor: @@ -24,10 +24,9 @@ namespace stream::fmt::detail { break; } } - return {}; } - [[nodiscard]] std::expected TextPropertiesapplyManager::reload_color_bg(const TextProperties::TextColor::ColorBG& target) { + void TextPropertiesapplyManager::reload_color_bg(const TextProperties::TextColor::ColorBG& target) { if (target.type != current_context_properties_.color.bg.type) { switch (target.type) { case TextProperties::TextColor::ColorType::BasicColor: @@ -50,52 +49,51 @@ namespace stream::fmt::detail { break; } } - return {}; } // NOLINTBEGIN(readability-function-cognitive-complexity) - [[nodiscard]] std::expected TextPropertiesapplyManager::reload_style(const TextProperties::TextStyle::Style& target) { + void TextPropertiesapplyManager::reload_style(const TextProperties::TextStyle::Style& target) { if (target.intensity != current_context_properties_.style.intensity) { - SF_VERIFY(apply_style(target.intensity)); + apply_style(target.intensity); current_context_properties_.style.intensity = target.intensity; } if (target.italic != current_context_properties_.style.italic) { - SF_VERIFY(apply_style(target.italic)); + apply_style(target.italic); current_context_properties_.style.italic = target.italic; } if (target.blink != current_context_properties_.style.blink) { - SF_VERIFY(apply_style(target.blink)); + apply_style(target.blink); current_context_properties_.style.blink = target.blink; } if (target.inverted != current_context_properties_.style.inverted) { - SF_VERIFY(apply_style(target.inverted)); + apply_style(target.inverted); current_context_properties_.style.inverted = target.inverted; } if (target.ideogram != current_context_properties_.style.ideogram) { - SF_VERIFY(apply_style(target.ideogram)); + apply_style(target.ideogram); current_context_properties_.style.ideogram = target.ideogram; } if (target.script != current_context_properties_.style.script) { - SF_VERIFY(apply_style(target.script)); + apply_style(target.script); current_context_properties_.style.script = target.script; } if (target.underline != current_context_properties_.style.underline) { - SF_VERIFY(apply_style(target.underline)); + apply_style(target.underline); current_context_properties_.style.underline = target.underline; } if (target.underline_color.type != current_context_properties_.style.underline_color.type) { switch (target.underline_color.type) { case TextProperties::TextStyle::UnderlineColor::ColorType::Default: - SF_VERIFY(apply_style(TextProperties::TextStyle::UnderlineColor::ColorCube{TextProperties::TextStyle::UnderlineColor::ColorCube::Default})); + apply_style(TextProperties::TextStyle::UnderlineColor::ColorCube{TextProperties::TextStyle::UnderlineColor::ColorCube::Default}); break; case TextProperties::TextStyle::UnderlineColor::ColorType::ColorCube: - SF_VERIFY(apply_style(target.underline_color.data.color_cube)); + apply_style(target.underline_color.data.color_cube); current_context_properties_.style.underline_color.data.color_cube = target.underline_color.data.color_cube; break; case TextProperties::TextStyle::UnderlineColor::ColorType::Color24b: - SF_VERIFY(apply_style(target.underline_color.data.color24b)); + apply_style(target.underline_color.data.color24b); current_context_properties_.style.underline_color.data.color24b = target.underline_color.data.color24b; break; } @@ -106,27 +104,25 @@ namespace stream::fmt::detail { break; case TextProperties::TextStyle::UnderlineColor::ColorType::ColorCube: if (current_context_properties_.style.underline_color.data.color_cube != target.underline_color.data.color_cube) { - SF_VERIFY(apply_style(target.underline_color.data.color_cube)); + apply_style(target.underline_color.data.color_cube); current_context_properties_.style.underline_color.data.color_cube = target.underline_color.data.color_cube; } break; case TextProperties::TextStyle::UnderlineColor::ColorType::Color24b: if (current_context_properties_.style.underline_color.data.color24b != target.underline_color.data.color24b) { - SF_VERIFY(apply_style(target.underline_color.data.color24b)); + apply_style(target.underline_color.data.color24b); current_context_properties_.style.underline_color.data.color24b = target.underline_color.data.color24b; } break; } } - return {}; } // NOLINTEND(readability-function-cognitive-complexity) - [[nodiscard]] std::expected TextPropertiesapplyManager::reload_front(const TextProperties::TextFront::Front& target) { - if (current_context_properties_.front == target) return {}; + void TextPropertiesapplyManager::reload_front(const TextProperties::TextFront::Front& target) { + if (current_context_properties_.front == target) return; - SF_VERIFY(apply_front(target.current_id)); + apply_front(target.current_id); current_context_properties_.front = target; - return {}; } } // namespace stream::fmt::detail diff --git a/src/stream/fmt/context/basic_context/text_properties_manager.hxx b/src/stream/fmt/context/basic_context/text_properties_manager.hxx index 12ef5939..011f343c 100644 --- a/src/stream/fmt/context/basic_context/text_properties_manager.hxx +++ b/src/stream/fmt/context/basic_context/text_properties_manager.hxx @@ -12,44 +12,44 @@ namespace stream::fmt::detail { public: TextPropertiesapplyManager(ITextPropertiesExecutor& text_properties_executor) : text_properties_executor_{text_properties_executor}, current_context_properties_{} {} - [[nodiscard]] std::expected terminate() { + void terminate() { return reload_default(); } public: template requires detail::text_properties_color_can_apply - [[nodiscard]] std::expected apply_color(const T& modif) { + void apply_color(const T& modif) { current_context_properties_.color.apply(modif); return text_properties_executor_.execute_color(modif); } template requires detail::text_properties_style_can_apply - [[nodiscard]] std::expected apply_style(const T& modif) { + void apply_style(const T& modif) { current_context_properties_.style.apply(modif); return text_properties_executor_.execute_style(modif); } template requires detail::text_properties_front_can_apply - [[nodiscard]] std::expected apply_front(const T& modif) { + void apply_front(const T& modif) { current_context_properties_.front.apply(modif); return text_properties_executor_.execute_front(modif); } - [[nodiscard]] std::expected all_properties_reset() { - SF_VERIFY(apply_color_reset()); - SF_VERIFY(apply_style_reset()); + void all_properties_reset() { + apply_color_reset(); + apply_style_reset(); return apply_front_reset(); } - [[nodiscard]] std::expected apply_color_reset() { + void apply_color_reset() { current_context_properties_.color.modify_reset(); return text_properties_executor_.reset_color(); } - [[nodiscard]] std::expected apply_style_reset() { + void apply_style_reset() { current_context_properties_.style.modify_reset(); return text_properties_executor_.reset_style(); } - [[nodiscard]] std::expected apply_front_reset() { + void apply_front_reset() { current_context_properties_.front.modify_reset(); return text_properties_executor_.reset_front(); } @@ -60,42 +60,42 @@ namespace stream::fmt::detail { } public: - [[nodiscard]] std::expected reload_default() { - SF_VERIFY(reload_default_color()); - SF_VERIFY(reload_default_style()); + void reload_default() { + reload_default_color(); + reload_default_style(); return reload_default_front(); } - [[nodiscard]] std::expected reload_default_color() { - SF_VERIFY(reload_default_color_fg()); + void reload_default_color() { + reload_default_color_fg(); return reload_default_color_bg(); } - [[nodiscard]] std::expected reload_default_color_fg() { + void reload_default_color_fg() { return reload_color_fg(detail::TextProperties::TextColor::ColorFG{}); } - [[nodiscard]] std::expected reload_default_color_bg() { + void reload_default_color_bg() { return reload_color_bg(detail::TextProperties::TextColor::ColorBG{}); } - [[nodiscard]] std::expected reload_default_style() { + void reload_default_style() { return reload_style(detail::TextProperties::TextStyle::Style{}); } - [[nodiscard]] std::expected reload_default_front() { + void reload_default_front() { return reload_front(detail::TextProperties::TextFront::Front{}); } - [[nodiscard]] std::expected reload(const detail::TextProperties::Properties& target) { - SF_VERIFY(reload_color(target.color)); - SF_VERIFY(reload_style(target.style)); + void reload(const detail::TextProperties::Properties& target) { + reload_color(target.color); + reload_style(target.style); return reload_front(target.front); } - [[nodiscard]] std::expected reload_color(const detail::TextProperties::TextColor::Color& target) { - SF_VERIFY(reload_color_fg(target.fg)); + void reload_color(const detail::TextProperties::TextColor::Color& target) { + reload_color_fg(target.fg); return reload_color_bg(target.bg); } - [[nodiscard]] std::expected reload_color_fg(const detail::TextProperties::TextColor::ColorFG& target); - [[nodiscard]] std::expected reload_color_bg(const detail::TextProperties::TextColor::ColorBG& target); - [[nodiscard]] std::expected reload_style(const detail::TextProperties::TextStyle::Style& target); - [[nodiscard]] std::expected reload_front(const detail::TextProperties::TextFront::Front& target); + void reload_color_fg(const detail::TextProperties::TextColor::ColorFG& target); + void reload_color_bg(const detail::TextProperties::TextColor::ColorBG& target); + void reload_style(const detail::TextProperties::TextStyle::Style& target); + void reload_front(const detail::TextProperties::TextFront::Front& target); public: ITextPropertiesExecutor& get_text_properties_executor() { @@ -112,60 +112,51 @@ namespace stream::fmt::detail { public: template requires detail::text_properties_color_can_apply - [[nodiscard]] inline std::expected ask_apply_color(const T& modif) { + void ask_apply_color(const T& modif) { if (current_context_properties_.color.need_modif(modif)) return apply_color(modif); - return {}; } template requires detail::text_properties_style_can_apply - [[nodiscard]] inline std::expected ask_apply_style(const T& modif) { + void ask_apply_style(const T& modif) { if (current_context_properties_.style.need_modif(modif)) return apply_style(modif); - return {}; } template requires detail::text_properties_front_can_apply - [[nodiscard]] inline std::expected ask_apply_front(const T& modif) { + void ask_apply_front(const T& modif) { if (current_context_properties_.front.need_modif(modif)) return apply_front(modif); - return {}; } - [[nodiscard]] std::expected ask_apply_color(const detail::TextProperties::TextColor::BasicColor& modif) { + void ask_apply_color(const detail::TextProperties::TextColor::BasicColor& modif) { if (current_context_properties_.color.need_modif(modif.fg)) { if (current_context_properties_.color.need_modif(modif.bg)) return apply_color(modif); return apply_color(modif.fg); } if (current_context_properties_.color.need_modif(modif.fg)) return apply_color(modif.bg); - - return {}; } - [[nodiscard]] std::expected ask_apply_color(const detail::TextProperties::TextColor::ColorCube& modif) { + void ask_apply_color(const detail::TextProperties::TextColor::ColorCube& modif) { if (current_context_properties_.color.need_modif(modif.fg)) { if (current_context_properties_.color.need_modif(modif)) return apply_color(modif); return apply_color(modif.fg); } if (current_context_properties_.color.need_modif(modif.fg)) return apply_color(modif.bg); - - return {}; } - [[nodiscard]] std::expected ask_apply_color(const detail::TextProperties::TextColor::Color24b& modif) { + void ask_apply_color(const detail::TextProperties::TextColor::Color24b& modif) { if (current_context_properties_.color.need_modif(modif.fg)) { if (current_context_properties_.color.need_modif(modif)) return apply_color(modif); return apply_color(modif.fg); } if (current_context_properties_.color.need_modif(modif.fg)) return apply_color(modif.bg); - - return {}; } - [[nodiscard]] std::expected ask_apply_color(const detail::TextProperties::TextColor::ColorFG& modif) { + void ask_apply_color(const detail::TextProperties::TextColor::ColorFG& modif) { return reload_color_fg(modif); } - [[nodiscard]] std::expected ask_apply_color(const detail::TextProperties::TextColor::ColorBG& modif) { + void ask_apply_color(const detail::TextProperties::TextColor::ColorBG& modif) { return reload_color_bg(modif); } - [[nodiscard]] std::expected ask_apply_color(const detail::TextProperties::TextColor::Color& modif) { + void ask_apply_color(const detail::TextProperties::TextColor::Color& modif) { return reload_color(modif); } }; @@ -176,33 +167,34 @@ namespace stream::fmt::detail { TextPropertiesManager(ITextPropertiesExecutor& text_properties_executor) : TextPropertiesapplyManager(text_properties_executor) {} public: - [[nodiscard]] std::expected apply_colorOnIndex(context::BasicContext& context, std::int32_t index); - [[nodiscard]] std::expected apply_styleOnIndex(context::BasicContext& context, std::int32_t index); - [[nodiscard]] std::expected apply_frontOnIndex(context::BasicContext& context, std::int32_t index); + void apply_color_on_index(context::BasicContext& context, std::int32_t index); + void apply_style_on_index(context::BasicContext& context, std::int32_t index); + void apply_front_on_index(context::BasicContext& context, std::int32_t index); public: - [[nodiscard]] std::expected parse_color(context::BasicContext& context); - [[nodiscard]] std::expected parse_style(context::BasicContext& context); - [[nodiscard]] std::expected parse_front(context::BasicContext& context); + void parse_color(context::BasicContext& context); + void parse_style(context::BasicContext& context); + void parse_front(context::BasicContext& context); private: - template - [[nodiscard]] std::expected get_color_code(buf::StreamView& format); - [[nodiscard]] std::expected parse_style_named(buf::StreamView& format); - [[nodiscard]] std::expected select_underlined_color_style(buf::StreamView& format); + std::optional get_color_code(buf::StreamView& format, std::size_t base, std::size_t brightbase); + void parse_style_named(buf::StreamView& format); + TextProperties::TextStyle::UnderlineColor::ColorCube select_underlined_color_style(buf::StreamView& format); }; } // namespace stream::fmt::detail namespace stream::fmt::detail { template - template - [[nodiscard]] std::expected detail::TextPropertiesManager::get_color_code(buf::StreamView& format) { + std::optional detail::TextPropertiesManager::get_color_code(buf::StreamView& format, std::size_t base, std::size_t brightbase) { static constexpr std::string_view colorCode[] = {"black", "red", "green", "yellow", "blue", "magenta", "cyan", "white", " ", "default"}; - bool bright = SF_TRY(buf::TestManip(format).is_equal_to_forward('+')); - std::uint8_t step = static_cast(bright ? T::BaseBStep : T::BaseStep); - std::uint8_t code = (std::uint8_t)SF_TRY(buf::UtilsManip(format).get_word_from_list(colorCode)); - return static_cast(code + step); + bool bright = buf::TestManip(format).is_equal_to_forward('+'); + std::size_t step = bright ? brightbase : base; + std::optional color_code = buf::UtilsManip(format).get_word_from_list(colorCode); + if (color_code.has_value() == false) { + return std::nullopt; + } + return color_code.value() + step; } } // namespace stream::fmt::detail diff --git a/src/stream/fmt/context/basic_context/text_properties_manager_impl.hxx b/src/stream/fmt/context/basic_context/text_properties_manager_impl.hxx index b1f185b0..9823425a 100644 --- a/src/stream/fmt/context/basic_context/text_properties_manager_impl.hxx +++ b/src/stream/fmt/context/basic_context/text_properties_manager_impl.hxx @@ -10,141 +10,86 @@ namespace stream::fmt::detail { template - [[nodiscard]] std::expected detail::TextPropertiesManager::apply_colorOnIndex(context::BasicContext& context, std::int32_t index) { - SF_VERIFY(context.args_interface.template run_func_from_type_at( - index, [this](const detail::TextProperties::TextColor::Color& data) -> std::expected { - this->reload_color(data); - return {}; - })); - SF_VERIFY(context.args_interface.template run_func_from_type_at( - index, [this](const detail::TextProperties::TextColor::BasicColorFG& data) -> std::expected { - this->ask_apply_color(data); - return {}; - })); - SF_VERIFY(context.args_interface.template run_func_from_type_at( - index, [this](const detail::TextProperties::TextColor::BasicColorBG& data) -> std::expected { - this->ask_apply_color(data); - return {}; - })); - SF_VERIFY(context.args_interface.template run_func_from_type_at( - index, [this](const detail::TextProperties::TextColor::ColorCubeFG& data) -> std::expected { - this->ask_apply_color(data); - return {}; - })); - SF_VERIFY(context.args_interface.template run_func_from_type_at( - index, [this](const detail::TextProperties::TextColor::ColorCubeBG& data) -> std::expected { - this->ask_apply_color(data); - return {}; - })); - SF_VERIFY(context.args_interface.template run_func_from_type_at( - index, [this](const detail::TextProperties::TextColor::Color24bFG& data) -> std::expected { - this->ask_apply_color(data); - return {}; - })); - SF_VERIFY(context.args_interface.template run_func_from_type_at( - index, [this](const detail::TextProperties::TextColor::Color24bBG& data) -> std::expected { - this->ask_apply_color(data); - return {}; - })); - return {}; + void detail::TextPropertiesManager::apply_color_on_index(context::BasicContext& context, std::int32_t index) { + context.args_interface.template run_func_from_type_at( + index, [this](const detail::TextProperties::TextColor::Color& data) -> void { this->reload_color(data); }); + context.args_interface.template run_func_from_type_at( + index, [this](const detail::TextProperties::TextColor::BasicColorFG& data) -> void { this->ask_apply_color(data); }); + context.args_interface.template run_func_from_type_at( + index, [this](const detail::TextProperties::TextColor::BasicColorBG& data) -> void { this->ask_apply_color(data); }); + context.args_interface.template run_func_from_type_at( + index, [this](const detail::TextProperties::TextColor::ColorCubeFG& data) -> void { this->ask_apply_color(data); }); + context.args_interface.template run_func_from_type_at( + index, [this](const detail::TextProperties::TextColor::ColorCubeBG& data) -> void { this->ask_apply_color(data); }); + context.args_interface.template run_func_from_type_at( + index, [this](const detail::TextProperties::TextColor::Color24bFG& data) -> void { this->ask_apply_color(data); }); + context.args_interface.template run_func_from_type_at( + index, [this](const detail::TextProperties::TextColor::Color24bBG& data) -> void { this->ask_apply_color(data); }); } template - [[nodiscard]] std::expected detail::TextPropertiesManager::apply_frontOnIndex(context::BasicContext& context, std::int32_t index) { - SF_VERIFY(context.args_interface.template run_func_from_type_at( - index, [this](const detail::TextProperties::TextFront::Front& data) -> std::expected { - this->reload_front(data); - return {}; - })); - SF_VERIFY(context.args_interface.template run_func_from_type_at( - index, [this](const detail::TextProperties::TextFront::FrontID& data) -> std::expected { - this->ask_apply_front(data); - return {}; - })); - return {}; + void detail::TextPropertiesManager::apply_front_on_index(context::BasicContext& context, std::int32_t index) { + context.args_interface.template run_func_from_type_at( + index, [this](const detail::TextProperties::TextFront::Front& data) -> void { this->reload_front(data); }); + context.args_interface.template run_func_from_type_at( + index, [this](const detail::TextProperties::TextFront::FrontID& data) -> void { this->ask_apply_front(data); }); } template - [[nodiscard]] std::expected detail::TextPropertiesManager::apply_styleOnIndex(context::BasicContext& context, std::int32_t index) { - SF_VERIFY(context.args_interface.template run_func_from_type_at( - index, [this](const detail::TextProperties::TextStyle::Style& data) -> std::expected { - return this->reload_style(data); - return {}; - })); - SF_VERIFY(context.args_interface.template run_func_from_type_at( - index, [this](const detail::TextProperties::TextStyle::Intensity& data) -> std::expected { - return this->ask_apply_style(data); - return {}; - })); - SF_VERIFY(context.args_interface.template run_func_from_type_at( - index, [this](const detail::TextProperties::TextStyle::Italic& data) -> std::expected { - return this->ask_apply_style(data); - return {}; - })); - SF_VERIFY(context.args_interface.template run_func_from_type_at( - index, [this](const detail::TextProperties::TextStyle::Underline& data) -> std::expected { - return this->ask_apply_style(data); - return {}; - })); - SF_VERIFY(context.args_interface.template run_func_from_type_at( - index, [this](const detail::TextProperties::TextStyle::Blink& data) -> std::expected { - return this->ask_apply_style(data); - return {}; - })); - SF_VERIFY(context.args_interface.template run_func_from_type_at( - index, [this](const detail::TextProperties::TextStyle::Inverted& data) -> std::expected { - return this->ask_apply_style(data); - return {}; - })); - SF_VERIFY(context.args_interface.template run_func_from_type_at( - index, [this](const detail::TextProperties::TextStyle::Ideogram& data) -> std::expected { - return this->ask_apply_style(data); - return {}; - })); - SF_VERIFY(context.args_interface.template run_func_from_type_at( - index, [this](const detail::TextProperties::TextStyle::Script& data) -> std::expected { - return this->ask_apply_style(data); - return {}; - })); - - SF_VERIFY(context.args_interface.template run_func_from_type_at( - index, [this](const detail::TextProperties::TextStyle::UnderlineColor::ColorCube& data) -> std::expected { - this->ask_apply_style(data); - return {}; - })); - SF_VERIFY(context.args_interface.template run_func_from_type_at( - index, [this](const detail::TextProperties::TextStyle::UnderlineColor::Color24b& data) -> std::expected { - this->ask_apply_style(data); - return {}; - })); - return {}; + void detail::TextPropertiesManager::apply_style_on_index(context::BasicContext& context, std::int32_t index) { + context.args_interface.template run_func_from_type_at( + index, [this](const detail::TextProperties::TextStyle::Style& data) -> void { return this->reload_style(data); }); + context.args_interface.template run_func_from_type_at( + index, [this](const detail::TextProperties::TextStyle::Intensity& data) -> void { return this->ask_apply_style(data); }); + context.args_interface.template run_func_from_type_at( + index, [this](const detail::TextProperties::TextStyle::Italic& data) -> void { return this->ask_apply_style(data); }); + context.args_interface.template run_func_from_type_at( + index, [this](const detail::TextProperties::TextStyle::Underline& data) -> void { return this->ask_apply_style(data); }); + context.args_interface.template run_func_from_type_at( + index, [this](const detail::TextProperties::TextStyle::Blink& data) -> void { return this->ask_apply_style(data); }); + context.args_interface.template run_func_from_type_at( + index, [this](const detail::TextProperties::TextStyle::Inverted& data) -> void { return this->ask_apply_style(data); }); + context.args_interface.template run_func_from_type_at( + index, [this](const detail::TextProperties::TextStyle::Ideogram& data) -> void { return this->ask_apply_style(data); }); + context.args_interface.template run_func_from_type_at( + index, [this](const detail::TextProperties::TextStyle::Script& data) -> void { return this->ask_apply_style(data); }); + + context.args_interface.template run_func_from_type_at( + index, [this](const detail::TextProperties::TextStyle::UnderlineColor::ColorCube& data) -> void { this->ask_apply_style(data); }); + context.args_interface.template run_func_from_type_at( + index, [this](const detail::TextProperties::TextStyle::UnderlineColor::Color24b& data) -> void { this->ask_apply_style(data); }); } template - [[nodiscard]] std::expected detail::TextPropertiesManager::parse_color(context::BasicContext& context) { + void detail::TextPropertiesManager::parse_color(context::BasicContext& context) { if (buf::TestAccess(context.fmtstream).is_equal_to(':')) { - SF_VERIFY(buf::Manip(context.fmtstream).forward()); + buf::Manip(context.fmtstream).forward(); buf::TestManip(context.fmtstream).ignore_every_spaces(); if (buf::TestAccess(context.fmtstream).is_equal_to('{')) { - SF_VERIFY(buf::Manip(context.fmtstream).forward()); - std::int32_t idx = SF_TRY(context.get_format_index()); - SF_VERIFY(apply_colorOnIndex(context, idx)); - SF_VERIFY(buf::TestManip(context.fmtstream).skip_one_of('}')); + buf::Manip(context.fmtstream).forward(); + std::optional idx = context.get_format_index(); + if (idx.has_value() == false) { + } + apply_color_on_index(context, idx.value()); + buf::TestManip(context.fmtstream).skip_one_of('}'); } else { - auto color_fg = get_color_code(context.fmtstream); + std::optional color_fg = get_color_code(context.fmtstream, static_cast(TextProperties::TextColor::BasicColorFG::BaseStep), + static_cast(TextProperties::TextColor::BasicColorFG::BaseBrightStep)); buf::FMTParamsManip(context.fmtstream).param_go_to('-', ','); if (buf::TestAccess(context.fmtstream).is_equal_to('-')) { - SF_VERIFY(buf::Manip(context.fmtstream).forward()); + buf::Manip(context.fmtstream).forward(); buf::TestManip(context.fmtstream).ignore_every_spaces(); - auto color_bg = get_color_code(context.fmtstream); + std::optional color_bg = get_color_code(context.fmtstream, static_cast(TextProperties::TextColor::BasicColorBG::BaseStep), + static_cast(TextProperties::TextColor::BasicColorBG::BaseBrightStep)); if (color_bg.has_value() && color_fg.has_value()) { - return ask_apply_color(detail::TextProperties::TextColor::BasicColor{color_fg.value(), color_bg.value()}); + return ask_apply_color(detail::TextProperties::TextColor::BasicColor{static_cast(color_fg.value()), + static_cast(color_bg.value())}); } else { return reload_default_color(); } } else { if (color_fg.has_value()) { - return ask_apply_color(color_fg.value()); + return ask_apply_color(static_cast(color_fg.value())); } else { return reload_default_color(); } @@ -153,28 +98,27 @@ namespace stream::fmt::detail { } else { return reload_default_color(); } - return {}; } template - [[nodiscard]] std::expected detail::TextPropertiesManager::parse_style(context::BasicContext& context) { + void detail::TextPropertiesManager::parse_style(context::BasicContext& context) { if (buf::TestAccess(context.fmtstream).is_equal_to(':')) { - SF_VERIFY(buf::Manip(context.fmtstream).forward()); + buf::Manip(context.fmtstream).forward(); if (!buf::TestAccess(context.fmtstream).is_equal_to('}', ',')) { bool loop = true; while (loop) { buf::TestManip(context.fmtstream).ignore_every_spaces(); if (buf::TestAccess(context.fmtstream).is_equal_to('{')) { - SF_VERIFY(buf::Manip(context.fmtstream).forward()); - std::int32_t idx = SF_TRY(context.get_format_index()); - apply_styleOnIndex(context, idx); + buf::Manip(context.fmtstream).forward(); + std::optional idx = context.get_format_index(); + apply_style_on_index(context, idx.value()); buf::TestManip(context.fmtstream).skip_one_of('}'); } else { parse_style_named(context.fmtstream); } buf::FMTParamsManip(context.fmtstream).param_go_to('|', ','); loop = buf::TestAccess(context.fmtstream).is_equal_to('|'); - SF_VERIFY(buf::Manip(context.fmtstream).forward()); + buf::Manip(context.fmtstream).forward(); buf::TestManip(context.fmtstream).ignore_every_spaces(); } } else { @@ -183,11 +127,10 @@ namespace stream::fmt::detail { } else { return reload_default_style(); } - return {}; } template - [[nodiscard]] std::expected detail::TextPropertiesManager::parse_style_named(buf::StreamView& format) { + void detail::TextPropertiesManager::parse_style_named(buf::StreamView& format) { buf::UtilsManip utils(format); static constexpr std::pair, detail::TextProperties::TextStyle::Intensity> styleIntensity[] = { @@ -235,52 +178,51 @@ namespace stream::fmt::detail { { "n-script", detail::TextProperties::TextStyle::Script::AllDisable} }; - std::uint8_t code = (std::uint8_t)SF_TRY(buf::UtilsManip(format).get_word_from_dict_pairs(styleIntensity)); + std::uint8_t code = (std::uint8_t)buf::UtilsManip(format).get_word_from_dict_pairs(styleIntensity); if (code != 255) return apply_style(detail::TextProperties::TextStyle::Intensity{code}); - code = (std::uint8_t)SF_TRY(buf::UtilsManip(format).get_word_from_dict_pairs(styleItalic)); + code = (std::uint8_t)buf::UtilsManip(format).get_word_from_dict_pairs(styleItalic); if (code != 255) return apply_style(detail::TextProperties::TextStyle::Italic{code}); - code = (std::uint8_t)SF_TRY(buf::UtilsManip(format).get_word_from_dict_pairs(styleBlink)); + code = (std::uint8_t)buf::UtilsManip(format).get_word_from_dict_pairs(styleBlink); if (code != 255) return apply_style(detail::TextProperties::TextStyle::Blink{code}); - code = (std::uint8_t)SF_TRY(buf::UtilsManip(format).get_word_from_dict_pairs(styleInverted)); + code = (std::uint8_t)buf::UtilsManip(format).get_word_from_dict_pairs(styleInverted); if (code != 255) return apply_style(detail::TextProperties::TextStyle::Inverted{code}); - code = (std::uint8_t)SF_TRY(buf::UtilsManip(format).get_word_from_dict_pairs(styleIdeogram)); + code = (std::uint8_t)buf::UtilsManip(format).get_word_from_dict_pairs(styleIdeogram); if (code != 255) return apply_style(detail::TextProperties::TextStyle::Ideogram{code}); - code = (std::uint8_t)SF_TRY(buf::UtilsManip(format).get_word_from_dict_pairs(styleScript)); + code = (std::uint8_t)buf::UtilsManip(format).get_word_from_dict_pairs(styleScript); if (code != 255) return apply_style(detail::TextProperties::TextStyle::Script{code}); - code = (std::uint8_t)SF_TRY(buf::UtilsManip(format).get_word_from_dict_pairs(styleUnderline)); + code = (std::uint8_t)buf::UtilsManip(format).get_word_from_dict_pairs(styleUnderline); if (code != 255) { if (code == (std::uint8_t)detail::TextProperties::TextStyle::Underline::SelectUnderlinedColor) { - auto underlineColor = select_underlined_color_style(format); - if (underlineColor.has_value()) return std::unexpected(underlineColor.error()); - return apply_style(detail::TextProperties::TextStyle::UnderlineColor::ColorCube{underlineColor.value()}); + detail::TextProperties::TextStyle::UnderlineColor::ColorCube underlineColor = select_underlined_color_style(format); + return apply_style(underlineColor); } return apply_style(detail::TextProperties::TextStyle::Underline{code}); } - return {}; } template - [[nodiscard]] std::expected TextPropertiesManager::select_underlined_color_style( - buf::StreamView& format) { + TextProperties::TextStyle::UnderlineColor::ColorCube TextPropertiesManager::select_underlined_color_style(buf::StreamView& format) { // TODO // FIXME - return std::unexpected(FMTResult::FunctionNotImpl); + throw std::runtime_error("fmt error: FunctionNotImpl"); } template - [[nodiscard]] std::expected detail::TextPropertiesManager::parse_front(context::BasicContext& context) { + void detail::TextPropertiesManager::parse_front(context::BasicContext& context) { static constexpr std::string_view frontCode[] = {"default", "front0", "front1", "front2", "front3", "front4", "front5", "front6", "front7", "front8", "front9"}; if (buf::TestAccess(context.fmtstream).is_equal_to(':')) { - SF_VERIFY(buf::Manip(context.fmtstream).forward()); + buf::Manip(context.fmtstream).forward(); buf::TestManip(context.fmtstream).ignore_every_spaces(); - auto front_id = buf::UtilsManip(context.fmtstream).get_word_from_list(frontCode); - if (front_id.has_value()) return std::unexpected(front_id.error()); - return apply_front(detail::TextProperties::TextFront::FrontID{front_id.value()}); - } else - return reload_default_front(); - return {}; + std::optional front_id = buf::UtilsManip(context.fmtstream).get_word_from_list(frontCode); + + if (front_id.has_value()) { + apply_front(static_cast(front_id.value())); + return; + } + } + reload_default_front(); } } // namespace stream::fmt::detail diff --git a/src/stream/fmt/context/formatter_executor/basic_formatter_executor.hxx b/src/stream/fmt/context/formatter_executor/basic_formatter_executor.hxx index fd5e8721..79d7c09d 100644 --- a/src/stream/fmt/context/formatter_executor/basic_formatter_executor.hxx +++ b/src/stream/fmt/context/formatter_executor/basic_formatter_executor.hxx @@ -30,36 +30,34 @@ namespace stream::fmt::context { BasicFormatterExecutor(buf::FMTStreamIO& ostream, detail::ITextPropertiesExecutor& text_properties_executor); ~BasicFormatterExecutor() override = default; - [[nodiscard]] std::expected terminate(); + void terminate(); public: buf::FMTStreamIO& ostream; - EndOfStringCharMode EndOfStringChar = EndOfStringCharMode::Optional; + EndOfStringCharMode end_of_string_char = EndOfStringCharMode::Optional; using context_executor::data; using context_executor::text_manager; protected: - [[nodiscard]] std::expected exec_raw_string(std::basic_string_view sv) override { + void exec_raw_string(std::basic_string_view sv) override { return buf::WriteManip(ostream).fast_write_string(sv); } - [[nodiscard]] std::expected exec_settings() override; + void exec_settings() override; public: template - [[nodiscard]] std::expected run_(buf::StreamView format, Args&&... args); + void run_(buf::StreamView format, Args&&... args); template - [[nodiscard]] std::expected run(Format&& format, Args&&... args); + void run(Format&& format, Args&&... args); public: template - [[nodiscard]] inline std::expected write_type(Type&& type, Rest&&... rest) { - auto&& formatErr = FormatterType>::type, M_Type>::format(std::forward(type), *this); - SF_VERIFY(formatErr); + void write_type(Type&& type, Rest&&... rest) { + FormatterType>::type, M_Type>::format(std::forward(type), *this); if constexpr (sizeof...(rest) > 0) { - SF_VERIFY(write_type(std::forward(rest)...)); + write_type(std::forward(rest)...); } - return {}; } }; } // namespace stream::fmt::context @@ -72,40 +70,40 @@ namespace stream::fmt::context { } template - [[nodiscard]] std::expected BasicFormatterExecutor::terminate() { + void BasicFormatterExecutor::terminate() { buf::ManipIO(ostream).compute_generated_size(); // End char not included in buffer manager context to deduce size correctly - auto res = buf::ManipIO(ostream).pushback('\0'); - if (EndOfStringChar == EndOfStringCharMode::Forced) { - SF_VERIFY(res); + if (end_of_string_char == EndOfStringCharMode::Forced) { + buf::ManipIO(ostream).pushback('\0'); + } else { + if (ostream.get_buffer_remaining_size() > 1) { + buf::ManipIO(ostream).pushback('\0'); + } } - - return {}; } template - [[nodiscard]] std::expected BasicFormatterExecutor::exec_settings() { + void BasicFormatterExecutor::exec_settings() { // indent auto indent = data.specifiers.get("indent"); if (indent != nullptr) ostream.indent = indent->as_number; - return {}; } template template - [[nodiscard]] std::expected BasicFormatterExecutor::run_(buf::StreamView format, Args&&... args) { + void BasicFormatterExecutor::run_(buf::StreamView format, Args&&... args) { auto args_interface = detail::FormatterArgsInterface, Args...>(*this, std::forward(args)...); detail::TextProperties::Properties saveTextProperties = text_manager.save(); context::BasicContext context(*this, format, args_interface); - SF_VERIFY(context.run()); + context.run(); return text_manager.reload(saveTextProperties); } template template - [[nodiscard]] std::expected BasicFormatterExecutor::run(Format&& format_input, Args&&... args) { + void BasicFormatterExecutor::run(Format&& format_input, Args&&... args) { return run_(buf::StreamView{format_input}, std::forward(args)...); } } // namespace stream::fmt::context diff --git a/src/stream/fmt/context/formatter_executor/format_basics_impl.hxx b/src/stream/fmt/context/formatter_executor/format_basics_impl.hxx index 11265c0c..dbf960df 100644 --- a/src/stream/fmt/context/formatter_executor/format_basics_impl.hxx +++ b/src/stream/fmt/context/formatter_executor/format_basics_impl.hxx @@ -11,87 +11,80 @@ namespace stream::fmt { template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static std::expected format(const typename FormatterExecutor::detail::template FormatSpecifier& specifier, - FormatterExecutor& executor) { + static void format(const typename FormatterExecutor::detail::template FormatSpecifier& specifier, FormatterExecutor& executor) { if (specifier.ValueIsText) { - SF_VERIFY(executor.run("{ '{}', '{}' }", specifier.name, specifier.as_text)); + executor.run("{ '{}', '{}' }", specifier.name, specifier.as_text); } else { - SF_VERIFY(executor.run("{ '{}', '{}' }", specifier.name, specifier.as_number)); + executor.run("{ '{}', '{}' }", specifier.name, specifier.as_number); } - return {}; + return; } }; //----------------------------------------------// - //----------------- Forwarders -----------------// + //----------------- forwarders -----------------// //----------------------------------------------// - namespace detail::Forwarders { + namespace detail::forwarders { template - [[nodiscard]] std::expected FormatObjectArray(const T* const buffer, std::size_t totalsize, FormatterExecutor& executor) { - std::size_t beginIdx = (std::size_t)executor.data.specifiers.get_as_number("begin", 0); - totalsize = executor.data.specifiers.get_as_number("totalsize", totalsize); - totalsize = executor.data.specifiers.get_as_number("end", totalsize); + void format_object_array(const T* const buffer, std::size_t totalsize, FormatterExecutor& executor) { + std::size_t begin_idx = (std::size_t)executor.data.specifiers.get_as_number("begin", 0); + totalsize = executor.data.specifiers.get_as_number("totalsize", totalsize); + totalsize = executor.data.specifiers.get_as_number("end", totalsize); - std::size_t size = executor.data.specifiers.get_as_number("size", totalsize - beginIdx); + std::size_t size = executor.data.specifiers.get_as_number("size", totalsize - begin_idx); - if (size == std::numeric_limits::max()) { - return std::unexpected(FMTResult::GivenArgs_UnableToDeduceSize); - } - - SF_VERIFY(buf::WriteManip(executor.ostream).fast_write_string(executor.data.specifiers.get_as_text("begin", STDEnumerableUtility::DefaultBegin))); + buf::WriteManip(executor.ostream).fast_write_string(executor.data.specifiers.get_as_text("begin", STDEnumerableUtility::DefaultBegin)); std::basic_string_view join = executor.data.specifiers.get_as_text("join", STDEnumerableUtility::DefaultJoin); bool first = true; - const T* itbegin = buffer + beginIdx; - const T* itend = buffer + size + beginIdx; + const T* itbegin = buffer + begin_idx; + const T* itend = buffer + size + begin_idx; while (itbegin < itend) { if (first) { first = false; } else { - SF_VERIFY(buf::FMTWriteManip(executor.ostream).write_indent_string(join)); + buf::FMTWriteManip(executor.ostream).write_indent_string(join); } - SF_VERIFY(executor.write_type(*itbegin++)); + executor.write_type(*itbegin++); } return buf::WriteManip(executor.ostream).fast_write_string(executor.data.specifiers.get_as_text("end", STDEnumerableUtility::DefaultEnd)); } template - [[nodiscard]] std::expected format_string(const T* buffer, std::size_t size, FormatterExecutor& executor) { - std::size_t beginIdx = (std::size_t)executor.data.specifiers.get_as_number("begin", 0); - size = executor.data.specifiers.get_as_number("size", size); + void format_string(const T* buffer, std::size_t size, FormatterExecutor& executor) { + std::size_t begin_idx = (std::size_t)executor.data.specifiers.get_as_number("begin", 0); + size = executor.data.specifiers.get_as_number("size", size); if (size == std::numeric_limits::max()) { size = std::basic_string_view(buffer).size(); } - if (executor.data.specifiers.has("array")) return FormatObjectArray(buffer, size, executor); + if (executor.data.specifiers.has("array")) return format_object_array(buffer, size, executor); - if (beginIdx > size) return {}; - const T* begin = buffer + beginIdx; + if (begin_idx > size) return; + const T* begin = buffer + begin_idx; // TODO: current indent ignore shift if (executor.data.specifiers.has("indent")) return buf::FMTWriteManip(executor.ostream).write_indent_char_ptr(begin, size); if (executor.data.prefix_suffix) { - SF_VERIFY(buf::ManipIO(executor.ostream).pushback('\"')); + buf::ManipIO(executor.ostream).pushback('\"'); } if (executor.data.has_spec == false) { - SF_VERIFY(buf::WriteManip(executor.ostream).fast_write_char_array(begin, size)); + buf::WriteManip(executor.ostream).fast_write_char_array(begin, size); } else { - SF_VERIFY(buf::FMTWriteManip(executor.ostream).write_char_ptr(begin, size, executor.data.shift)); + buf::FMTWriteManip(executor.ostream).write_char_ptr(begin, size, executor.data.shift); } if (executor.data.prefix_suffix) { - SF_VERIFY(buf::ManipIO(executor.ostream).pushback('\"')); + buf::ManipIO(executor.ostream).pushback('\"'); } - - return {}; } - } // namespace detail::Forwarders + } // namespace detail::forwarders //-----------------------------------------------// //----------------- C/CXX Types -----------------// @@ -100,7 +93,7 @@ namespace stream::fmt { // Bool template struct FormatterType { - [[nodiscard]] static std::expected format(const bool t, FormatterExecutor& executor) { + static void format(const bool t, FormatterExecutor& executor) { if (executor.data.prefix_suffix) { if (t == true) return buf::WriteManip(executor.ostream).fast_write_string_literal("True"); @@ -113,14 +106,14 @@ namespace stream::fmt { return buf::ManipIO(executor.ostream).pushback('0'); } - return {}; + return; } }; template requires(std::is_integral_v && !std::is_floating_point_v && !detail::IsCharType::value) struct FormatterType { - [[nodiscard]] static inline std::expected format(const T t, FormatterExecutor& executor) { + static inline void format(const T t, FormatterExecutor& executor) { return buf::FMTWriteManip(executor.ostream).write_integer_format_data(t, executor.data); } }; @@ -128,7 +121,7 @@ namespace stream::fmt { template requires std::is_floating_point_v struct FormatterType { - [[nodiscard]] static inline std::expected format(const T t, FormatterExecutor& executor) { + static inline void format(const T t, FormatterExecutor& executor) { return buf::FMTWriteManip(executor.ostream).write_float_formatdata(t, executor.data); } }; @@ -136,7 +129,7 @@ namespace stream::fmt { template requires detail::IsCharType::value struct FormatterType { - [[nodiscard]] static inline std::expected format(const T t, FormatterExecutor& executor) { + static inline void format(const T t, FormatterExecutor& executor) { return buf::ManipIO(executor.ostream).pushback(t); } }; @@ -147,7 +140,7 @@ namespace stream::fmt { template struct FormatterType { - [[nodiscard]] static inline std::expected format(const void* const t, FormatterExecutor& executor) { + static inline void format(const void* const t, FormatterExecutor& executor) { if (t == nullptr) return buf::ManipIO(executor.ostream).fast_write_string(executor.data.get_as_text("null", "nullptr")); return buf::WriteManip(executor.ostream).fast_write_integer(std::size_t(t)); } @@ -155,34 +148,30 @@ namespace stream::fmt { template struct FormatterType { - [[nodiscard]] static inline std::expected format(const T* const t, FormatterExecutor& executor) { + static inline void format(const T* const t, FormatterExecutor& executor) { if (t == nullptr) { return buf::WriteManip(executor.ostream).fast_write_string(executor.data.specifiers.get_as_text("null", "nullptr")); } if constexpr (detail::IsCharType::value) { - return detail::Forwarders::format_string(t, std::numeric_limits::max(), executor); + return detail::forwarders::format_string(t, std::numeric_limits::max(), executor); } else { - detail::Forwarders::FormatObjectArray(t, std::numeric_limits::max(), executor); + detail::forwarders::format_object_array(t, std::numeric_limits::max(), executor); } - - return {}; } }; template struct FormatterType { - [[nodiscard]] static inline std::expected format(T const (&t)[SIZE], FormatterExecutor& executor) { + static inline void format(T const (&t)[SIZE], FormatterExecutor& executor) { if constexpr (detail::IsCharType::value) { std::size_t size = SIZE; while (t[size - 1] == '\0') --size; - return detail::Forwarders::format_string(t, size, executor); + return detail::forwarders::format_string(t, size, executor); } else { - return detail::Forwarders::FormatObjectArray(t, SIZE, executor); + return detail::forwarders::format_object_array(t, SIZE, executor); } - - return {}; } }; } // namespace stream::fmt diff --git a/src/stream/fmt/context/formatter_executor/format_text_properties_impl.hxx b/src/stream/fmt/context/formatter_executor/format_text_properties_impl.hxx index 630abc90..d1c7c664 100644 --- a/src/stream/fmt/context/formatter_executor/format_text_properties_impl.hxx +++ b/src/stream/fmt/context/formatter_executor/format_text_properties_impl.hxx @@ -9,28 +9,28 @@ namespace stream::fmt { template struct FormatterType { - [[nodiscard]] static std::expected format(const detail::TextProperties::ResetProperties, FormatterExecutor& executor) { + static void format(const detail::TextProperties::ResetProperties, FormatterExecutor& executor) { return executor.text_manager.all_properties_reset(); } }; template struct FormatterType { - [[nodiscard]] static std::expected format(const detail::TextProperties::TextColor::reset_color, FormatterExecutor& executor) { + static void format(const detail::TextProperties::TextColor::reset_color, FormatterExecutor& executor) { return executor.text_manager.apply_color_reset(); } }; template struct FormatterType { - [[nodiscard]] static std::expected format(const detail::TextProperties::TextStyle::reset_style, FormatterExecutor& executor) { + static void format(const detail::TextProperties::TextStyle::reset_style, FormatterExecutor& executor) { return executor.text_manager.apply_style_reset(); } }; template struct FormatterType { - [[nodiscard]] static std::expected format(const detail::TextProperties::TextFront::ResetFront, FormatterExecutor& executor) { + static void format(const detail::TextProperties::TextFront::ResetFront, FormatterExecutor& executor) { return executor.text_manager.apply_front_reset(); } }; @@ -42,7 +42,7 @@ namespace stream::fmt { template requires detail::text_properties_color_is_apply struct FormatterType { - [[nodiscard]] static std::expected format(const T& t, FormatterExecutor& executor) { + static void format(const T& t, FormatterExecutor& executor) { return executor.text_manager.ask_apply_color(t); } }; @@ -50,7 +50,7 @@ namespace stream::fmt { template requires detail::TextPropertiesStyleIsapply struct FormatterType { - [[nodiscard]] static std::expected format(const T& t, FormatterExecutor& executor) { + static void format(const T& t, FormatterExecutor& executor) { return executor.text_manager.ask_apply_style(t); } }; @@ -58,7 +58,7 @@ namespace stream::fmt { template requires detail::TextPropertiesFrontIsapply struct FormatterType { - [[nodiscard]] static std::expected format(const T& t, FormatterExecutor& executor) { + static void format(const T& t, FormatterExecutor& executor) { return executor.text_manager.ask_apply_front(t); } }; diff --git a/src/stream/fmt/context/formatter_executor/formatter_args.hxx b/src/stream/fmt/context/formatter_executor/formatter_args.hxx index 6825afe9..1d4a531c 100644 --- a/src/stream/fmt/context/formatter_executor/formatter_args.hxx +++ b/src/stream/fmt/context/formatter_executor/formatter_args.hxx @@ -22,19 +22,19 @@ namespace stream::fmt::detail { public: template - [[nodiscard]] inline std::expected run_type_at(FormatterExecutor&, std::int32_t) { - return std::unexpected(FMTResult::ArgsInterface_IndexOutOfBounds); + void run_type_at(FormatterExecutor&, std::int32_t) { + throw std::runtime_error("fmt error: ArgsInterface_IndexOutOfBounds"); } template - [[nodiscard]] inline std::expected get_index_of_current_named_arg(buf::StreamView&, std::int32_t) { - return std::unexpected(FMTResult::ArgsInterface_CantMatchNamedArgs); + inline std::optional get_index_of_current_named_arg(buf::StreamView& stream, std::int32_t) { + return std::nullopt; } - [[nodiscard]] inline std::expected get_pointerid_at(std::int32_t) { - return std::unexpected(FMTResult::ArgsInterface_IndexOutOfBounds); + inline PointerID get_pointerid_at(std::int32_t) { + throw std::runtime_error("fmt error: ArgsInterface_IndexOutOfBounds"); } template - [[nodiscard]] inline std::expected get_converted_type_at(std::int32_t) { - return std::unexpected(FMTResult::ArgsInterface_IndexOutOfBounds); + inline T get_converted_type_at(std::int32_t) { + throw std::runtime_error("fmt error: ArgsInterface_IndexOutOfBounds"); } }; @@ -44,10 +44,10 @@ namespace stream::fmt::detail { using TypeWithoutRef = std::remove_reference_t; public: - FormatterArgs(const TypeWithoutRef& t, Rest&&... rest) : FormatterArgs(std::forward(rest)...), m_Value(t) {} + FormatterArgs(const TypeWithoutRef& t, Rest&&... rest) : FormatterArgs(std::forward(rest)...), value_(t) {} private: - const TypeWithoutRef& m_Value; + const TypeWithoutRef& value_; public: static inline constexpr std::size_t size() { @@ -56,37 +56,37 @@ namespace stream::fmt::detail { public: template - [[nodiscard]] inline std::expected run_type_at(Executor& executor, std::int32_t idx) { + void run_type_at(Executor& executor, std::int32_t idx) { if (idx == 0) { - return executor.write_type(m_Value); + return executor.write_type(value_); } return FormatterArgs::run_type_at(executor, idx - 1); } public: template - [[nodiscard]] inline std::expected get_index_of_current_named_arg(buf::StreamView& format, std::int32_t begin_search_index) { + inline std::optional get_index_of_current_named_arg(buf::StreamView& format, std::int32_t begin_search_index) { if constexpr (detail::IsANamedArgs>::value) { - bool current_is_a_named_arg = SF_TRY(buf::FMTParamsManip(format).next_is_named_args(m_Value.get_name())); + bool current_is_a_named_arg = buf::FMTParamsManip(format).next_is_named_args(value_.get_name()); if (current_is_a_named_arg) return begin_search_index; } return FormatterArgs::get_index_of_current_named_arg(format, begin_search_index + 1); } public: - [[nodiscard]] inline std::expected get_pointerid_at(std::int32_t idx) { - if (idx == 0) return PointerID{.type_info = typeid(const TypeWithoutRef), .ptr = const_cast(static_cast(&m_Value))}; + inline PointerID get_pointerid_at(std::int32_t idx) { + if (idx == 0) return PointerID{.type_info = typeid(const TypeWithoutRef), .ptr = const_cast(static_cast(&value_))}; return FormatterArgs::get_pointerid_at(idx - 1); } public: template - [[nodiscard]] inline std::expected get_converted_type_at(std::int32_t idx) { + inline T get_converted_type_at(std::int32_t idx) { if (idx == 0) { if constexpr (FMTCanContextConvert) { - return FMTContextConvert::convert(m_Value); + return FMTContextConvert::convert(value_); } else { - return std::unexpected(FMTResult::ArgsInterface_InvalidConversion); + throw std::runtime_error("fmt error: ArgsInterface_InvalidConversion"); } } return FormatterArgs::template get_converted_type_at(idx - 1); @@ -111,21 +111,21 @@ namespace stream::fmt::detail { return args_interface.size(); } - [[nodiscard]] std::expected run_type_at(std::int32_t idx) override { + void run_type_at(std::int32_t idx) override { return args_interface.run_type_at(executor, idx); } - [[nodiscard]] std::expected get_index_of_current_named_arg(buf::StreamView& format) override { + std::optional get_index_of_current_named_arg(buf::StreamView& format) override { return args_interface.get_index_of_current_named_arg(format, std::int32_t{0}); } - [[nodiscard]] std::expected get_pointerid_at(std::int32_t idx) override { + PointerID get_pointerid_at(std::int32_t idx) override { return args_interface.get_pointerid_at(idx); } public: - [[nodiscard]] std::expected, FMTResult> get_string_at(std::int32_t idx) override { + std::basic_string_view get_string_at(std::int32_t idx) override { return args_interface.template get_converted_type_at>(idx); } - [[nodiscard]] std::expected get_int_at(std::int32_t idx) override { + std::int64_t get_int_at(std::int32_t idx) override { return args_interface.template get_converted_type_at(idx); } diff --git a/src/stream/fmt/context/formatter_executor/formatter_text_properties_executor/formatter_text_properties_executor.hxx b/src/stream/fmt/context/formatter_executor/formatter_text_properties_executor/formatter_text_properties_executor.hxx index cf31eb35..0393af62 100644 --- a/src/stream/fmt/context/formatter_executor/formatter_text_properties_executor/formatter_text_properties_executor.hxx +++ b/src/stream/fmt/context/formatter_executor/formatter_text_properties_executor/formatter_text_properties_executor.hxx @@ -27,35 +27,35 @@ namespace stream::fmt::detail { ~FormatterNOTextPropertiesExecutor() override = default; public: - [[nodiscard]] std::expected all_properties_reset() override {} + void all_properties_reset() override {} public: - [[nodiscard]] std::expected reset_color() override {} - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::BasicColorFG&) override {} - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::BasicColorBG&) override {} - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::BasicColor&) override {} - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::Color24bFG&) override {} - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::Color24bBG&) override {} - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::Color24b&) override {} - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::ColorCubeFG&) override {} - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::ColorCubeBG&) override {} - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::ColorCube&) override {} + void reset_color() override {} + void execute_color(const detail::TextProperties::TextColor::BasicColorFG&) override {} + void execute_color(const detail::TextProperties::TextColor::BasicColorBG&) override {} + void execute_color(const detail::TextProperties::TextColor::BasicColor&) override {} + void execute_color(const detail::TextProperties::TextColor::Color24bFG&) override {} + void execute_color(const detail::TextProperties::TextColor::Color24bBG&) override {} + void execute_color(const detail::TextProperties::TextColor::Color24b&) override {} + void execute_color(const detail::TextProperties::TextColor::ColorCubeFG&) override {} + void execute_color(const detail::TextProperties::TextColor::ColorCubeBG&) override {} + void execute_color(const detail::TextProperties::TextColor::ColorCube&) override {} public: - [[nodiscard]] std::expected reset_front() override {} - [[nodiscard]] std::expected execute_front(const detail::TextProperties::TextFront::FrontID&) override {} + void reset_front() override {} + void execute_front(const detail::TextProperties::TextFront::FrontID&) override {} public: - [[nodiscard]] std::expected reset_style() override {} - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Intensity&) override {} - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Italic&) override {} - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Underline&) override {} - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::UnderlineColor::Color&) override {} - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::UnderlineColor::ColorCube&) override {} - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::UnderlineColor::Color24b&) override {} - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Blink&) override {} - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Inverted&) override {} - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Ideogram&) override {} - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Script&) override {} + void reset_style() override {} + void execute_style(const detail::TextProperties::TextStyle::Intensity&) override {} + void execute_style(const detail::TextProperties::TextStyle::Italic&) override {} + void execute_style(const detail::TextProperties::TextStyle::Underline&) override {} + void execute_style(const detail::TextProperties::TextStyle::UnderlineColor::Color&) override {} + void execute_style(const detail::TextProperties::TextStyle::UnderlineColor::ColorCube&) override {} + void execute_style(const detail::TextProperties::TextStyle::UnderlineColor::Color24b&) override {} + void execute_style(const detail::TextProperties::TextStyle::Blink&) override {} + void execute_style(const detail::TextProperties::TextStyle::Inverted&) override {} + void execute_style(const detail::TextProperties::TextStyle::Ideogram&) override {} + void execute_style(const detail::TextProperties::TextStyle::Script&) override {} }; } // namespace stream::fmt::detail diff --git a/src/stream/fmt/context/formatter_executor/formatter_text_properties_executor/formatter_text_properties_executor_ansi.hxx b/src/stream/fmt/context/formatter_executor/formatter_text_properties_executor/formatter_text_properties_executor_ansi.hxx index 286e8f16..428a2809 100644 --- a/src/stream/fmt/context/formatter_executor/formatter_text_properties_executor/formatter_text_properties_executor_ansi.hxx +++ b/src/stream/fmt/context/formatter_executor/formatter_text_properties_executor/formatter_text_properties_executor_ansi.hxx @@ -13,107 +13,107 @@ namespace stream::fmt::detail { using IFormatterTextPropertiesExecutor::buffer; public: - [[nodiscard]] std::expected all_properties_reset() override { + void all_properties_reset() override { NoStrideFunction no_stride(*buffer); return buf::WriteManip(*buffer).fast_write_string_literal("\033[0m"); } public: - [[nodiscard]] std::expected reset_color() override { + void reset_color() override { NoStrideFunction no_stride(*buffer); return buf::WriteManip(*buffer).fast_write_string_literal("\033[39;49m"); } - [[nodiscard]] std::expected execute_color(const TextProperties::TextColor::BasicColorFG& t) { + void execute_color(const TextProperties::TextColor::BasicColorFG& t) { NoStrideFunction no_stride(*buffer); return buf::WriteManip(*buffer).basic_write_type("\033[", static_cast(t), "m"); } - [[nodiscard]] std::expected execute_color(const TextProperties::TextColor::BasicColorBG& t) { + void execute_color(const TextProperties::TextColor::BasicColorBG& t) { NoStrideFunction no_stride(*buffer); return buf::WriteManip(*buffer).basic_write_type("\033[", static_cast(t), "m"); } - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::BasicColor& t) override { + void execute_color(const detail::TextProperties::TextColor::BasicColor& t) override { NoStrideFunction no_stride(*buffer); return buf::WriteManip(*buffer).basic_write_type("\033[", static_cast(t.fg), ";", static_cast(t.bg), "m"); } - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::Color24bFG& t) override { + void execute_color(const detail::TextProperties::TextColor::Color24bFG& t) override { NoStrideFunction no_stride(*buffer); return buf::WriteManip(*buffer).basic_write_type("\033[38;2;", t.r, ";", t.g, ";", t.b, "m"); } - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::Color24bBG& t) override { + void execute_color(const detail::TextProperties::TextColor::Color24bBG& t) override { NoStrideFunction no_stride(*buffer); return buf::WriteManip(*buffer).basic_write_type("\033[48;2;", t.r, ";", t.g, ";", t.b, "m"); } - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::Color24b& t) override { + void execute_color(const detail::TextProperties::TextColor::Color24b& t) override { NoStrideFunction no_stride(*buffer); return buf::WriteManip(*buffer).basic_write_type("\033[38;2;", t.fg.r, ";", t.fg.g, ";", t.fg.b, "; 48; 2;", t.bg.r, ";", t.bg.g, ";", t.bg.b, "m"); } - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::ColorCubeFG& t) override { + void execute_color(const detail::TextProperties::TextColor::ColorCubeFG& t) override { NoStrideFunction no_stride(*buffer); return buf::WriteManip(*buffer).basic_write_type("\033[38;5;", t.get_color_ref(), "m"); } - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::ColorCubeBG& t) override { + void execute_color(const detail::TextProperties::TextColor::ColorCubeBG& t) override { NoStrideFunction no_stride(*buffer); return buf::WriteManip(*buffer).basic_write_type("\033[48;5;", t.get_color_ref(), "m"); } - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::ColorCube& t) override { + void execute_color(const detail::TextProperties::TextColor::ColorCube& t) override { NoStrideFunction no_stride(*buffer); return buf::WriteManip(*buffer).basic_write_type("\033[48;5;", t.fg.get_color_ref(), ";48;5;", t.bg.get_color_ref(), "m"); } public: - [[nodiscard]] std::expected reset_front() override { + void reset_front() override { NoStrideFunction no_stride(*buffer); return buf::WriteManip(*buffer).basic_write_type("\033[", detail::TextProperties::TextFront::FrontID::DefaultFrontID, "m"); } - [[nodiscard]] std::expected execute_front(const detail::TextProperties::TextFront::FrontID& t) override { + void execute_front(const detail::TextProperties::TextFront::FrontID& t) override { NoStrideFunction no_stride(*buffer); return buf::WriteManip(*buffer).basic_write_type("\033[", t.id, "m"); } public: - [[nodiscard]] std::expected reset_style() override { + void reset_style() override { // TODO NoStrideFunction no_stride(*buffer); return buf::WriteManip(*buffer).fast_write_string_literal("\033[0m"); } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Intensity& t) override { + void execute_style(const detail::TextProperties::TextStyle::Intensity& t) override { NoStrideFunction no_stride(*buffer); return buf::WriteManip(*buffer).basic_write_type("\033[", static_cast(t), "m"); } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Italic& t) override { + void execute_style(const detail::TextProperties::TextStyle::Italic& t) override { NoStrideFunction no_stride(*buffer); return buf::WriteManip(*buffer).basic_write_type("\033[", static_cast(t), "m"); } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Underline& t) override { + void execute_style(const detail::TextProperties::TextStyle::Underline& t) override { NoStrideFunction no_stride(*buffer); return buf::WriteManip(*buffer).basic_write_type("\033[", static_cast(t), "m"); } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::UnderlineColor::Color&) override { + void execute_style(const detail::TextProperties::TextStyle::UnderlineColor::Color&) override { NoStrideFunction no_stride(*buffer); return buf::WriteManip(*buffer).basic_write_type("\033[59m"); } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::UnderlineColor::ColorCube& t) override { + void execute_style(const detail::TextProperties::TextStyle::UnderlineColor::ColorCube& t) override { NoStrideFunction no_stride(*buffer); return buf::WriteManip(*buffer).basic_write_type("\033[58;5;", t.get_color_ref(), "m"); } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::UnderlineColor::Color24b& t) override { + void execute_style(const detail::TextProperties::TextStyle::UnderlineColor::Color24b& t) override { NoStrideFunction no_stride(*buffer); return buf::WriteManip(*buffer).basic_write_type("\033[58;2;", t.r, ";", t.g, ";", t.b, "m"); } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Blink& t) override { + void execute_style(const detail::TextProperties::TextStyle::Blink& t) override { NoStrideFunction no_stride(*buffer); return buf::WriteManip(*buffer).basic_write_type("\033[", static_cast(t), "m"); } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Inverted& t) override { + void execute_style(const detail::TextProperties::TextStyle::Inverted& t) override { NoStrideFunction no_stride(*buffer); return buf::WriteManip(*buffer).basic_write_type("\033[", static_cast(t), "m"); } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Ideogram& t) override { + void execute_style(const detail::TextProperties::TextStyle::Ideogram& t) override { NoStrideFunction no_stride(*buffer); return buf::WriteManip(*buffer).basic_write_type("\033[", static_cast(t), "m"); } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Script& t) override { + void execute_style(const detail::TextProperties::TextStyle::Script& t) override { NoStrideFunction no_stride(*buffer); return buf::WriteManip(*buffer).basic_write_type("\033[", static_cast(t), "m"); } diff --git a/src/stream/fmt/context/formatter_executor/formatter_type.hxx b/src/stream/fmt/context/formatter_executor/formatter_type.hxx index d611864c..d803875a 100644 --- a/src/stream/fmt/context/formatter_executor/formatter_type.hxx +++ b/src/stream/fmt/context/formatter_executor/formatter_type.hxx @@ -6,7 +6,7 @@ namespace stream::fmt { template struct FormatterType { - [[nodiscard]] static std::expected format(const T&, FormatterExecutor& executor) { + static void format(const T&, FormatterExecutor& executor) { #ifdef UNKOWN_TYPE_MESSAGE executor.run("({C:red}FMT unknow type: {})", typeid(T).name()); #endif @@ -16,23 +16,22 @@ namespace stream::fmt { #ifdef UNKOWN_TYPE_DEBUG STREAMFORMAT_DEBUGBREAK(); #endif - return {}; } }; } // namespace stream::fmt -#define STREAMFORMAT_AUTO_FORMATTER(Type, formatstr, ...) \ - template \ - struct stream::fmt::FormatterType { \ - [[nodiscard]] static std::expected format(const Type&, FormatterExecutor& executor) { \ - return executor.run(formatstr, __VA_ARGS__); \ - } \ +#define STREAMFORMAT_AUTO_FORMATTER(Type, formatstr, ...) \ + template \ + struct stream::fmt::FormatterType { \ + static void format(const Type&, FormatterExecutor& executor) { \ + return executor.run(formatstr, __VA_ARGS__); \ + } \ }; -#define STREAMFORMAT_AUTO_FORMATTER_T(Type, formatstr, ...) \ - template \ - struct stream::fmt::FormatterType { \ - [[nodiscard]] static std::expected format(const Type&, FormatterExecutor& executor) { \ - return executor.run(formatstr, __VA_ARGS__); \ - } \ +#define STREAMFORMAT_AUTO_FORMATTER_T(Type, formatstr, ...) \ + template \ + struct stream::fmt::FormatterType { \ + static void format(const Type&, FormatterExecutor& executor) { \ + return executor.run(formatstr, __VA_ARGS__); \ + } \ }; diff --git a/src/stream/fmt/context/formatter_executor/index_args.hxx b/src/stream/fmt/context/formatter_executor/index_args.hxx index 12fd6875..95062044 100644 --- a/src/stream/fmt/context/formatter_executor/index_args.hxx +++ b/src/stream/fmt/context/formatter_executor/index_args.hxx @@ -6,7 +6,7 @@ namespace stream::fmt { template struct FCIndexArgs { public: - FCIndexArgs(const std::uint8_t idx, const T& t) : m_Value(t), idx_(idx) {} + FCIndexArgs(const std::uint8_t idx, const T& t) : value_(t), idx_(idx) {} public: inline bool IsRightIdx(std::uint8_t idx) const { @@ -15,18 +15,18 @@ namespace stream::fmt { public: inline const T& get_value() const { - return m_Value; + return value_; } protected: - const T& m_Value; + const T& value_; const std::uint8_t idx_; }; template struct FormatterType, FormatterExecutor> { template - [[nodiscard]] static inline std::expected format(const FCIndexArgs& t, FormatterExecutor& executor) { + static inline void format(const FCIndexArgs& t, FormatterExecutor& executor) { return executor.write_type(t.get_value()); } }; diff --git a/src/stream/fmt/context/formatter_executor/named_args.hxx b/src/stream/fmt/context/formatter_executor/named_args.hxx index 9d4e0458..cf9dd476 100644 --- a/src/stream/fmt/context/formatter_executor/named_args.hxx +++ b/src/stream/fmt/context/formatter_executor/named_args.hxx @@ -30,7 +30,7 @@ namespace stream::fmt { template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static inline std::expected format(const StringViewNamedArgs& t, FormatterExecutor& executor) { + static inline void format(const StringViewNamedArgs& t, FormatterExecutor& executor) { return executor.write_type(t.get_value()); } }; @@ -39,9 +39,7 @@ namespace stream::fmt { template struct StringNamedArgs { public: - StringNamedArgs(const std::string& str, const T& t) : name_(str), value(t) {} - - StringNamedArgs(std::string&& str, const T& t) : name_(std::move(str)), value(t) {} + StringNamedArgs(std::string str, const T& t) : name_(std::move(str)), value(t) {} public: T& get_value() { @@ -61,7 +59,7 @@ namespace stream::fmt { template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static inline std::expected format(const StringNamedArgs& t, FormatterExecutor& executor) { + static inline void format(const StringNamedArgs& t, FormatterExecutor& executor) { return executor.write_type(t.get_value()); } }; diff --git a/src/stream/fmt/context/formatter_executor/std_enumerable.hxx b/src/stream/fmt/context/formatter_executor/std_enumerable.hxx index daeee638..3371bd2e 100644 --- a/src/stream/fmt/context/formatter_executor/std_enumerable.hxx +++ b/src/stream/fmt/context/formatter_executor/std_enumerable.hxx @@ -18,47 +18,47 @@ namespace stream::fmt { template class STDEnumerable { public: - explicit inline STDEnumerable(const T& value, std::basic_string_view strJoin = ", ", std::basic_string_view strBegin = "{ ", - std::basic_string_view strEnd = " }", const std::int32_t beginIdx = 0, const std::int32_t size = -1) - : m_Value(value), m_StrJoin(strJoin), m_StrBegin(strBegin), m_StrEnd(strEnd), m_BeginIdx(beginIdx), m_Size(size < 0 ? (std::int32_t)value.size() - beginIdx : size) {} + explicit inline STDEnumerable(const T& value, std::basic_string_view join_str = ", ", std::basic_string_view begin_str = "{ ", + std::basic_string_view end_str = " }", const std::int32_t begin_idx = 0, const std::int32_t size = -1) + : value_(value), join_str_(join_str), begin_str_(begin_str), end_(end_str), begin_idx_(begin_idx), size_(size < 0 ? (std::int32_t)value.size() - begin_idx : size) {} inline const T& get_value() const { - return m_Value; + return value_; } inline std::basic_string_view get_str_join() const { - return m_StrJoin; + return join_str_; } inline std::basic_string_view get_str_begin() const { - return m_StrBegin; + return begin_str_; } inline std::basic_string_view get_str_end() const { - return m_StrEnd; + return end_; } inline std::int32_t get_begin_idx() const { - return m_BeginIdx; + return begin_idx_; } inline std::int32_t get_size() const { - return m_Size; + return size_; } private: - const T& m_Value; + const T& value_; - std::basic_string_view m_StrJoin; - std::basic_string_view m_StrBegin; - std::basic_string_view m_StrEnd; + std::basic_string_view join_str_; + std::basic_string_view begin_str_; + std::basic_string_view end_; - std::int32_t m_BeginIdx; - std::int32_t m_Size; + std::int32_t begin_idx_; + std::int32_t size_; }; template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static std::expected format(const STDEnumerable& enumerable, FormatterExecutor& executor) { - SF_VERIFY(executor.ostream.write_indent_string_view(enumerable.get_str_begin())); - SF_VERIFY(executor.ostream.add_indent(enumerable.get_str_begin().size())); + static void format(const STDEnumerable& enumerable, FormatterExecutor& executor) { + executor.ostream.write_indent_string_view(enumerable.get_str_begin()); + executor.ostream.add_indent(enumerable.get_str_begin().size()); { // TODO: Why ? ... @@ -69,15 +69,15 @@ namespace stream::fmt { if (first) { first = false; } else { - SF_VERIFY(executor.ostream.write_indent_string_view(enumerable.get_str_join())); + executor.ostream.write_indent_string_view(enumerable.get_str_join()); } - SF_VERIFY(executor.write_type(element)); + executor.write_type(element); }); } executor.ostream.remove_indent(enumerable.get_str_begin().size()); - SF_VERIFY(executor.ostream.write_indent_string_view(enumerable.get_str_end())); + executor.ostream.write_indent_string_view(enumerable.get_str_end()); } }; @@ -86,7 +86,7 @@ namespace stream::fmt { template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static inline std::expected format(const T& container, FormatterExecutor& executor) { + static inline void format(const T& container, FormatterExecutor& executor) { STDEnumerable enumerable(container, executor.data.get_as_text("join", STDEnumerableUtility::DefaultJoin), executor.data.get_as_text("begin", STDEnumerableUtility::DefaultBegin), executor.data.get_as_text("end", STDEnumerableUtility::DefaultEnd), executor.data.get_as_number("begin", 0), executor.data.get_as_number("size", -1)); diff --git a/src/stream/fmt/context/formatter_executor/utility_functions.hxx b/src/stream/fmt/context/formatter_executor/utility_functions.hxx index a2fd6d05..28852b90 100644 --- a/src/stream/fmt/context/formatter_executor/utility_functions.hxx +++ b/src/stream/fmt/context/formatter_executor/utility_functions.hxx @@ -15,104 +15,98 @@ namespace stream::fmt { namespace detail { template requires(IsCharType::value) - [[nodiscard]] std::expected format_in_manager(buf::BasicStreamIOManager& ostream_manager, bool newline, buf::StreamView format, - Args&&... args) { + void format_in_manager(buf::BasicStreamIOManager& ostream_manager, bool newline, buf::StreamView format, Args&&... args) { using TCharResolved = std::remove_const_t; detail::FormatterTextPropertiesExecutorANSI text_properties_executor; - buf::FMTStreamIO ostream = SF_TRY(buf::FMTStreamIO::create(ostream_manager)); + buf::FMTStreamIO ostream = buf::FMTStreamIO::create(ostream_manager); context::BasicFormatterExecutor executor(ostream, text_properties_executor); - SF_VERIFY(executor.run(format, std::forward(args)...)); - if (newline) SF_VERIFY(buf::ManipIO(ostream).pushback('\n')); + executor.run(format, std::forward(args)...); + if (newline) buf::ManipIO(ostream).pushback('\n'); return executor.terminate(); } template requires(IsCharType::value) - [[nodiscard]] std::expected format_in_manager(buf::BasicStreamIOManager& ostream_manager, bool newline, T&& t) { + void format_in_manager(buf::BasicStreamIOManager& ostream_manager, bool newline, T&& t) { using TCharResolved = std::remove_const_t; detail::FormatterTextPropertiesExecutorANSI text_properties_executor; - buf::FMTStreamIO ostream = SF_TRY(buf::FMTStreamIO::create(ostream_manager)); + buf::FMTStreamIO ostream = buf::FMTStreamIO::create(ostream_manager); context::BasicFormatterExecutor executor(ostream, text_properties_executor); - SF_VERIFY(executor.write_type(std::forward(t))); - if (newline) SF_VERIFY(buf::ManipIO(ostream).pushback('\n')); + executor.write_type(std::forward(t)); + if (newline) buf::ManipIO(ostream).pushback('\n'); return executor.terminate(); } } // namespace detail template requires(detail::IsCharType::value && buf::convertible_to_buffer_info_view) - [[nodiscard]] std::expected format_in_char(TChar (&buffer)[BUFFER_SIZE], Format&& format_input, Args&&... args) { + void format_in_char(TChar (&buffer)[BUFFER_SIZE], Format&& format_input, Args&&... args) { buf::GivenStreamIOManager ostream_manager(buffer); return detail::format_in_manager(ostream_manager, false, buf::StreamView{format_input}, std::forward(args)...); } template requires(detail::IsCharType::value && buf::convertible_to_buffer_info_view) - [[nodiscard]] std::expected format_in_char(TChar* const buffer, const std::size_t buffer_size, Format&& format_input, Args&&... args) { + void format_in_char(TChar* const buffer, const std::size_t buffer_size, Format&& format_input, Args&&... args) { buf::GivenStreamIOManager ostream_manager(buffer, buffer_size); return detail::format_in_manager(ostream_manager, false, buf::StreamView{format_input}, std::forward(args)...); } template requires(detail::IsCharType::value && buf::convertible_to_buffer_info_view) - [[nodiscard]] std::expected cfile_print(FILE* stream, Format&& format_input, Args&&... args) { + void cfile_print(FILE* stream, Format&& format_input, Args&&... args) { buf::DynamicStreamIOManager ostream_manager(256); - SF_VERIFY(detail::format_in_manager(ostream_manager, false, buf::StreamView{format_input}, std::forward(args)...)); + detail::format_in_manager(ostream_manager, false, buf::StreamView{format_input}, std::forward(args)...); std::fwrite(ostream_manager.get_buffer(), ostream_manager.get_last_generated_data_size(), 1, stream); std::fflush(stream); - return {}; } template requires(detail::IsCharType::value && buf::convertible_to_buffer_info_view) - [[nodiscard]] std::expected cfile_println(FILE* stream, Format&& format_input, Args&&... args) { + void cfile_println(FILE* stream, Format&& format_input, Args&&... args) { buf::DynamicStreamIOManager ostream_manager(256); - SF_VERIFY(detail::format_in_manager(ostream_manager, true, buf::StreamView{format_input}, std::forward(args)...)); + detail::format_in_manager(ostream_manager, true, buf::StreamView{format_input}, std::forward(args)...); std::fwrite(ostream_manager.get_buffer(), ostream_manager.get_last_generated_data_size(), 1, stream); std::fflush(stream); - return {}; } template requires(detail::IsCharType::value && buf::convertible_to_buffer_info_view) - [[nodiscard]] std::expected file_print(std::basic_ostream& stream, Format&& format_input, Args&&... args) { + void file_print(std::basic_ostream& stream, Format&& format_input, Args&&... args) { buf::DynamicStreamIOManager ostream_manager(256); - SF_VERIFY(detail::format_in_manager(ostream_manager, false, buf::StreamView{format_input}, std::forward(args)...)); + detail::format_in_manager(ostream_manager, false, buf::StreamView{format_input}, std::forward(args)...); stream.write(ostream_manager.get_buffer(), ostream_manager.get_last_generated_data_size()); stream.flush(); - return {}; } template requires(detail::IsCharType::value && buf::convertible_to_buffer_info_view) - [[nodiscard]] std::expected file_println(std::basic_ostream& stream, Format&& format_input, Args&&... args) { + void file_println(std::basic_ostream& stream, Format&& format_input, Args&&... args) { buf::DynamicStreamIOManager ostream_manager(256); - SF_VERIFY(detail::format_in_manager(ostream_manager, true, buf::StreamView{format_input}, std::forward(args)...)); + detail::format_in_manager(ostream_manager, true, buf::StreamView{format_input}, std::forward(args)...); stream.write(ostream_manager.get_buffer(), ostream_manager.get_last_generated_data_size()); stream.flush(); - return {}; } template requires(detail::IsCharType::value && buf::convertible_to_buffer_info_view) - [[nodiscard]] std::expected format_in_string(std::basic_string& str, Format&& format_input, Args&&... args) { + void format_in_string(std::basic_string& str, Format&& format_input, Args&&... args) { buf::DynamicStreamIOManager ostream_manager(256); - SF_VERIFY(detail::format_in_manager(ostream_manager, false, buf::StreamView{format_input}, std::forward(args)...)); + detail::format_in_manager(ostream_manager, false, buf::StreamView{format_input}, std::forward(args)...); str = ostream_manager.get_last_generated_string_view(); - return {}; } template requires(detail::IsCharType::value && buf::convertible_to_buffer_info_view) - [[nodiscard]] inline std::expected, FMTResult> format_string(Format&& format_input, Args&&... args) { + inline std::basic_string format_string(Format&& format_input, Args&&... args) { buf::DynamicStreamIOManager ostream_manager(256); - SF_VERIFY(detail::format_in_manager(ostream_manager, false, buf::StreamView{format_input}, std::forward(args)...)); + detail::format_in_manager(ostream_manager, false, buf::StreamView{format_input}, std::forward(args)...); return std::basic_string{ostream_manager.get_last_generated_string_view()}; } @@ -120,128 +114,71 @@ namespace stream::fmt { template requires(detail::IsCharType::value) - [[nodiscard]] std::expected format_in_char(TChar (&buffer)[BUFFER_SIZE], T&& t) { + void format_in_char(TChar (&buffer)[BUFFER_SIZE], T&& t) { buf::GivenStreamIOManager ostream_manager(buffer, BUFFER_SIZE); return detail::format_in_manager(ostream_manager, false, std::forward(t)); } template requires(detail::IsCharType::value) - [[nodiscard]] std::expected format_in_char(TChar* const buffer, const std::size_t buffer_size, T&& t) { + void format_in_char(TChar* const buffer, const std::size_t buffer_size, T&& t) { buf::GivenStreamIOManager ostream_manager(buffer, buffer_size); return detail::format_in_manager(ostream_manager, false, std::forward(t)); } template requires(detail::IsCharType::value) - [[nodiscard]] std::expected cfile_print(FILE* stream, T&& t) { + void cfile_print(FILE* stream, T&& t) { buf::DynamicStreamIOManager ostream_manager(32); - SF_VERIFY(detail::format_in_manager(ostream_manager, false, std::forward(t))); + detail::format_in_manager(ostream_manager, false, std::forward(t)); std::fwrite(ostream_manager.get_buffer(), static_cast(ostream_manager.get_last_generated_data_size()), 1, stream); std::fflush(stream); - return {}; } template requires(detail::IsCharType::value) - [[nodiscard]] std::expected cfile_println(FILE* stream, T&& t) { + void cfile_println(FILE* stream, T&& t) { buf::DynamicStreamIOManager ostream_manager(32); - SF_VERIFY(detail::format_in_manager(ostream_manager, true, std::forward(t))); + detail::format_in_manager(ostream_manager, true, std::forward(t)); std::fwrite(ostream_manager.get_buffer(), static_cast(ostream_manager.get_last_generated_data_size()), 1, stream); std::fflush(stream); - return {}; } template requires(detail::IsCharType::value) - [[nodiscard]] std::expected file_print(std::basic_ostream& stream, T&& t) { + void file_print(std::basic_ostream& stream, T&& t) { buf::DynamicStreamIOManager ostream_manager(32); - SF_VERIFY(detail::format_in_manager(ostream_manager, false, std::forward(t))); + detail::format_in_manager(ostream_manager, false, std::forward(t)); stream.write(ostream_manager.get_buffer(), static_cast(ostream_manager.get_last_generated_data_size())); stream.flush(); - return {}; } template requires(detail::IsCharType::value) - [[nodiscard]] std::expected file_println(std::basic_ostream& stream, T&& t) { + void file_println(std::basic_ostream& stream, T&& t) { buf::DynamicStreamIOManager ostream_manager(32); - SF_VERIFY(detail::format_in_manager(ostream_manager, true, std::forward(t))); + detail::format_in_manager(ostream_manager, true, std::forward(t)); stream.write(ostream_manager.get_buffer(), static_cast(ostream_manager.get_last_generated_data_size())); stream.flush(); - return {}; } template requires(detail::IsCharType::value) - [[nodiscard]] std::expected format_in_string(std::basic_string& str, T&& t) { + void format_in_string(std::basic_string& str, T&& t) { buf::DynamicStreamIOManager ostream_manager(32); - SF_VERIFY(detail::format_in_manager(ostream_manager, false, std::forward(t))); + detail::format_in_manager(ostream_manager, false, std::forward(t)); str = ostream_manager.get_last_generated_string_view(); - return {}; } template requires(detail::IsCharType::value) - [[nodiscard]] inline std::expected, FMTResult> format_string(T&& t) { + inline std::basic_string format_string(T&& t) { buf::DynamicStreamIOManager ostream_manager(32); - SF_VERIFY(detail::format_in_manager(ostream_manager, false, std::forward(t))); + detail::format_in_manager(ostream_manager, false, std::forward(t)); return std::string{ostream_manager.get_last_generated_string_view()}; } } // namespace stream::fmt - -namespace stream::fmt { - template - struct FormatterType { - [[nodiscard]] static std::expected format(FMTResult result, FormatterExecutor& executor) { - switch (result) { - case FMTResult::FunctionNotImpl: - return buf::WriteManip(executor.ostream).fast_write_string_literal("FunctionNotImpl"); - case FMTResult::Buffer_NonValid: - return buf::WriteManip(executor.ostream).fast_write_string_literal("Buffer_NonValid"); - case FMTResult::Buffer_OutOfBoundAccess: - return buf::WriteManip(executor.ostream).fast_write_string_literal("Buffer_OutOfBoundAccess"); - case FMTResult::Buffer_UnableToReserveMemory: - return buf::WriteManip(executor.ostream).fast_write_string_literal("Buffer_UnableToReserveMemory"); - case FMTResult::Parse_NonValidDigit: - return buf::WriteManip(executor.ostream).fast_write_string_literal("Parse_NonValidDigit"); - case FMTResult::Parse_TokenNotExpected: - return buf::WriteManip(executor.ostream).fast_write_string_literal("Parse_TokenNotExpected"); - case FMTResult::ArgsInterface_Unavaible: - return buf::WriteManip(executor.ostream).fast_write_string_literal("ArgsInterface_Unavaible"); - case FMTResult::ArgsInterface_InvalidTypeID: - return buf::WriteManip(executor.ostream).fast_write_string_literal("ArgsInterface_InvalidTypeID"); - case FMTResult::ArgsInterface_InvalidConversion: - return buf::WriteManip(executor.ostream).fast_write_string_literal("ArgsInterface_InvalidConversion"); - case FMTResult::ArgsInterface_CantMatchNamedArgs: - return buf::WriteManip(executor.ostream).fast_write_string_literal("ArgsInterface_CantMatchNamedArgs"); - case FMTResult::ArgsInterface_IndexOutOfBounds: - return buf::WriteManip(executor.ostream).fast_write_string_literal("ArgsInterface_IndexOutOfBounds"); - case FMTResult::Specifiers_Full: - return buf::WriteManip(executor.ostream).fast_write_string_literal("Specifiers_Full"); - case FMTResult::Specifiers_Invalid: - return buf::WriteManip(executor.ostream).fast_write_string_literal("Specifiers_Invalid"); - case FMTResult::Specifiers_DoesNotExist: - return buf::WriteManip(executor.ostream).fast_write_string_literal("Specifiers_DoesNotExist"); - case FMTResult::Context_ParsingFormat: - return buf::WriteManip(executor.ostream).fast_write_string_literal("Context_ParsingFormat"); - case FMTResult::Context_ArgumentIndexResolution: - return buf::WriteManip(executor.ostream).fast_write_string_literal("Context_ArgumentIndexResolution"); - case FMTResult::Context_ArgumentIndexExpected: - return buf::WriteManip(executor.ostream).fast_write_string_literal("Context_ArgumentIndexExpected"); - case FMTResult::Context_CannotapplyType: - return buf::WriteManip(executor.ostream).fast_write_string_literal("Context_CannotapplyType"); - case FMTResult::GivenArgs_UnableToDeduceSize: - return buf::WriteManip(executor.ostream).fast_write_string_literal("GivenArgs_UnableToDeduceSize"); - case FMTResult::Manager_StaticMemory: - return buf::WriteManip(executor.ostream).fast_write_string_literal("Manager_StaticMemory"); - case FMTResult::Manager_AllocationFailed: - return buf::WriteManip(executor.ostream).fast_write_string_literal("Manager_AllocationFailed"); - } - } - }; -} // namespace stream::fmt diff --git a/src/stream/fmt/context/parser_executor/basic_parser_executor.hxx b/src/stream/fmt/context/parser_executor/basic_parser_executor.hxx index 6b9b0c3e..55aadd3d 100644 --- a/src/stream/fmt/context/parser_executor/basic_parser_executor.hxx +++ b/src/stream/fmt/context/parser_executor/basic_parser_executor.hxx @@ -25,7 +25,7 @@ namespace stream::fmt::context { BasicParserExecutor(buf::StreamView& istream, detail::ITextPropertiesExecutor& text_properties_executor); ~BasicParserExecutor() override = default; - [[nodiscard]] std::expected terminate(); + void terminate(); public: buf::StreamView& istream; @@ -34,27 +34,22 @@ namespace stream::fmt::context { using context_executor::text_manager; protected: - [[nodiscard]] std::expected exec_raw_string(std::basic_string_view sv) override { - SF_VERIFY(buf::TestManip(istream).is_same_forward(sv.data(), sv.size())); - return {}; + void exec_raw_string(std::basic_string_view sv) override { + buf::TestManip(istream).is_same_forward(sv.data(), sv.size()); } - [[nodiscard]] std::expected exec_settings() override { - return {}; - }; + void exec_settings() override {}; public: template - [[nodiscard]] std::expected run_(buf::StreamView format, Args&&... args); + void run_(buf::StreamView format, Args&&... args); template - [[nodiscard]] std::expected run(Format&& format, Args&&... args); + void run(Format&& format, Args&&... args); public: template - [[nodiscard]] inline std::expected read_type(Type& type, Rest&... rest) { - auto&& parseErr = ParserType>::type, M_Type>::parse(type, *this); - SF_VERIFY(parseErr); - if constexpr (sizeof...(rest) > 0) SF_VERIFY(read_type(std::forward(rest)...)); - return {}; + void read_type(Type& type, Rest&... rest) { + ParserType>::type, M_Type>::parse(type, *this); + if constexpr (sizeof...(rest) > 0) read_type(std::forward(rest)...); } }; } // namespace stream::fmt::context @@ -67,24 +62,22 @@ namespace stream::fmt::context { } template - [[nodiscard]] std::expected BasicParserExecutor::terminate() { - return {}; - } + void BasicParserExecutor::terminate() {} template template - [[nodiscard]] std::expected BasicParserExecutor::run_(buf::StreamView format, Args&&... args) { + void BasicParserExecutor::run_(buf::StreamView format, Args&&... args) { auto args_interface = detail::ParserArgsInterface, Args...>(*this, std::forward(args)...); detail::TextProperties::Properties saveTextProperties = text_manager.save(); context::BasicContext context(*this, format, args_interface); - SF_VERIFY(context.run()); + context.run(); return text_manager.reload(saveTextProperties); } template template - [[nodiscard]] std::expected BasicParserExecutor::run(Format&& format_input, Args&&... args) { + void BasicParserExecutor::run(Format&& format_input, Args&&... args) { return run_(buf::StreamView{format_input}, std::forward(args)...); } } // namespace stream::fmt::context diff --git a/src/stream/fmt/context/parser_executor/parse_basics_impl.hxx b/src/stream/fmt/context/parser_executor/parse_basics_impl.hxx index d54c987c..f966dc22 100644 --- a/src/stream/fmt/context/parser_executor/parse_basics_impl.hxx +++ b/src/stream/fmt/context/parser_executor/parse_basics_impl.hxx @@ -5,7 +5,7 @@ namespace stream::fmt { //----------------------------------------------// - //----------------- Forwarders -----------------// + //----------------- forwarders -----------------// //----------------------------------------------// //-----------------------------------------------// @@ -14,38 +14,37 @@ namespace stream::fmt { template struct ParserType { - [[nodiscard]] static std::expected parse(bool& t, ParserExecutor& executor) { + static void parse(bool& t, ParserExecutor& executor) { if (!executor.data.prefix_suffix) { if (buf::TestAccess(executor.istream).is_equal_to('t', 'T')) { - SF_VERIFY(buf::Manip(executor.istream).forward()); + buf::Manip(executor.istream).forward(); if (buf::TestAccess(executor.istream).is_same("rue")) { - SF_VERIFY(buf::Manip(executor.istream).forward(3)); + buf::Manip(executor.istream).forward(3); t = true; } } else if (buf::TestAccess(executor.istream).is_equal_to('f', 'F')) { - SF_VERIFY(buf::Manip(executor.istream).forward()); + buf::Manip(executor.istream).forward(); if (buf::TestAccess(executor.istream).is_same("alse")) { - SF_VERIFY(buf::Manip(executor.istream).forward(4)); + buf::Manip(executor.istream).forward(4); t = false; } } } else { if (buf::TestAccess(executor.istream).is_equal_to('1')) { - SF_VERIFY(buf::Manip(executor.istream).forward()); + buf::Manip(executor.istream).forward(); t = true; } else if (buf::TestAccess(executor.istream).is_equal_to('0')) { - SF_VERIFY(buf::Manip(executor.istream).forward()); + buf::Manip(executor.istream).forward(); t = false; } } - return {}; } }; template requires(std::is_integral_v && !std::is_floating_point_v && !detail::IsCharType::value) struct ParserType { - [[nodiscard]] static inline std::expected parse(T& t, ParserExecutor& executor) { + static inline void parse(T& t, ParserExecutor& executor) { return buf::FMTReadManip(executor.istream).read_integer_format_data(t, executor.data); } }; @@ -53,7 +52,7 @@ namespace stream::fmt { template requires std::is_floating_point_v struct ParserType { - [[nodiscard]] static inline std::expected parse(T& t, ParserExecutor& executor) { + static inline void parse(T& t, ParserExecutor& executor) { return buf::FMTReadManip(executor.istream).read_float_format_data(t, executor.data); } }; @@ -64,28 +63,28 @@ namespace stream::fmt { template struct ParserType { - [[nodiscard]] static inline std::expected parse(void*&, ParserExecutor&) { + static inline void parse(void*&, ParserExecutor&) { // FIXME // TODO - return std::unexpected(FMTResult::FunctionNotImpl); + throw std::runtime_error("fmt error: FunctionNotImpl"); } }; template struct ParserType { - [[nodiscard]] static inline std::expected parse(T*&, ParserExecutor&) { + static inline void parse(T*&, ParserExecutor&) { // FIXME // TODO - return std::unexpected(FMTResult::FunctionNotImpl); + throw std::runtime_error("fmt error: FunctionNotImpl"); } }; template struct ParserType { - [[nodiscard]] static inline std::expected parse(T (&)[SIZE], ParserExecutor&) { + static inline void parse(T (&)[SIZE], ParserExecutor&) { // FIXME // TODO - return std::unexpected(FMTResult::FunctionNotImpl); + throw std::runtime_error("fmt error: FunctionNotImpl"); } }; } // namespace stream::fmt diff --git a/src/stream/fmt/context/parser_executor/parse_text_properties_impl.hxx b/src/stream/fmt/context/parser_executor/parse_text_properties_impl.hxx index 9fea0316..f35a49f6 100644 --- a/src/stream/fmt/context/parser_executor/parse_text_properties_impl.hxx +++ b/src/stream/fmt/context/parser_executor/parse_text_properties_impl.hxx @@ -9,28 +9,28 @@ namespace stream::fmt { template struct ParserType { - [[nodiscard]] static inline std::expected parse(detail::TextProperties::ResetProperties, ParserExecutor& executor) { + static inline void parse(detail::TextProperties::ResetProperties, ParserExecutor& executor) { return executor.text_manager.all_properties_reset(); } }; template struct ParserType { - [[nodiscard]] static inline std::expected parse(detail::TextProperties::TextColor::reset_color, ParserExecutor& executor) { + static inline void parse(detail::TextProperties::TextColor::reset_color, ParserExecutor& executor) { return executor.text_manager.apply_color_reset(); } }; template struct ParserType { - [[nodiscard]] static inline std::expected parse(detail::TextProperties::TextStyle::reset_style, ParserExecutor& executor) { + static inline void parse(detail::TextProperties::TextStyle::reset_style, ParserExecutor& executor) { return executor.text_manager.apply_style_reset(); } }; template struct ParserType { - [[nodiscard]] static inline std::expected parse(detail::TextProperties::TextFront::ResetFront, ParserExecutor& executor) { + static inline void parse(detail::TextProperties::TextFront::ResetFront, ParserExecutor& executor) { return executor.text_manager.apply_front_reset(); } }; @@ -42,7 +42,7 @@ namespace stream::fmt { template requires detail::text_properties_color_is_apply struct ParserType { - [[nodiscard]] static inline std::expected parse(T& t, ParserExecutor& executor) { + static inline void parse(T& t, ParserExecutor& executor) { return executor.text_manager.ask_apply_color(t); } }; @@ -50,7 +50,7 @@ namespace stream::fmt { template requires detail::TextPropertiesStyleIsapply struct ParserType { - [[nodiscard]] static inline std::expected parse(T& t, ParserExecutor& executor) { + static inline void parse(T& t, ParserExecutor& executor) { return executor.text_manager.ask_apply_style(t); } }; @@ -58,7 +58,7 @@ namespace stream::fmt { template requires detail::TextPropertiesFrontIsapply struct ParserType { - [[nodiscard]] static inline std::expected parse(T& t, ParserExecutor& executor) { + static inline void parse(T& t, ParserExecutor& executor) { return executor.text_manager.ask_apply_front(t); } }; diff --git a/src/stream/fmt/context/parser_executor/parser_args.hxx b/src/stream/fmt/context/parser_executor/parser_args.hxx index 2f74a540..816c6815 100644 --- a/src/stream/fmt/context/parser_executor/parser_args.hxx +++ b/src/stream/fmt/context/parser_executor/parser_args.hxx @@ -23,19 +23,19 @@ namespace stream::fmt::detail { public: template - [[nodiscard]] inline std::expected run_type_at(FormatterExecutor&, std::int32_t) { - return std::unexpected(FMTResult::ArgsInterface_IndexOutOfBounds); + void run_type_at(FormatterExecutor&, std::int32_t) { + throw std::runtime_error("fmt error: ArgsInterface_IndexOutOfBounds"); } template - [[nodiscard]] inline std::expected get_index_of_current_named_arg(buf::StreamView& format, std::int32_t) { - return std::unexpected(FMTResult::ArgsInterface_CantMatchNamedArgs); + inline std::optional get_index_of_current_named_arg(buf::StreamView& format, std::int32_t) { + return std::nullopt; } - [[nodiscard]] inline std::expected get_pointerid_at(std::int32_t) { - return std::unexpected(FMTResult::ArgsInterface_IndexOutOfBounds); + inline PointerID get_pointerid_at(std::int32_t) { + throw std::runtime_error("fmt error: ArgsInterface_IndexOutOfBounds"); } template - [[nodiscard]] inline std::expected get_converted_type_at(std::int32_t) { - return std::unexpected(FMTResult::ArgsInterface_IndexOutOfBounds); + inline T get_converted_type_at(std::int32_t) { + throw std::runtime_error("fmt error: ArgsInterface_IndexOutOfBounds"); } }; @@ -45,10 +45,10 @@ namespace stream::fmt::detail { using TypeWithoutRef = std::remove_reference_t; public: - ParserArgs(TypeWithoutRef& t, Rest&... rest) : ParserArgs(std::forward(rest)...), m_Value(t) {} + ParserArgs(TypeWithoutRef& t, Rest&... rest) : ParserArgs(std::forward(rest)...), value_(t) {} private: - TypeWithoutRef& m_Value; + TypeWithoutRef& value_; public: static inline constexpr std::size_t size() { @@ -57,37 +57,37 @@ namespace stream::fmt::detail { public: template - [[nodiscard]] inline std::expected run_type_at(Executor& executor, std::int32_t idx) { + void run_type_at(Executor& executor, std::int32_t idx) { if (idx == 0) { - return executor.read_type(m_Value); + return executor.read_type(value_); } return ParserArgs::run_type_at(executor, idx - 1); } public: template - [[nodiscard]] inline std::expected get_index_of_current_named_arg(buf::StreamView& format, std::int32_t begin_search_index) { + inline std::optional get_index_of_current_named_arg(buf::StreamView& format, std::int32_t begin_search_index) { if constexpr (detail::IsANamedArgs>::value) { - bool current_is_a_named_arg = SF_TRY(buf::FMTParamsManip(format).next_is_named_args(m_Value.get_name())); + bool current_is_a_named_arg = buf::FMTParamsManip(format).next_is_named_args(value_.get_name()); if (current_is_a_named_arg) return begin_search_index; } return ParserArgs::get_index_of_current_named_arg(format, begin_search_index + 1); } public: - [[nodiscard]] inline std::expected get_pointerid_at(std::int32_t idx) { - if (idx == 0) return PointerID{.type_info = typeid(TypeWithoutRef), .ptr = static_cast(&m_Value)}; + inline PointerID get_pointerid_at(std::int32_t idx) { + if (idx == 0) return PointerID{.type_info = typeid(TypeWithoutRef), .ptr = static_cast(&value_)}; return ParserArgs::get_pointerid_at(idx - 1); } public: template - [[nodiscard]] inline std::expected get_converted_type_at(std::int32_t idx) { + inline T get_converted_type_at(std::int32_t idx) { if (idx == 0) { if constexpr (FMTCanContextConvert) { - return FMTContextConvert::convert(m_Value); + return FMTContextConvert::convert(value_); } else { - return std::unexpected(FMTResult::ArgsInterface_InvalidConversion); + throw std::runtime_error("fmt error: ArgsInterface_InvalidConversion"); } } return ParserArgs::template get_converted_type_at(idx - 1); @@ -113,21 +113,21 @@ namespace stream::fmt::detail { } public: - [[nodiscard]] std::expected run_type_at(std::int32_t idx) override { + void run_type_at(std::int32_t idx) override { return args_interface.run_type_at(executor, idx); } - [[nodiscard]] std::expected get_index_of_current_named_arg(buf::StreamView& format) override { + std::optional get_index_of_current_named_arg(buf::StreamView& format) override { return args_interface.get_index_of_current_named_arg(format, std::int32_t{0}); } - [[nodiscard]] inline std::expected get_pointerid_at(std::int32_t idx) override { + inline PointerID get_pointerid_at(std::int32_t idx) override { return args_interface.get_pointerid_at(idx); } public: - [[nodiscard]] std::expected, FMTResult> get_string_at(std::int32_t idx) override { + typename std::basic_string_view get_string_at(std::int32_t idx) override { return args_interface.template get_converted_type_at>(idx); } - [[nodiscard]] std::expected get_int_at(std::int32_t idx) override { + std::int64_t get_int_at(std::int32_t idx) override { return args_interface.template get_converted_type_at(idx); } diff --git a/src/stream/fmt/context/parser_executor/parser_text_properties_executor/parser_text_properties_executor.hxx b/src/stream/fmt/context/parser_executor/parser_text_properties_executor/parser_text_properties_executor.hxx index 7a33ddf4..66067e1b 100644 --- a/src/stream/fmt/context/parser_executor/parser_text_properties_executor/parser_text_properties_executor.hxx +++ b/src/stream/fmt/context/parser_executor/parser_text_properties_executor/parser_text_properties_executor.hxx @@ -30,81 +30,35 @@ namespace stream::fmt::detail { using IParserTextPropertiesExecutor::buffer; public: - [[nodiscard]] std::expected all_properties_reset() override { - return {}; - } + void all_properties_reset() override {} public: - [[nodiscard]] std::expected reset_color() override {} - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::BasicColorFG&) override { - return {}; - } - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::BasicColorBG&) override { - return {}; - } - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::BasicColor&) override { - return {}; - } - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::Color24bFG&) override { - return {}; - } - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::Color24bBG&) override { - return {}; - } - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::Color24b&) override { - return {}; - } - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::ColorCubeFG&) override { - return {}; - } - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::ColorCubeBG&) override { - return {}; - } - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::ColorCube&) override { - return {}; - } + void reset_color() override {} + void execute_color(const detail::TextProperties::TextColor::BasicColorFG&) override {} + void execute_color(const detail::TextProperties::TextColor::BasicColorBG&) override {} + void execute_color(const detail::TextProperties::TextColor::BasicColor&) override {} + void execute_color(const detail::TextProperties::TextColor::Color24bFG&) override {} + void execute_color(const detail::TextProperties::TextColor::Color24bBG&) override {} + void execute_color(const detail::TextProperties::TextColor::Color24b&) override {} + void execute_color(const detail::TextProperties::TextColor::ColorCubeFG&) override {} + void execute_color(const detail::TextProperties::TextColor::ColorCubeBG&) override {} + void execute_color(const detail::TextProperties::TextColor::ColorCube&) override {} public: - [[nodiscard]] std::expected reset_front() override { - return {}; - } - [[nodiscard]] std::expected execute_front(const detail::TextProperties::TextFront::FrontID&) override { - return {}; - } + void reset_front() override {} + void execute_front(const detail::TextProperties::TextFront::FrontID&) override {} public: - [[nodiscard]] std::expected reset_style() override { - return {}; - } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Intensity&) override { - return {}; - } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Italic&) override { - return {}; - } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Underline&) override { - return {}; - } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::UnderlineColor::Color&) override { - return {}; - } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::UnderlineColor::ColorCube&) override { - return {}; - } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::UnderlineColor::Color24b&) override { - return {}; - } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Blink&) override { - return {}; - } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Inverted&) override { - return {}; - } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Ideogram&) override { - return {}; - } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Script&) override { - return {}; - } + void reset_style() override {} + void execute_style(const detail::TextProperties::TextStyle::Intensity&) override {} + void execute_style(const detail::TextProperties::TextStyle::Italic&) override {} + void execute_style(const detail::TextProperties::TextStyle::Underline&) override {} + void execute_style(const detail::TextProperties::TextStyle::UnderlineColor::Color&) override {} + void execute_style(const detail::TextProperties::TextStyle::UnderlineColor::ColorCube&) override {} + void execute_style(const detail::TextProperties::TextStyle::UnderlineColor::Color24b&) override {} + void execute_style(const detail::TextProperties::TextStyle::Blink&) override {} + void execute_style(const detail::TextProperties::TextStyle::Inverted&) override {} + void execute_style(const detail::TextProperties::TextStyle::Ideogram&) override {} + void execute_style(const detail::TextProperties::TextStyle::Script&) override {} }; } // namespace stream::fmt::detail diff --git a/src/stream/fmt/context/parser_executor/parser_text_properties_executor/parser_text_properties_executor_ansi.hxx b/src/stream/fmt/context/parser_executor/parser_text_properties_executor/parser_text_properties_executor_ansi.hxx index ac641c1b..788058d0 100644 --- a/src/stream/fmt/context/parser_executor/parser_text_properties_executor/parser_text_properties_executor_ansi.hxx +++ b/src/stream/fmt/context/parser_executor/parser_text_properties_executor/parser_text_properties_executor_ansi.hxx @@ -12,106 +12,106 @@ namespace stream::fmt::detail { using IParserTextPropertiesExecutor::buffer; public: - [[nodiscard]] std::expected all_properties_reset() override { - return std::unexpected(FMTResult::FunctionNotImpl); + void all_properties_reset() override { + throw std::runtime_error("fmt error: FunctionNotImpl"); /*ReadManip(buffer).BasicReadType('\033', '[', 0, 'm');*/ } public: - [[nodiscard]] std::expected reset_color() override { - return std::unexpected(FMTResult::FunctionNotImpl); + void reset_color() override { + throw std::runtime_error("fmt error: FunctionNotImpl"); /*ReadManip(buffer).BasicReadType('\033', '[', 39, ';', 49, 'm');*/ } - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::BasicColorFG&) override { - return std::unexpected(FMTResult::FunctionNotImpl); + void execute_color(const detail::TextProperties::TextColor::BasicColorFG&) override { + throw std::runtime_error("fmt error: FunctionNotImpl"); /*ReadManip(buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ } - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::BasicColorBG&) override { - return std::unexpected(FMTResult::FunctionNotImpl); + void execute_color(const detail::TextProperties::TextColor::BasicColorBG&) override { + throw std::runtime_error("fmt error: FunctionNotImpl"); /*ReadManip(buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ } - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::BasicColor&) override { - return std::unexpected(FMTResult::FunctionNotImpl); + void execute_color(const detail::TextProperties::TextColor::BasicColor&) override { + throw std::runtime_error("fmt error: FunctionNotImpl"); /*ReadManip(buffer).BasicReadType('\033', '[', static_cast(t.fg) , ';', static_cast(t.bg), 'm');*/ } - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::Color24bFG&) override { - return std::unexpected(FMTResult::FunctionNotImpl); + void execute_color(const detail::TextProperties::TextColor::Color24bFG&) override { + throw std::runtime_error("fmt error: FunctionNotImpl"); /*ReadManip(buffer).BasicReadType("\033[38;2;", t.r, ';', t.g, ';', t.b, 'm');*/ } - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::Color24bBG&) override { - return std::unexpected(FMTResult::FunctionNotImpl); + void execute_color(const detail::TextProperties::TextColor::Color24bBG&) override { + throw std::runtime_error("fmt error: FunctionNotImpl"); /*ReadManip(buffer).BasicReadType("\033[48;2;", t.r, ';', t.g, ';', t.b, 'm');*/ } - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::Color24b&) override { - return std::unexpected(FMTResult::FunctionNotImpl); + void execute_color(const detail::TextProperties::TextColor::Color24b&) override { + throw std::runtime_error("fmt error: FunctionNotImpl"); /*ReadManip(buffer).BasicReadType("\033[38;2;", t.fg.r, ';', t.fg.g, ';', t.fg.b, "; 48; 2;", t.bg.r, ';', t.bg.g, ';', t.bg.b, 'm');*/ } - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::ColorCubeFG&) override { - return std::unexpected(FMTResult::FunctionNotImpl); + void execute_color(const detail::TextProperties::TextColor::ColorCubeFG&) override { + throw std::runtime_error("fmt error: FunctionNotImpl"); /*ReadManip(buffer).BasicReadType("\033[38;5;", t.get_color_ref(), 'm');*/ } - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::ColorCubeBG&) override { - return std::unexpected(FMTResult::FunctionNotImpl); + void execute_color(const detail::TextProperties::TextColor::ColorCubeBG&) override { + throw std::runtime_error("fmt error: FunctionNotImpl"); /*ReadManip(buffer).BasicReadType("\033[48;5;", t.get_color_ref(), 'm');*/ } - [[nodiscard]] std::expected execute_color(const detail::TextProperties::TextColor::ColorCube&) override { - return std::unexpected(FMTResult::FunctionNotImpl); + void execute_color(const detail::TextProperties::TextColor::ColorCube&) override { + throw std::runtime_error("fmt error: FunctionNotImpl"); /*ReadManip(buffer).BasicReadType("\033[48;5;", t.fg.get_color_ref(), ";48;5;", t.bg.get_color_ref(), 'm');*/ } public: - [[nodiscard]] std::expected reset_front() override { - return std::unexpected(FMTResult::FunctionNotImpl); + void reset_front() override { + throw std::runtime_error("fmt error: FunctionNotImpl"); /*ReadManip(buffer).BasicReadType('\033', '[', detail::TextProperties::TextFront::FrontID::DefaultFrontID, 'm');*/ } - [[nodiscard]] std::expected execute_front(const detail::TextProperties::TextFront::FrontID&) override { - return std::unexpected(FMTResult::FunctionNotImpl); + void execute_front(const detail::TextProperties::TextFront::FrontID&) override { + throw std::runtime_error("fmt error: FunctionNotImpl"); /*ReadManip(buffer).BasicReadType('\033', '[', t.id, 'm');*/ } public: - [[nodiscard]] std::expected reset_style() override { - return std::unexpected(FMTResult::FunctionNotImpl); + void reset_style() override { + throw std::runtime_error("fmt error: FunctionNotImpl"); /*ReadManip(buffer).BasicReadType('\033', '[', 0, 'm');*/ } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Intensity&) override { - return std::unexpected(FMTResult::FunctionNotImpl); + void execute_style(const detail::TextProperties::TextStyle::Intensity&) override { + throw std::runtime_error("fmt error: FunctionNotImpl"); /*ReadManip(buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Italic&) override { - return std::unexpected(FMTResult::FunctionNotImpl); + void execute_style(const detail::TextProperties::TextStyle::Italic&) override { + throw std::runtime_error("fmt error: FunctionNotImpl"); /*ReadManip(buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Underline&) override { - return std::unexpected(FMTResult::FunctionNotImpl); + void execute_style(const detail::TextProperties::TextStyle::Underline&) override { + throw std::runtime_error("fmt error: FunctionNotImpl"); /*ReadManip(buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::UnderlineColor::Color&) override { - return std::unexpected(FMTResult::FunctionNotImpl); + void execute_style(const detail::TextProperties::TextStyle::UnderlineColor::Color&) override { + throw std::runtime_error("fmt error: FunctionNotImpl"); /*ReadManip(buffer).BasicReadType("\033[59m");*/ } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::UnderlineColor::ColorCube&) override { - return std::unexpected(FMTResult::FunctionNotImpl); + void execute_style(const detail::TextProperties::TextStyle::UnderlineColor::ColorCube&) override { + throw std::runtime_error("fmt error: FunctionNotImpl"); /*ReadManip(buffer).BasicReadType("\033[58;5;", t.get_color_ref(), 'm');*/ } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::UnderlineColor::Color24b&) override { - return std::unexpected(FMTResult::FunctionNotImpl); + void execute_style(const detail::TextProperties::TextStyle::UnderlineColor::Color24b&) override { + throw std::runtime_error("fmt error: FunctionNotImpl"); /*ReadManip(buffer).BasicReadType("\033[58;2;", t.r, ';', t.g, ';', t.b, 'm');*/ } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Blink&) override { - return std::unexpected(FMTResult::FunctionNotImpl); + void execute_style(const detail::TextProperties::TextStyle::Blink&) override { + throw std::runtime_error("fmt error: FunctionNotImpl"); /*ReadManip(buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Inverted&) override { - return std::unexpected(FMTResult::FunctionNotImpl); + void execute_style(const detail::TextProperties::TextStyle::Inverted&) override { + throw std::runtime_error("fmt error: FunctionNotImpl"); /*ReadManip(buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Ideogram&) override { - return std::unexpected(FMTResult::FunctionNotImpl); + void execute_style(const detail::TextProperties::TextStyle::Ideogram&) override { + throw std::runtime_error("fmt error: FunctionNotImpl"); /*ReadManip(buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ } - [[nodiscard]] std::expected execute_style(const detail::TextProperties::TextStyle::Script&) override { - return std::unexpected(FMTResult::FunctionNotImpl); + void execute_style(const detail::TextProperties::TextStyle::Script&) override { + throw std::runtime_error("fmt error: FunctionNotImpl"); /*ReadManip(buffer).BasicReadType('\033', '[', static_cast(t), 'm');*/ } }; diff --git a/src/stream/fmt/context/parser_executor/utility_functions.hxx b/src/stream/fmt/context/parser_executor/utility_functions.hxx index f64055e2..87e468cf 100644 --- a/src/stream/fmt/context/parser_executor/utility_functions.hxx +++ b/src/stream/fmt/context/parser_executor/utility_functions.hxx @@ -9,14 +9,14 @@ namespace stream::fmt { template - [[nodiscard]] std::expected parse(Buffer&& buffer_input, Format&& format_input, Args&&... args) { + void parse(Buffer&& buffer_input, Format&& format_input, Args&&... args) { buf::StreamView buffer{buffer_input}; buf::StreamView format{format_input}; using TChar = typename decltype(format)::TChar; detail::ParserNOTextPropertiesExecutor> text_properties_executor; context::BasicParserExecutor> executor(buffer, text_properties_executor); - SF_VERIFY(executor.run(format, std::forward(args)...)); + executor.run(format, std::forward(args)...); return executor.terminate(); } } // namespace stream::fmt diff --git a/src/stream/fmt/detail/fmt_result.hxx b/src/stream/fmt/detail/fmt_result.hxx deleted file mode 100644 index 8b5f0bc1..00000000 --- a/src/stream/fmt/detail/fmt_result.hxx +++ /dev/null @@ -1,44 +0,0 @@ -#pragma once - -#include "stream/core/prelude.hxx" - -namespace stream::fmt { - enum class FMTResult { - FunctionNotImpl, - - Buffer_NonValid, - Buffer_OutOfBoundAccess, - Buffer_UnableToReserveMemory, - Parse_NonValidDigit, - Parse_TokenNotExpected, - - ArgsInterface_Unavaible, - ArgsInterface_InvalidTypeID, - ArgsInterface_InvalidConversion, - ArgsInterface_CantMatchNamedArgs, - ArgsInterface_IndexOutOfBounds, - - Specifiers_Full, - Specifiers_Invalid, - Specifiers_DoesNotExist, - - Context_ParsingFormat, - Context_ArgumentIndexResolution, - Context_ArgumentIndexExpected, - Context_CannotapplyType, - - GivenArgs_UnableToDeduceSize, - - Manager_StaticMemory, - Manager_AllocationFailed, - }; -} // namespace stream::fmt - -namespace stream::detail { - template <> - inline fmt::FMTResult forward_error(fmt::FMTResult t) { - if (t == fmt::FMTResult::ArgsInterface_CantMatchNamedArgs) return t; - if (t == fmt::FMTResult::Manager_StaticMemory) return t; - return t; - } -} // namespace stream::detail diff --git a/src/stream/fmt/detail/indent_handlers.hxx b/src/stream/fmt/detail/indent_handlers.hxx index 217ad045..930d6247 100644 --- a/src/stream/fmt/detail/indent_handlers.hxx +++ b/src/stream/fmt/detail/indent_handlers.hxx @@ -6,10 +6,10 @@ namespace stream::fmt::detail { template struct NoStrideFunction { - inline explicit NoStrideFunction(buf::FMTStreamIO& buffer_) : buffer(buffer_), size_buffer(buf::Access(buffer_).get_buffer_current_size()) {} + inline explicit NoStrideFunction(buf::FMTStreamIO& buffer_) : buffer(buffer_), size_buffer(buffer_.get_buffer_current_size()) {} ~NoStrideFunction() { - buf::FMTManipIO(buffer).add_no_stride(buf::Access(buffer).get_buffer_current_size() - size_buffer); + buf::FMTManipIO(buffer).add_no_stride(buffer.get_buffer_current_size() - size_buffer); } buf::FMTStreamIO& buffer; diff --git a/src/stream/fmt/detail/prelude.hxx b/src/stream/fmt/detail/prelude.hxx index e93c207b..217ac2d9 100644 --- a/src/stream/fmt/detail/prelude.hxx +++ b/src/stream/fmt/detail/prelude.hxx @@ -2,7 +2,6 @@ #include "stream/core/prelude.hxx" #include "types_traits.hxx" -#include "fmt_result.hxx" #define UNKOWN_TYPE_MESSAGE diff --git a/src/stream/fmt/detail/specifiers.hxx b/src/stream/fmt/detail/specifiers.hxx index 82c263c5..5fcd76c1 100644 --- a/src/stream/fmt/detail/specifiers.hxx +++ b/src/stream/fmt/detail/specifiers.hxx @@ -87,10 +87,6 @@ namespace stream::fmt::detail { }; public: - static inline constexpr std::uint8_t NotFound() { - return (std::numeric_limits::max)(); - } - FormatSpecifier* get(std::basic_string_view name, const Constraint& constraint = Constraint{}) { STREAMFORMAT_ASSERT(specifier_count <= SIZE); for (std::uint8_t i = 0; i < specifier_count; ++i) @@ -130,13 +126,12 @@ namespace stream::fmt::detail { } public: - [[nodiscard]] std::expected pushback(const FormatSpecifier& specifier) { - if (specifier_count >= SIZE) return std::unexpected(FMTResult::Specifiers_Full); + void pushback(const FormatSpecifier& specifier) { + if (specifier_count >= SIZE) throw std::runtime_error("fmt error: Specifiers_Full"); specifiers[specifier_count++] = specifier; - return {}; } - [[nodiscard]] std::expected concat(const FormatSpecifier& specifier) { + void concat(const FormatSpecifier& specifier) { FormatSpecifier* local = get(specifier.name); if (local == nullptr) return pushback(specifier); @@ -148,7 +143,6 @@ namespace stream::fmt::detail { local->has_number = true; local->as_number = specifier.as_number; } - return {}; } }; diff --git a/src/stream/fmt/serializers/compilation_data.hxx b/src/stream/fmt/serializers/compilation_data.hxx index 603612e2..4821a283 100644 --- a/src/stream/fmt/serializers/compilation_data.hxx +++ b/src/stream/fmt/serializers/compilation_data.hxx @@ -32,18 +32,18 @@ namespace stream::fmt::detail { namespace stream::fmt { template struct FormatterType { - [[nodiscard]] static inline std::expected format(const detail::FileLocation& t, FormatterExecutor& executor) { - SF_VERIFY(executor.write_type(t.file_name)); - SF_VERIFY(executor.ostream.pushback(':')); + static inline void format(const detail::FileLocation& t, FormatterExecutor& executor) { + executor.write_type(t.file_name); + executor.ostream.pushback(':'); return executor.write_type(t.file_line); } }; template struct FormatterType { - [[nodiscard]] static inline std::expected format(const detail::FunctionProperties& t, FormatterExecutor& executor) { - SF_VERIFY(executor.write_type(t.location)); - SF_VERIFY(executor.ostream.write_char_array(" @ ")); + static inline void format(const detail::FunctionProperties& t, FormatterExecutor& executor) { + executor.write_type(t.location); + executor.ostream.write_char_array(" @ "); return executor.write_type(t.function_name); } }; diff --git a/src/stream/fmt/serializers/format_chrono.hxx b/src/stream/fmt/serializers/format_chrono.hxx index 93c55ef0..095bfa35 100644 --- a/src/stream/fmt/serializers/format_chrono.hxx +++ b/src/stream/fmt/serializers/format_chrono.hxx @@ -17,69 +17,69 @@ namespace stream::fmt::detail { }; template - [[nodiscard]] std::expected write_sub_time_(const std::chrono::time_point& value, buf::StreamView& pattern, - buf::FMTStreamIO& buffer, TimePrintMode mode) { + void write_sub_time_(const std::chrono::time_point& value, buf::StreamView& pattern, buf::FMTStreamIO& buffer, TimePrintMode mode) { ShiftInfo shift; shift.type = detail::ShiftInfo::ShiftType::Right; shift.print = detail::ShiftInfo::ShiftPrint('0', ' '); shift.size = 0; - (void)buf::ReadManip(pattern).fast_read_integer(shift.size); + if (buf::TestAccess(pattern).is_a_digit()) { + buf::ReadManip(pattern).fast_read_integer(shift.size); + } if (mode == TimePrintMode::Mod && shift.size < 0) shift.size = 3; if (buf::TestAccess(pattern).is_same("ns", 2)) { - SF_VERIFY(buf::Manip(pattern).forward(2)); + buf::Manip(pattern).forward(2); std::uint32_t ns = static_cast(std::chrono::time_point_cast(value).time_since_epoch().count()); if (mode == TimePrintMode::Mod) ns = ns % 1000; - SF_VERIFY(buf::FMTWriteManip(buffer).write_integer(static_cast(ns) % 1000, shift)); + buf::FMTWriteManip(buffer).write_integer(static_cast(ns) % 1000, shift); } else if (buf::TestAccess(pattern).is_same("us", 2)) { - SF_VERIFY(buf::Manip(pattern).forward(2)); + buf::Manip(pattern).forward(2); std::uint32_t us = static_cast(std::chrono::time_point_cast(value).time_since_epoch().count()); if (mode == TimePrintMode::Mod) us = us % 1000; else if (mode == TimePrintMode::Sub) us = us / 1000; - SF_VERIFY(buf::FMTWriteManip(buffer).write_integer(static_cast(us) % 1000, shift)); + buf::FMTWriteManip(buffer).write_integer(static_cast(us) % 1000, shift); } else if (buf::TestAccess(pattern).is_same("ms", 2)) { - SF_VERIFY(buf::Manip(pattern).forward(2)); + buf::Manip(pattern).forward(2); std::uint32_t ms = static_cast(std::chrono::time_point_cast(value).time_since_epoch().count()); if (mode == TimePrintMode::Mod) ms = ms % 1000; else if (mode == TimePrintMode::Sub) ms = ms / 1000000; - SF_VERIFY(buf::FMTWriteManip(buffer).write_integer(static_cast(ms) % 1000, shift)); + buf::FMTWriteManip(buffer).write_integer(static_cast(ms) % 1000, shift); } else if (buf::TestAccess(pattern).is_equal_to('s')) { - SF_VERIFY(buf::Manip(pattern).forward()); + buf::Manip(pattern).forward(); std::uint32_t sec = static_cast(std::chrono::time_point_cast(value).time_since_epoch().count()); if (mode == TimePrintMode::Mod) sec = sec % 60; else if (mode == TimePrintMode::Sub) sec = sec / 1000000000; - SF_VERIFY(buf::FMTWriteManip(buffer).write_integer(static_cast(sec) % 1000, shift)); + buf::FMTWriteManip(buffer).write_integer(static_cast(sec) % 1000, shift); } else if (buf::TestAccess(pattern).is_equal_to('m')) { - SF_VERIFY(buf::Manip(pattern).forward()); + buf::Manip(pattern).forward(); std::uint32_t min = static_cast(std::chrono::time_point_cast(value).time_since_epoch().count()); if (mode == TimePrintMode::Mod) min = min % 60; - SF_VERIFY(buf::FMTWriteManip(buffer).write_integer(static_cast(min) % 1000, shift)); + buf::FMTWriteManip(buffer).write_integer(static_cast(min) % 1000, shift); } else if (buf::TestAccess(pattern).is_equal_to('h')) { - SF_VERIFY(buf::Manip(pattern).forward()); - std::uint32_t min = static_cast(std::chrono::time_point_cast(value).time_since_epoch().count()); - if (mode == TimePrintMode::Mod) min = min % 24; - SF_VERIFY(buf::FMTWriteManip(buffer).write_integer(static_cast(min) % 1000, shift)); + buf::Manip(pattern).forward(); + std::uint32_t hours = static_cast(std::chrono::time_point_cast(value).time_since_epoch().count()); + if (mode == TimePrintMode::Mod) hours = hours % 24; + buf::FMTWriteManip(buffer).write_integer(static_cast(hours) % 1000, shift); } - - return {}; } template - [[nodiscard]] std::expected WriteTime(const std::chrono::time_point& value, buf::StreamView pattern, buf::FMTStreamIO& buffer) { - auto view = SF_TRY(buf::TestManip(pattern).ViewExec([&] -> std::expected { - buf::FMTParamsManip(pattern).param_go_to('%', '#', '/'); - return {}; - })); - SF_VERIFY(buf::WriteManip(buffer).fast_write_string(view)); + void write_time(const std::chrono::time_point& value, buf::StreamView pattern, buf::FMTStreamIO& buffer) { + if (buf::TestAccess(pattern).is_same("default", true) == true) { + buf::Manip(pattern).reload("%2h:%2m:%2s:%3ms"); + } - while (!buf::Access(pattern).is_end_of_string()) { + auto view = buf::TestManip(pattern).view_exec([&] -> void { buf::FMTParamsManip(pattern).param_go_to('%', '#', '/'); }); + buf::WriteManip(buffer).fast_write_string(view); + + while (!pattern.is_end_of_string()) { TimePrintMode mode; if (buf::TestAccess(pattern).is_equal_to('%')) mode = TimePrintMode::Mod; @@ -88,52 +88,45 @@ namespace stream::fmt::detail { else if (buf::TestAccess(pattern).is_equal_to('/')) mode = TimePrintMode::Sub; - SF_VERIFY(buf::Manip(pattern).forward()); - SF_VERIFY(write_sub_time_(value, pattern, buffer, mode)); + buf::Manip(pattern).forward(); + write_sub_time_(value, pattern, buffer, mode); - auto view = SF_TRY(buf::TestManip(pattern).ViewExec([&] -> std::expected { - buf::FMTParamsManip(pattern).param_go_to('%', '#', '/'); - return {}; - })); - SF_VERIFY(buf::WriteManip(buffer).fast_write_string(view)); + auto view = buf::TestManip(pattern).view_exec([&] -> void { buf::FMTParamsManip(pattern).param_go_to('%', '#', '/'); }); + buf::WriteManip(buffer).fast_write_string(view); } - - return {}; } } // namespace stream::fmt::detail namespace stream::fmt { template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static inline std::expected format(const std::chrono::time_point& t, FormatterExecutor& executor) { - return detail::WriteTime(t, buf::StreamView(executor.data.specifiers.get_as_text("pattern", "%h:%m:%s.%ms")), executor.ostream); + static inline void format(const std::chrono::time_point& t, FormatterExecutor& executor) { + return detail::write_time(t, buf::StreamView(executor.data.specifiers.get_as_text("pattern", "default")), executor.ostream); } }; template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static inline std::expected format(const std::chrono::duration& t, FormatterExecutor& executor) { + static inline void format(const std::chrono::duration& t, FormatterExecutor& executor) { if (executor.data.specifiers.has("pattern")) { - return detail::WriteTime(std::chrono::time_point>(t), - buf::StreamView(executor.data.specifiers.get_as_text("pattern", "%h:%m:%s.%ms")), executor.ostream); + return detail::write_time(std::chrono::time_point>(t), + buf::StreamView(executor.data.specifiers.get_as_text("pattern", "default")), executor.ostream); } - SF_VERIFY(buf::WriteManip(executor.ostream).fast_write_integer(t.count())); + buf::WriteManip(executor.ostream).fast_write_integer(t.count()); if constexpr (std::is_same_v, std::chrono::seconds>) { - SF_VERIFY(buf::ManipIO(executor.ostream).pushback('s')); + buf::ManipIO(executor.ostream).pushback('s'); } else if constexpr (std::is_same_v, std::chrono::minutes>) { - SF_VERIFY(buf::ManipIO(executor.ostream).pushback('m')); + buf::ManipIO(executor.ostream).pushback('m'); } else if constexpr (std::is_same_v, std::chrono::hours>) { - SF_VERIFY(buf::ManipIO(executor.ostream).pushback('h')); + buf::ManipIO(executor.ostream).pushback('h'); } else if constexpr (std::is_same_v, std::chrono::milliseconds>) { - SF_VERIFY(buf::ManipIO(executor.ostream).pushback('m', 's')); + buf::ManipIO(executor.ostream).pushback('m', 's'); } else if constexpr (std::is_same_v, std::chrono::microseconds>) { - SF_VERIFY(buf::ManipIO(executor.ostream).pushback('u', 's')); + buf::ManipIO(executor.ostream).pushback('u', 's'); } else if constexpr (std::is_same_v, std::chrono::nanoseconds>) { - SF_VERIFY(buf::ManipIO(executor.ostream).pushback('n', 's')); + buf::ManipIO(executor.ostream).pushback('n', 's'); } - - return {}; } }; } // namespace stream::fmt diff --git a/src/stream/fmt/serializers/format_stdlib.hxx b/src/stream/fmt/serializers/format_stdlib.hxx index 484f1b4b..42ec3aa8 100644 --- a/src/stream/fmt/serializers/format_stdlib.hxx +++ b/src/stream/fmt/serializers/format_stdlib.hxx @@ -14,21 +14,21 @@ namespace stream::fmt { template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static inline std::expected format(const std::basic_string& t, FormatterExecutor& executor) { + static inline void format(const std::basic_string& t, FormatterExecutor& executor) { return buf::WriteManip(executor.ostream).fast_write_string(t); } }; template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static inline std::expected format(std::basic_string_view t, FormatterExecutor& executor) { + static inline void format(std::basic_string_view t, FormatterExecutor& executor) { return buf::WriteManip(executor.ostream).fast_write_string(t); } }; template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static inline std::expected format(const std::basic_stringstream& t, FormatterExecutor& executor) { + static inline void format(const std::basic_stringstream& t, FormatterExecutor& executor) { return buf::WriteManip(executor.ostream).fast_write_char_array(t.str(), t.size()); } }; @@ -40,33 +40,29 @@ namespace stream::fmt { // UniquePtr template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static inline std::expected format(const std::unique_ptr& t, FormatterExecutor& executor) { + static inline void format(const std::unique_ptr& t, FormatterExecutor& executor) { if (executor.data.TrueValue) return FormatterType::format(t.get(), executor); else return FormatterType::format(*t, executor); - - return {}; } }; // SharedPtr template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static inline std::expected format(const std::shared_ptr& t, FormatterExecutor& executor) { + static inline void format(const std::shared_ptr& t, FormatterExecutor& executor) { if (executor.data.TrueValue) return FormatterType::format(t.get(), executor); else return FormatterType::format(*t, executor); - - return {}; } }; // WeakPtr template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static inline std::expected format(const std::weak_ptr& t, FormatterExecutor& executor) { + static inline void format(const std::weak_ptr& t, FormatterExecutor& executor) { return FormatterType, FormatterExecutor>::format(t.lock(), executor); } }; diff --git a/src/stream/fmt/serializers/std_container/array.hxx b/src/stream/fmt/serializers/std_container/array.hxx index 28feec7c..40e1b029 100644 --- a/src/stream/fmt/serializers/std_container/array.hxx +++ b/src/stream/fmt/serializers/std_container/array.hxx @@ -8,7 +8,7 @@ namespace stream::fmt { template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static std::expected format(const std::array& t, FormatterExecutor& executor) { + static void format(const std::array& t, FormatterExecutor& executor) { return FormatterType>, FormatterExecutor>::format(t, executor); } }; diff --git a/src/stream/fmt/serializers/std_container/deque.hxx b/src/stream/fmt/serializers/std_container/deque.hxx index cac3d2ec..1381532d 100644 --- a/src/stream/fmt/serializers/std_container/deque.hxx +++ b/src/stream/fmt/serializers/std_container/deque.hxx @@ -8,7 +8,7 @@ namespace stream::fmt { template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static std::expected format(const std::deque& t, FormatterExecutor& executor) { + static void format(const std::deque& t, FormatterExecutor& executor) { return FormatterType>, FormatterExecutor>::format(t, executor); } }; diff --git a/src/stream/fmt/serializers/std_container/forward_list.hxx b/src/stream/fmt/serializers/std_container/forward_list.hxx index 44b4e0e3..1ff27b4a 100644 --- a/src/stream/fmt/serializers/std_container/forward_list.hxx +++ b/src/stream/fmt/serializers/std_container/forward_list.hxx @@ -8,7 +8,7 @@ namespace stream::fmt { template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static std::expected format(const std::forward_list& t, FormatterExecutor& executor) { + static void format(const std::forward_list& t, FormatterExecutor& executor) { return FormatterType>, FormatterExecutor>::format(t, executor); } }; diff --git a/src/stream/fmt/serializers/std_container/list.hxx b/src/stream/fmt/serializers/std_container/list.hxx index e1d8526f..152a433e 100644 --- a/src/stream/fmt/serializers/std_container/list.hxx +++ b/src/stream/fmt/serializers/std_container/list.hxx @@ -8,7 +8,7 @@ namespace stream::fmt { template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static std::expected format(const std::list& t, FormatterExecutor& executor) { + static void format(const std::list& t, FormatterExecutor& executor) { return FormatterType>, FormatterExecutor>::format(t, executor); } }; diff --git a/src/stream/fmt/serializers/std_container/map.hxx b/src/stream/fmt/serializers/std_container/map.hxx index bf3d3eaf..d931aa6d 100644 --- a/src/stream/fmt/serializers/std_container/map.hxx +++ b/src/stream/fmt/serializers/std_container/map.hxx @@ -9,14 +9,14 @@ namespace stream::fmt { template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static std::expected format(const std::map& t, FormatterExecutor& executor) { + static void format(const std::map& t, FormatterExecutor& executor) { return FormatterType>, FormatterExecutor>::format(t, executor); } }; template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static std::expected format(const std::multimap& t, FormatterExecutor& executor) { + static void format(const std::multimap& t, FormatterExecutor& executor) { return FormatterType>, FormatterExecutor>::format(t, executor); } }; diff --git a/src/stream/fmt/serializers/std_container/queue.hxx b/src/stream/fmt/serializers/std_container/queue.hxx index 1e430001..43004603 100644 --- a/src/stream/fmt/serializers/std_container/queue.hxx +++ b/src/stream/fmt/serializers/std_container/queue.hxx @@ -6,8 +6,8 @@ namespace stream::fmt { template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static std::expected format(const std::queue& t, FormatterExecutor& executor) { - return std::unexpected(FMTResult::FunctionNotImpl); + static void format(const std::queue& t, FormatterExecutor& executor) { + throw std::runtime_error("fmt error: FunctionNotImpl"); } }; } // namespace stream::fmt diff --git a/src/stream/fmt/serializers/std_container/set.hxx b/src/stream/fmt/serializers/std_container/set.hxx index 49fc6ab6..d26b7e1d 100644 --- a/src/stream/fmt/serializers/std_container/set.hxx +++ b/src/stream/fmt/serializers/std_container/set.hxx @@ -8,14 +8,14 @@ namespace stream::fmt { template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static std::expected format(const std::set& t, FormatterExecutor& executor) { + static void format(const std::set& t, FormatterExecutor& executor) { return FormatterType>, FormatterExecutor>::format(t, executor); } }; template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static std::expected format(const std::multiset& t, FormatterExecutor& executor) { + static void format(const std::multiset& t, FormatterExecutor& executor) { return FormatterType>, FormatterExecutor>::format(t, executor); } }; diff --git a/src/stream/fmt/serializers/std_container/stack.hxx b/src/stream/fmt/serializers/std_container/stack.hxx index 8e030508..920ce5c3 100644 --- a/src/stream/fmt/serializers/std_container/stack.hxx +++ b/src/stream/fmt/serializers/std_container/stack.hxx @@ -8,7 +8,7 @@ namespace stream::fmt { template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static inline std::expected format(const std::stack& t, FormatterExecutor& executor) { + static inline void format(const std::stack& t, FormatterExecutor& executor) { } }; */ diff --git a/src/stream/fmt/serializers/std_container/tuple.hxx b/src/stream/fmt/serializers/std_container/tuple.hxx index 7a7b0758..00dcf8f9 100644 --- a/src/stream/fmt/serializers/std_container/tuple.hxx +++ b/src/stream/fmt/serializers/std_container/tuple.hxx @@ -15,20 +15,18 @@ namespace stream::fmt::tuple_detail { } template - [[nodiscard]] static inline std::expected tuple_format_rec(FormatterExecutor& executor) { - return {}; - } + static inline void tuple_format_rec(FormatterExecutor& executor) {} template - [[nodiscard]] static inline std::expected tuple_format_rec(FormatterExecutor& executor, const T& t) { + static inline void tuple_format_rec(FormatterExecutor& executor, const T& t) { return executor.write_type(t); } template - [[nodiscard]] static inline std::expected tuple_format_rec(FormatterExecutor& executor, const T& t, Args&&... args) { - SF_VERIFY(executor.write_type(t)); - SF_VERIFY(executor.ostream.pushback(',')); - SF_VERIFY(executor.ostream.pushback(' ')); + static inline void tuple_format_rec(FormatterExecutor& executor, const T& t, Args&&... args) { + executor.write_type(t); + executor.ostream.pushback(','); + executor.ostream.pushback(' '); return tuple_format_rec(executor, args...); } } // namespace stream::fmt::tuple_detail @@ -36,29 +34,27 @@ namespace stream::fmt::tuple_detail { namespace stream::fmt { template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static std::expected format(const std::tuple& t, FormatterExecutor& executor) { - SF_VERIFY(executor.ostream.pushback('<')); - std::expected err = {}; + static void format(const std::tuple& t, FormatterExecutor& executor) { + executor.ostream.pushback('<'); + void err = {}; std::apply([&context_executor, &err](auto&&... args) { auto&& res = tuple_detail::tuple_format_rec(context_executor, args...); if (not res) { err = res.error(); } }, t); - SF_VERIFY(executor.ostream.pushback('>')); + executor.ostream.pushback('>'); } }; template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static std::expected format(const std::pair& t, FormatterExecutor& executor) { - SF_VERIFY(executor.ostream.pushback('<')); - SF_VERIFY(executor.write_type(t.first)); - SF_VERIFY(executor.ostream.pushback(':')); - SF_VERIFY(executor.write_type(t.second)); - SF_VERIFY(executor.ostream.pushback('>')); - - return {}; + static void format(const std::pair& t, FormatterExecutor& executor) { + executor.ostream.pushback('<'); + executor.write_type(t.first); + executor.ostream.pushback(':'); + executor.write_type(t.second); + executor.ostream.pushback('>'); } }; } // namespace stream::fmt diff --git a/src/stream/fmt/serializers/std_container/unordered_map.hxx b/src/stream/fmt/serializers/std_container/unordered_map.hxx index 9f94d5e0..307e607c 100644 --- a/src/stream/fmt/serializers/std_container/unordered_map.hxx +++ b/src/stream/fmt/serializers/std_container/unordered_map.hxx @@ -9,14 +9,14 @@ namespace stream::fmt { template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static std::expected format(const std::unordered_map& t, FormatterExecutor& executor) { + static void format(const std::unordered_map& t, FormatterExecutor& executor) { return FormatterType>, FormatterExecutor>::format(t, executor); } }; template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static std::expected format(const std::unordered_multimap& t, FormatterExecutor& executor) { + static void format(const std::unordered_multimap& t, FormatterExecutor& executor) { return FormatterType>, FormatterExecutor>::format(t, executor); } }; diff --git a/src/stream/fmt/serializers/std_container/unordered_set.hxx b/src/stream/fmt/serializers/std_container/unordered_set.hxx index e1d2024f..6f0c824b 100644 --- a/src/stream/fmt/serializers/std_container/unordered_set.hxx +++ b/src/stream/fmt/serializers/std_container/unordered_set.hxx @@ -8,14 +8,14 @@ namespace stream::fmt { template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static std::expected format(const std::unordered_set& t, FormatterExecutor& executor) { + static void format(const std::unordered_set& t, FormatterExecutor& executor) { return FormatterType>, FormatterExecutor>::format(t, executor); } }; template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static std::expected format(const std::unordered_multiset& t, FormatterExecutor& executor) { + static void format(const std::unordered_multiset& t, FormatterExecutor& executor) { return FormatterType>, FormatterExecutor>::format(t, executor); } }; diff --git a/src/stream/fmt/serializers/std_container/vector.hxx b/src/stream/fmt/serializers/std_container/vector.hxx index 92759bdf..ba3faade 100644 --- a/src/stream/fmt/serializers/std_container/vector.hxx +++ b/src/stream/fmt/serializers/std_container/vector.hxx @@ -8,7 +8,7 @@ namespace stream::fmt { template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static std::expected format(const std::vector& t, FormatterExecutor& executor) { + static void format(const std::vector& t, FormatterExecutor& executor) { return FormatterType>, FormatterExecutor>::format(t, executor); } }; diff --git a/src/stream/fmt/text_properties/text_properties_color.hxx b/src/stream/fmt/text_properties/text_properties_color.hxx index 08e6e46e..c5867c43 100644 --- a/src/stream/fmt/text_properties/text_properties_color.hxx +++ b/src/stream/fmt/text_properties/text_properties_color.hxx @@ -51,8 +51,8 @@ namespace stream::fmt::detail { Default = 39, - BaseStep = Black, - BaseBStep = BrightBlack + BaseStep = Black, + BaseBrightStep = BrightBlack }; enum class TextProperties::TextColor::BasicColorBG : std::uint8_t { @@ -76,8 +76,8 @@ namespace stream::fmt::detail { Default = 49, - BaseStep = Black, - BaseBStep = BrightBlack, + BaseStep = Black, + BaseBrightStep = BrightBlack, }; struct TextProperties::TextColor::BasicColor { @@ -117,9 +117,9 @@ namespace stream::fmt::detail { static inline constexpr std::uint8_t MinGrayscale = 232; // grayscale from black to white in 24 step static inline constexpr std::uint8_t MaxGrayscale = 255; - static inline constexpr std::uint8_t BaseStep = MinNormalColor; - static inline constexpr std::uint8_t BaseBStep = MinBrightColor; - static inline constexpr std::uint8_t Default = 0; + static inline constexpr std::uint8_t BaseStep = MinNormalColor; + static inline constexpr std::uint8_t BaseBrightStep = MinBrightColor; + static inline constexpr std::uint8_t Default = 0; public: enum class type : std::uint8_t { @@ -148,7 +148,7 @@ namespace stream::fmt::detail { constexpr BaseColorCube() : color(0) {} - type GetType() { + type get_type() { if (color >= MinNormalColor && color <= MaxNormalColor) return type::Normal; else if (color >= MinBrightColor && color <= MaxBrightColor) diff --git a/src/stream/json/detail.hxx b/src/stream/json/detail.hxx index ce40ebeb..832d3652 100644 --- a/src/stream/json/detail.hxx +++ b/src/stream/json/detail.hxx @@ -8,35 +8,31 @@ namespace stream::json::detail { class JsonError : public std::exception { public: - JsonError(std::string&& msg) : m_What(std::move(msg)) {} - JsonError(const std::string_view msg) : m_What(msg) {} + JsonError(std::string&& msg) : what_(std::move(msg)) {} + JsonError(const std::string_view msg) : what_(msg) {} const char* what() const noexcept override { - return m_What.c_str(); + return what_.c_str(); } protected: - std::string m_What; + std::string what_; }; class JsonIndexingError : public JsonError { public: - JsonIndexingError(std::string&& msg = "") : JsonError(std::string("JsonIndexingError") + std::move(msg)) {} - JsonIndexingError(const std::string& msg) : JsonError(std::string("JsonIndexingError") + msg) {} + JsonIndexingError(std::string msg = "") : JsonError(std::string("JsonIndexingError") + std::move(msg)) {} }; class JsonTypeSerializerNotImpl : public JsonError { public: - JsonTypeSerializerNotImpl(std::string&& msg = "") : JsonError(std::string("JsonTypeSerializerNotImpl") + std::move(msg)) {} - JsonTypeSerializerNotImpl(const std::string& msg) : JsonError(std::string("JsonTypeSerializerNotImpl") + msg) {} + JsonTypeSerializerNotImpl(std::string msg = "") : JsonError(std::string("JsonTypeSerializerNotImpl") + std::move(msg)) {} }; class JsonGivenTypeError : public JsonError { public: - JsonGivenTypeError(std::string&& msg = "") : JsonError(std::string("JsonGivenTypeError") + std::move(msg)) {} - JsonGivenTypeError(const std::string& msg) : JsonError(std::string("JsonGivenTypeError") + msg) {} + JsonGivenTypeError(std::string msg = "") : JsonError(std::string("JsonGivenTypeError") + std::move(msg)) {} }; class JsonCastError : public JsonError { public: - JsonCastError(std::string&& msg = "") : JsonError(std::string("JsonCastError") + std::move(msg)) {} - JsonCastError(const std::string& msg) : JsonError(std::string("JsonCastError") + msg) {} + JsonCastError(std::string msg = "") : JsonError(std::string("JsonCastError") + std::move(msg)) {} }; } // namespace stream::json::detail diff --git a/src/stream/json/json_factory.hxx b/src/stream/json/json_factory.hxx index 70e849f5..fcc756c7 100644 --- a/src/stream/json/json_factory.hxx +++ b/src/stream/json/json_factory.hxx @@ -25,7 +25,7 @@ namespace stream::json { namespace stream::fmt { template struct FormatterType { - [[nodiscard]] static std::expected format(const json::JsonObject& object, FormatterExecutor& executor) { + static void format(const json::JsonObject& object, FormatterExecutor& executor) { return executor.write_type(json::FormatAsJson(object)); } }; @@ -65,7 +65,7 @@ namespace stream::json { if (file.is_open() == false) throw std::runtime_error("unable to open file"); fmt::buf::DynamicStreamIOManager StreamIOManager(256); - fmt::buf::StreamIO ostream = fmt::buf::StreamIO::create(StreamIOManager).value(); + fmt::buf::StreamIO ostream = fmt::buf::StreamIO::create(StreamIOManager); detail::JsonFormatter formatter(ostream, settings); JsonSerializer::format(json, formatter); diff --git a/src/stream/json/json_formatter.hxx b/src/stream/json/json_formatter.hxx index dff2fba3..a32dac9d 100644 --- a/src/stream/json/json_formatter.hxx +++ b/src/stream/json/json_formatter.hxx @@ -33,14 +33,14 @@ namespace stream::json::detail { if (settings.one_line) return; if (settings.indent_with_spaces) - fmt::buf::ManipIO(ostream).pushback(' ', indent_ * settings.indent_size).value(); + fmt::buf::ManipIO(ostream).pushback(' ', indent_ * settings.indent_size); else - fmt::buf::ManipIO(ostream).pushback('\t', indent_ * settings.indent_size).value(); + fmt::buf::ManipIO(ostream).pushback('\t', indent_ * settings.indent_size); } void NewLine() { if (settings.one_line) return; - fmt::buf::ManipIO(ostream).pushback('\n').value(); + fmt::buf::ManipIO(ostream).pushback('\n'); indent(); } void begin_new_object() { diff --git a/src/stream/json/json_objects.hxx b/src/stream/json/json_objects.hxx index 7a921cc4..9cfe7c16 100644 --- a/src/stream/json/json_objects.hxx +++ b/src/stream/json/json_objects.hxx @@ -29,16 +29,16 @@ namespace stream::json { public: JsonObject() {} - JsonObject(ObjectType type) : m_Type(type) {} + JsonObject(ObjectType type) : type_(type) {} virtual ~JsonObject() = default; private: - ObjectType m_Type = ObjectType::Undefined; + ObjectType type_ = ObjectType::Undefined; public: - ObjectType GetType() { - return m_Type; + ObjectType get_type() { + return type_; } JsonObject& operator[](const std::size_t index) { @@ -58,34 +58,33 @@ namespace stream::json { public: template requires std::is_base_of_v - T& As() { + T& as() { T* t = dynamic_cast(this); if (t == nullptr) throw detail::JsonCastError{}; return *t; } - template requires std::is_base_of_v - const T& As() const { + const T& as() const { const T* t = dynamic_cast(this); if (t == nullptr) throw detail::JsonCastError{}; return *t; } template - T Read() { + T read() { T value; - JsonObjectSerializer::ReadObject(value, *this); + JsonObjectSerializer::read_object(value, *this); return value; } template - void Write(const T& t) { - JsonObjectSerializer::WriteObject(t, *this); + void write(const T& t) { + JsonObjectSerializer::write_object(t, *this); } - std::string ToString() { - return fmt::format_string(*this).value(); + std::string to_string() { + return fmt::format_string(*this); } public: diff --git a/src/stream/json/json_parser.cxx b/src/stream/json/json_parser.cxx index a38c8d9d..3a6fd8bb 100644 --- a/src/stream/json/json_parser.cxx +++ b/src/stream/json/json_parser.cxx @@ -15,12 +15,12 @@ namespace stream::json::detail { const char* const begin = parser.istream.current_pos; if (parser.is_json_string_begin()) { - manip.skip_one_of('"').value(); + manip.skip_one_of('"'); while (true) { manip.GoTo('"'); if (fmt::buf::Access(parser.istream).get_prev_force() != '\\') break; } - manip.skip_one_of('"').value(); + manip.skip_one_of('"'); } else if (parser.is_json_number_begin()) { float k; JsonNumberSerializer::ParseFloat(k, parser); diff --git a/src/stream/json/json_serializer.hxx b/src/stream/json/json_serializer.hxx index 92ea4a04..fce41e74 100644 --- a/src/stream/json/json_serializer.hxx +++ b/src/stream/json/json_serializer.hxx @@ -16,7 +16,7 @@ namespace stream::json { struct JsonSerializer { static inline void parse(T&, detail::JsonParser&) { #ifdef UNKOWN_TYPE_MESSAGE - fmt::file_print(std::cerr, "{C:red}JsonSerializer::Parse<{}> not impl", typeid(T).name()).value(); + fmt::file_print(std::cerr, "{C:red}JsonSerializer::Parse<{}> not impl", typeid(T).name()); #endif #ifdef UNKOWN_TYPE_THROW throw detail::JsonTypeSerializerNotImpl{}; @@ -31,11 +31,11 @@ namespace stream::json { } static inline void format(const T&, detail::JsonFormatter& formatter) { - fmt::buf::WriteManip(formatter.ostream).fast_write_string(std::string_view("Unknown JsonFormatter for type : ")).value(); - fmt::buf::WriteManip(formatter.ostream).fast_write_string(std::string_view(typeid(T).name())).value(); + fmt::buf::WriteManip(formatter.ostream).fast_write_string(std::string_view("Unknown JsonFormatter for type : ")); + fmt::buf::WriteManip(formatter.ostream).fast_write_string(std::string_view(typeid(T).name())); #ifdef UNKOWN_TYPE_MESSAGE - fmt::file_print(std::cerr, "{C:red}JsonSerializer::Format<{}> not impl", typeid(T).name()).value(); + fmt::file_print(std::cerr, "{C:red}JsonSerializer::Format<{}> not impl", typeid(T).name()); #endif #ifdef UNKOWN_TYPE_THROW throw detail::JsonTypeSerializerNotImpl{}; @@ -52,9 +52,9 @@ namespace stream::json { template struct JsonObjectSerializer { - static inline void ReadObject(T&, const JsonObject&) { + static inline void read_object(T&, const JsonObject&) { #ifdef UNKOWN_TYPE_MESSAGE - fmt::file_print(std::cerr, "{C:red}JsonObjectSerializer::ReadObject<{}> not impl", typeid(T).name()).value(); + fmt::file_print(std::cerr, "{C:red}JsonObjectSerializer::read_object<{}> not impl", typeid(T).name()); #endif #ifdef UNKOWN_TYPE_THROW throw detail::JsonTypeSerializerNotImpl{}; @@ -68,9 +68,9 @@ namespace stream::json { #endif } - static inline void WriteObject(const T&, JsonObject&) { + static inline void write_object(const T&, JsonObject&) { #ifdef UNKOWN_TYPE_MESSAGE - fmt::file_print(std::cerr, "{C:red}JsonObjectSerializer::WriteObject<{}> not impl", typeid(T).name()).value(); + fmt::file_print(std::cerr, "{C:red}JsonObjectSerializer::write_object<{}> not impl", typeid(T).name()); #endif #ifdef UNKOWN_TYPE_THROW throw detail::JsonTypeSerializerNotImpl{}; @@ -88,60 +88,60 @@ namespace stream::json { struct JsonStringSerializer { static inline void ParseSTDString(std::string& t, detail::JsonParser& parser) { fmt::buf::DynamicStreamIOManager bufferData; - fmt::buf::StreamIO buffer = fmt::buf::StreamIO::create(bufferData).value(); - fmt::buf::utils::parse_escaped_quoted_string(parser.istream, buffer).value(); + fmt::buf::StreamIO buffer = fmt::buf::StreamIO::create(bufferData); + fmt::buf::utils::parse_escaped_quoted_string(parser.istream, buffer); fmt::buf::ManipIO(buffer).compute_generated_size(); t = bufferData.get_last_generated_string_view(); } static inline void FormatSTDString(const std::string_view t, detail::JsonFormatter& formatter) { fmt::buf::Stream buffer(t.data(), t.size()); - fmt::buf::utils::format_escaped_quoted_string(formatter.ostream, buffer).value(); + fmt::buf::utils::format_escaped_quoted_string(formatter.ostream, buffer); } }; struct JsonNumberSerializer { template static inline void ParseFloat(FloatType& t, detail::JsonParser& parser) { - fmt::buf::ReadManip(parser.istream).fast_read_float(t).value(); + fmt::buf::ReadManip(parser.istream).fast_read_float(t); } template static inline void ParseInteger(IntType& t, detail::JsonParser& parser) { const char* begin = parser.istream.current_pos; float tmp = 0; - fmt::buf::ReadManip(parser.istream).fast_read_float(tmp).value(); + fmt::buf::ReadManip(parser.istream).fast_read_float(tmp); const char* end = parser.istream.current_pos; parser.istream.current_pos = begin; - fmt::buf::ReadManip(parser.istream).fast_read_integer(t).value(); + fmt::buf::ReadManip(parser.istream).fast_read_integer(t); parser.istream.current_pos = end; } template static inline void FormatFloat(const FloatType& t, detail::JsonFormatter& formatter) { - fmt::buf::WriteManip(formatter.ostream).fast_write_float(t, formatter.settings.float_precision).value(); + fmt::buf::WriteManip(formatter.ostream).fast_write_float(t, formatter.settings.float_precision); } template static inline void FormatInteger(const IntType& t, detail::JsonFormatter& formatter) { - fmt::buf::WriteManip(formatter.ostream).fast_write_integer(t).value(); + fmt::buf::WriteManip(formatter.ostream).fast_write_integer(t); } }; struct JsonBooleanSerializer { static inline void ParseBool(bool& t, detail::JsonParser& parser) { - if (fmt::buf::TestManip(parser.istream).is_same_forward("true", 5).value()) + if (fmt::buf::TestManip(parser.istream).is_same_forward("true", 5)) t = true; - else if (fmt::buf::TestManip(parser.istream).is_same_forward("false", 5).value()) + else if (fmt::buf::TestManip(parser.istream).is_same_forward("false", 5)) t = false; } static inline void FormatBool(const bool& t, detail::JsonFormatter& formatter) { if (t) - fmt::buf::WriteManip(formatter.ostream).fast_write_char_array("true", 5).value(); + fmt::buf::WriteManip(formatter.ostream).fast_write_char_array("true", 5); else - fmt::buf::WriteManip(formatter.ostream).fast_write_char_array("false", 5).value(); + fmt::buf::WriteManip(formatter.ostream).fast_write_char_array("false", 5); } }; @@ -151,10 +151,10 @@ namespace stream::json { fmt::buf::TestAccess access(parser.istream); fmt::buf::TestManip manip(parser.istream); - manip.skip_one_of('{').value(); + manip.skip_one_of('{'); std::size_t idx = 0; - while (fmt::buf::Access(parser.istream).is_end_of_string() == false) { + while (parser.istream.is_end_of_string() == false) { manip.GoTo('"', '}'); if (access.is_equal_to('}')) break; @@ -162,16 +162,16 @@ namespace stream::json { JsonStringSerializer::ParseSTDString(name, parser); manip.IgnoreEveryBlanks(); - manip.skip_one_of(':').value(); + manip.skip_one_of(':'); manip.IgnoreEveryBlanks(); subObjectParsingFunction(t, idx++, std::move(name), parser); manip.GoTo(',', '}'); - manip.skip_one_of(',').value(); + manip.skip_one_of(','); } - manip.skip_one_of('}').value(); + manip.skip_one_of('}'); } template @@ -184,23 +184,23 @@ namespace stream::json { } static inline void FormatBegin(detail::JsonFormatter& formatter) { - fmt::buf::ManipIO(formatter.ostream).pushback('{').value(); + fmt::buf::ManipIO(formatter.ostream).pushback('{'); } static inline void FormatEnd(detail::JsonFormatter& formatter) { formatter.NewLine(); - fmt::buf::ManipIO(formatter.ostream).pushback('}').value(); + fmt::buf::ManipIO(formatter.ostream).pushback('}'); } template static inline void FormatObject(const std::string_view name, const SubObject& subObject, const std::size_t idx, detail::JsonFormatter& formatter) { - if (idx != 0) fmt::buf::ManipIO(formatter.ostream).pushback(',').value(); + if (idx != 0) fmt::buf::ManipIO(formatter.ostream).pushback(','); formatter.begin_new_object(); formatter.NewLine(); JsonStringSerializer::FormatSTDString(name, formatter); - fmt::buf::ManipIO(formatter.ostream).pushback(':').value(); - fmt::buf::ManipIO(formatter.ostream).pushback(' ').value(); + fmt::buf::ManipIO(formatter.ostream).pushback(':'); + fmt::buf::ManipIO(formatter.ostream).pushback(' '); formatter.format(subObject); formatter.end_new_object(); } @@ -212,10 +212,10 @@ namespace stream::json { fmt::buf::TestAccess access(parser.istream); fmt::buf::TestManip manip(parser.istream); - manip.skip_one_of('[').value(); + manip.skip_one_of('['); std::size_t idx = 0; - while (fmt::buf::Access(parser.istream).is_end_of_string() == false) { + while (parser.istream.is_end_of_string() == false) { manip.IgnoreEveryBlanks(); if (access.is_equal_to(']')) break; @@ -223,10 +223,10 @@ namespace stream::json { subObjectParsingFunction(t, idx++, parser); manip.GoTo(',', ']'); - manip.skip_one_of(',').value(); + manip.skip_one_of(','); } - manip.skip_one_of(']').value(); + manip.skip_one_of(']'); } template @@ -239,17 +239,17 @@ namespace stream::json { } static inline void FormatBegin(detail::JsonFormatter& formatter) { - fmt::buf::ManipIO(formatter.ostream).pushback('[').value(); + fmt::buf::ManipIO(formatter.ostream).pushback('['); } static inline void FormatEnd(detail::JsonFormatter& formatter) { formatter.NewLine(); - fmt::buf::ManipIO(formatter.ostream).pushback(']').value(); + fmt::buf::ManipIO(formatter.ostream).pushback(']'); } template static inline void FormatObject(const SubObject& subObject, const std::size_t idx, detail::JsonFormatter& formatter) { - if (idx != 0) fmt::buf::ManipIO(formatter.ostream).pushback(',').value(); + if (idx != 0) fmt::buf::ManipIO(formatter.ostream).pushback(','); formatter.begin_new_object(); formatter.NewLine(); @@ -260,11 +260,11 @@ namespace stream::json { struct JsonNullSerializer { static inline void ParseNull(detail::JsonParser& parser) { - fmt::buf::TestManip(parser.istream).is_same_forward("null", 4).value(); + fmt::buf::TestManip(parser.istream).is_same_forward("null", 4); } static inline void FormatNull(detail::JsonFormatter& formatter) { - fmt::buf::WriteManip(formatter.ostream).fast_write_char_array("null", 4).value(); + fmt::buf::WriteManip(formatter.ostream).fast_write_char_array("null", 4); } }; } // namespace stream::json @@ -297,12 +297,11 @@ namespace stream::fmt { #ifdef STREAMFORMAT_FORMATTER_DECLARED template struct FormatterType, FormatterExecutor> { - [[nodiscard]] static std::expected format(const json::FormatAsJson& json, FormatterExecutor& executor) { + static void format(const json::FormatAsJson& json, FormatterExecutor& executor) { bool ordered_struct = executor.data.specifiers.has("ordered_struct"); json::detail::JsonFormatter::FormatSettings settings{.ordered_struct = ordered_struct, .float_precision = executor.data.float_precision}; json::detail::JsonFormatter jsonFormatter(executor.ostream, settings); json::JsonSerializer::format(json.value, jsonFormatter); - return {}; } }; #endif @@ -310,13 +309,12 @@ namespace stream::fmt { #ifdef STREAMFORMAT_PARSER_DECLARED template struct ParserType, ParserExecutor> { - [[nodiscard]] static std::expected parse(T& json, ParserExecutor& executor) { - json::detail::JsonParser json_parser(*executor.istream.Manager); + static void parse(T& json, ParserExecutor& executor) { + json::detail::JsonParser json_parser(*executor.istream.manager); json_parser.istream.current_pos = executor.istream.current_pos; // TODO: // json::JsonSerializer::parse(json.value, json_parser); executor.istream.current_pos = json_parser.istream.current_pos; - return {}; } }; #endif diff --git a/src/stream/profiler/event.hxx b/src/stream/profiler/event.hxx index d52de44c..f789471d 100644 --- a/src/stream/profiler/event.hxx +++ b/src/stream/profiler/event.hxx @@ -116,7 +116,7 @@ namespace stream::profiler { namespace stream::fmt { template struct FormatterType { - [[nodiscard]] static std::expected format(const stream::profiler::EventType& t, FormatterExecutor& executor) { + static void format(const stream::profiler::EventType& t, FormatterExecutor& executor) { return executor.ostream.pushback(static_cast(t)); } }; diff --git a/src/stream/profiler/profiler_factory.cxx b/src/stream/profiler/profiler_factory.cxx index a1ae82df..7d4964a5 100644 --- a/src/stream/profiler/profiler_factory.cxx +++ b/src/stream/profiler/profiler_factory.cxx @@ -12,7 +12,7 @@ namespace stream::profiler { std::ofstream file(path.string(), std::ios::out); json::FormatAsJson const format_profiler(profiler); - fmt::file_print(file, format_profiler).value(); + fmt::file_print(file, format_profiler); file.close(); } } // namespace stream::profiler diff --git a/src/stream/tester/test_suite/basic_test.hxx b/src/stream/tester/test_suite/basic_test.hxx index 2bb60025..7aeb5020 100644 --- a/src/stream/tester/test_suite/basic_test.hxx +++ b/src/stream/tester/test_suite/basic_test.hxx @@ -29,13 +29,6 @@ namespace stream::tester::detail { template void test_not_eq(T result, std::convertible_to auto notExpected, std::string_view testView, int line); - template - void test_eq(std::expected result, std::convertible_to auto expected, std::string_view testView, int line); - template - void test_not_eq(std::expected result, std::convertible_to auto notExpected, std::string_view testView, int line); - - template - void assert_expected(std::expected result, std::string_view testView, int line); template void assert_optional(std::optional result, std::string_view testView, int line); @@ -47,55 +40,31 @@ namespace stream::tester::detail { void TestFunction::test_eq(T result, std::convertible_to auto expected, std::string_view testView, [[maybe_unused]] int line) { T expected_as_T = static_cast(expected); if (result != expected_as_T) { - link.test_logger.error("{C:red}{} return {} instead of {}", testView, result, expected, FORMAT_SV("test_name", name)).value(); + link.test_logger.error("{C:red}{} return {} instead of {}", testView, result, expected, FORMAT_SV("test_name", name)); throw TestFailure{}; } - link.test_logger.trace("{C:green}{} return {}", testView, result, FORMAT_SV("test_name", name)).value(); + link.test_logger.trace("{C:green}{} return {}", testView, result, FORMAT_SV("test_name", name)); } template void TestFunction::test_not_eq(T result, std::convertible_to auto notExpected, std::string_view testView, [[maybe_unused]] int line) { if (result == static_cast(notExpected)) { - link.test_logger.error("{C:red}{} return {} but that result was prohibited", testView, result, FORMAT_SV("test_name", name)).value(); + link.test_logger.error("{C:red}{} return {} but that result was prohibited", testView, result, FORMAT_SV("test_name", name)); throw TestFailure{}; } - link.test_logger.trace("{C:green}{} return {}", testView, result, FORMAT_SV("test_name", name)).value(); + link.test_logger.trace("{C:green}{} return {}", testView, result, FORMAT_SV("test_name", name)); } inline void TestFunction::test_assert(bool assert, std::string_view assertView, [[maybe_unused]] int line) { if (assert == false) { - link.test_logger.error("{C:red}ASSERT FAILED : {}", assertView, FORMAT_SV("test_name", name)).value(); + link.test_logger.error("{C:red}ASSERT FAILED : {}", assertView, FORMAT_SV("test_name", name)); throw TestFailure{}; } - link.test_logger.trace("{C:green}ASSERT SUCCED : {}", assertView, FORMAT_SV("test_name", name)).value(); - } - - - template - void TestFunction::test_eq(std::expected result, std::convertible_to auto expected, std::string_view testView, [[maybe_unused]] int line) { - if (result.has_value()) - test_eq(result.value(), expected, testView, line); - else - assert_expected(result, testView, line); - } - template - void TestFunction::test_not_eq(std::expected result, std::convertible_to auto notExpected, std::string_view testView, [[maybe_unused]] int line) { - if (result.has_value()) - test_eq(result.value(), notExpected, testView, line); - else - assert_expected(result, testView, line); + link.test_logger.trace("{C:green}ASSERT SUCCED : {}", assertView, FORMAT_SV("test_name", name)); } - - template - void TestFunction::assert_expected(std::expected result, std::string_view testView, int line) { - if (result.has_value() == false) { - link.test_logger.error("{C:red}{} return an error: {}", testView, result.error(), FORMAT_SV("test_name", name)).value(); - throw TestFailure{}; - } - } template void TestFunction::assert_optional(std::optional result, std::string_view testView, int line) { if (result.has_value() == false) { - link.test_logger.error("{C:red}{} didn't return any value", testView, FORMAT_SV("test_name", name)).value(); + link.test_logger.error("{C:red}{} didn't return any value", testView, FORMAT_SV("test_name", name)); throw TestFailure{}; } } @@ -115,5 +84,3 @@ namespace stream::tester::detail { #define SFT_ASSERT(Test) link.test_assert(Test, #Test, __LINE__) #define SFT_EQ(Test, Expected) link.test_eq(Test, Expected, #Test, __LINE__) #define SFT_NEQ(Test, NotExpected) link.test_not_eq(Test, NotExpected, #Test, __LINE__) - -#define SFT_EXPECTED_VALUE(Test) link.assert_expected(Test, #Test, __LINE__) diff --git a/src/stream/tester/test_suite/test_suite.cxx b/src/stream/tester/test_suite/test_suite.cxx index 3d38fb6d..cabd8070 100644 --- a/src/stream/tester/test_suite/test_suite.cxx +++ b/src/stream/tester/test_suite/test_suite.cxx @@ -96,19 +96,19 @@ namespace stream::tester::detail { } std::string time_pattern; - if (TestSuitesManager::print_time) time_pattern = "[{T:pattern='%h:%m:%s:%ms'}] "; + if (TestSuitesManager::print_time) time_pattern = "[{logtime:pattern='default'}] "; if (parent == nullptr) { logger.set_name(name); - logger.SetRealPattern("{C:+black}" + time_pattern + "{name} >> {color}{data}"); + logger.set_real_pattern("{C:+black}" + time_pattern + "{name} >> {color}{data}"); test_logger.set_name(name + ".{test_name}"); - test_logger.SetRealPattern("{C:+black}" + time_pattern + "{name} >> {color}{data}"); + test_logger.set_real_pattern("{C:+black}" + time_pattern + "{name} >> {color}{data}"); } else { std::string const corrected_name = get_corrected_size_name(); logger.set_name(corrected_name); - logger.set_real_pattern_strmv("{C:+black}" + time_pattern + "{name} >> {color}{data}"); + logger.set_real_pattern("{C:+black}" + time_pattern + "{name} >> {color}{data}"); test_logger.set_name(corrected_name + ".{test_name}"); - test_logger.set_real_pattern_strmv("{C:+black}" + time_pattern + "{name} >> {color}{data}"); + test_logger.set_real_pattern("{C:+black}" + time_pattern + "{name} >> {color}{data}"); } } diff --git a/src/stream/tester/test_suite/test_suite.hxx b/src/stream/tester/test_suite/test_suite.hxx index d3112613..6c380087 100644 --- a/src/stream/tester/test_suite/test_suite.hxx +++ b/src/stream/tester/test_suite/test_suite.hxx @@ -161,24 +161,23 @@ namespace stream::tester::detail { namespace stream::fmt { template struct FormatterType { - [[nodiscard]] static std::expected format(const stream::tester::detail::TestSuite& t, FormatterExecutor& executor) { + static void format(const stream::tester::detail::TestSuite& t, FormatterExecutor& executor) { return executor.ostream.fast_write_string(t.name); } }; template struct FormatterType { - [[nodiscard]] static std::expected format(const stream::tester::detail::Test& t, FormatterExecutor& executor) { - SF_VERIFY(buf::WriteManip(executor.ostream).fast_write_string(t.link.name)); - SF_VERIFY(buf::WriteManip(executor.ostream).fast_write_string_literal("::")); - SF_VERIFY(buf::WriteManip(executor.ostream).fast_write_string(t.name)); - return {}; + static void format(const stream::tester::detail::Test& t, FormatterExecutor& executor) { + buf::WriteManip(executor.ostream).fast_write_string(t.link.name); + buf::WriteManip(executor.ostream).fast_write_string_literal("::"); + buf::WriteManip(executor.ostream).fast_write_string(t.name); } }; template struct FormatterType { - [[nodiscard]] static std::expected format(const stream::tester::TestStatus& status, FormatterExecutor& executor) { + static void format(const stream::tester::TestStatus& status, FormatterExecutor& executor) { switch (status) { case stream::tester::TestStatus::ok: return executor.run("[ {C:green}OK{C} ]"); @@ -187,38 +186,35 @@ namespace stream::fmt { case stream::tester::TestStatus::Crash: return executor.run("[{C:magenta}Crash{C} ]"); } - return {}; } }; template struct FormatterType { - [[nodiscard]] static std::expected format(const stream::tester::detail::TestStatusBank& status_bank, FormatterExecutor& executor) { - SF_VERIFY(buf::WriteManip(executor.ostream).fast_write_string_literal("tests_done ")); - SF_VERIFY(executor.run("{:C:white}", status_bank.tests_done)); + static void format(const stream::tester::detail::TestStatusBank& status_bank, FormatterExecutor& executor) { + buf::WriteManip(executor.ostream).fast_write_string_literal("tests_done "); + executor.run("{:C:white}", status_bank.tests_done); - SF_VERIFY(buf::WriteManip(executor.ostream).fast_write_string_literal(" | testsOK ")); + buf::WriteManip(executor.ostream).fast_write_string_literal(" | testsOK "); if (status_bank.tests_ok == status_bank.tests_done) { - SF_VERIFY(executor.run("{:C:green}", status_bank.tests_ok)); + executor.run("{:C:green}", status_bank.tests_ok); } else { - SF_VERIFY(executor.run("{:C:yellow}", status_bank.tests_ok)); + executor.run("{:C:yellow}", status_bank.tests_ok); } - SF_VERIFY(buf::WriteManip(executor.ostream).fast_write_string_literal(" | testsFAIL ")); + buf::WriteManip(executor.ostream).fast_write_string_literal(" | testsFAIL "); if (status_bank.tests_failed == 0) { - SF_VERIFY(executor.run("{:C:green}", status_bank.tests_failed)); + executor.run("{:C:green}", status_bank.tests_failed); } else { - SF_VERIFY(executor.run("{:C:red}", status_bank.tests_failed)); + executor.run("{:C:red}", status_bank.tests_failed); } - SF_VERIFY(buf::WriteManip(executor.ostream).fast_write_string_literal(" | TestCrash ")); + buf::WriteManip(executor.ostream).fast_write_string_literal(" | TestCrash "); if (status_bank.tests_crash == 0) { - SF_VERIFY(executor.run("{:C:green}", status_bank.tests_crash)); + executor.run("{:C:green}", status_bank.tests_crash); } else { - SF_VERIFY(executor.run("{:C:magenta}", status_bank.tests_crash)); + executor.run("{:C:magenta}", status_bank.tests_crash); } - - return {}; } }; } // namespace stream::fmt diff --git a/tests/BUILD.bazel b/tests/BUILD.bazel index 7009bb0c..e2fea317 100644 --- a/tests/BUILD.bazel +++ b/tests/BUILD.bazel @@ -8,7 +8,7 @@ cc_test( copts = select({ "@rules_cc//cc/compiler:msvc-cl": ["/std:c++latest"], "//conditions:default": [ - "-std=c++23", + "-std=c++20", "-Wall", "-Wextra", "-Wpedantic", "-Wshadow", "-Wconversion", "-Wsign-conversion", diff --git a/tests/fmt/complex_pattern.cxx b/tests/fmt/complex_pattern.cxx index 04a1a573..3d97ab52 100644 --- a/tests/fmt/complex_pattern.cxx +++ b/tests/fmt/complex_pattern.cxx @@ -7,7 +7,7 @@ // NOLINTBEGIN(readability-magic-numbers) SFT_TEST_GROUP(FMT, COMPLEX_PATTERN); -#define TEST_FMT(fmt_test, expected, ...) SFT_EQ(stream::fmt::format_string(fmt_test, __VA_ARGS__).value(), std::string(expected)) +#define TEST_FMT(fmt_test, expected, ...) SFT_EQ(stream::fmt::format_string(fmt_test, __VA_ARGS__), std::string(expected)) SFT_TEST_FUNC(COMPLEX_PATTERN, UNESCAPED_ESCAPE_PATTERN) { TEST_FMT("{0}", "9", 9); diff --git a/tests/fmt/globber.cxx b/tests/fmt/globber.cxx index 906b3e1a..6d89fd79 100644 --- a/tests/fmt/globber.cxx +++ b/tests/fmt/globber.cxx @@ -7,12 +7,12 @@ // NOLINTBEGIN(misc-const-correctness) // NOLINTBEGIN(readability-magic-numbers) SFT_TEST_GROUP(FMT, GLOBBER); -#define TEST_GLOBBER(data, glob) \ - { \ - stream::fmt::buf::StreamView p_buffer(data); \ - stream::fmt::buf::StreamView p_glob(glob); \ - stream::fmt::buf::Globber::buffer_exec_glob(p_buffer, p_glob).value(); \ - SFT_ASSERT(stream::fmt::buf::Access(p_buffer).is_end_of_string()); \ +#define TEST_GLOBBER(data, glob) \ + { \ + stream::fmt::buf::StreamView p_buffer(data); \ + stream::fmt::buf::StreamView p_glob(glob); \ + stream::fmt::buf::Globber::buffer_exec_glob(p_buffer, p_glob); \ + SFT_ASSERT(p_buffer.is_end_of_string()); \ } SFT_TEST_FUNC(GLOBBER, BASIC_WILDCARD){TEST_GLOBBER("qwerty", "qwerty") TEST_GLOBBER("qwerty", "q?erty") TEST_GLOBBER("qwerty", "q?????") TEST_GLOBBER("qwerty", "qwer?y") @@ -22,36 +22,36 @@ SFT_TEST_FUNC(GLOBBER, BASIC_WILDCARD){TEST_GLOBBER("qwerty", "qwerty") TEST_GLO SFT_TEST_GROUP(FMT, PARSE_GLOBBER); SFT_TEST_FUNC(PARSE_GLOBBER, PG_BASIC_WILDCARD) { int k = 0; - stream::fmt::parse("|123|", "|{}|", k).value(); + stream::fmt::parse("|123|", "|{}|", k); SFT_EQ(k, 123); { // char test[5]; - // stream::fmt::parse("|test|", "|{}|", test).value(); + // stream::fmt::parse("|test|", "|{}|", test); // SFT_EQ(std::string(test), std::string("test")); } { // char test[4]; - // stream::fmt::parse("|test|", "|{:no-zero-end}|", test).value(); + // stream::fmt::parse("|test|", "|{:no-zero-end}|", test); // SFT_EQ(std::string(test, 4), std::string("test")); } { // char test[4]; - // stream::fmt::parse("|test|", "|{}t|", test).value(); + // stream::fmt::parse("|test|", "|{}t|", test); // SFT_EQ(std::string(test), std::string("tes")); } { // char test[11]; - // stream::fmt::parse("|test123456|", "|{}|", test).value(); + // stream::fmt::parse("|test123456|", "|{}|", test); // SFT_EQ(std::string(test), std::string("test123456")); } { // char test[11]; - // stream::fmt::parse("|test123456|", "|{:glob='*1'}23456|", test).value(); + // stream::fmt::parse("|test123456|", "|{:glob='*1'}23456|", test); // SFT_EQ(std::string(test), std::string("test1")); } @@ -63,7 +63,7 @@ SFT_TEST_FUNC(PARSE_GLOBBER, PG_BASIC_WILDCARD) { // "?" // "?" // "?'}123456|", - // test).value(); + // test); // SFT_EQ(std::string(test), std::string("test")); } } diff --git a/tests/fmt/limits.cxx b/tests/fmt/limits.cxx index 0f52ebe7..12a9c137 100644 --- a/tests/fmt/limits.cxx +++ b/tests/fmt/limits.cxx @@ -7,13 +7,12 @@ // NOLINTBEGIN(readability-magic-numbers) SFT_TEST_GROUP(FMT, LIMITS); -#define SFT_TEST_FUNC_LowBufferSize(k) \ - SFT_TEST_FUNC(LIMITS, LowBufferSize##k) { \ - char buffer[k] = {0}; \ - auto res = stream::fmt::format_in_char(buffer, "0123456789"); \ - SFT_EXPECTED_VALUE(res); \ - for (int i = 0; i < k; ++i) \ - SFT_EQ(buffer[i] - '0', i); \ +#define SFT_TEST_FUNC_LowBufferSize(k) \ + SFT_TEST_FUNC(LIMITS, LowBufferSize##k) { \ + char buffer[k] = {0}; \ + stream::fmt::format_in_char(buffer, "0123456789"); \ + for (int i = 0; i < k; ++i) \ + SFT_EQ(buffer[i] - '0', i); \ } SFT_TEST_FUNC_LowBufferSize(10); @@ -29,30 +28,27 @@ SFT_TEST_FUNC_LowBufferSize(1); SFT_TEST_FUNC(LIMITS, PlainLowBufferSize10) { char buffer[10] = {0}; - auto res = stream::fmt::format_in_char(buffer, "0123456789"); - SFT_EXPECTED_VALUE(res); + stream::fmt::format_in_char(buffer, "0123456789"); for (int i = 0; i < 10; ++i) SFT_EQ(buffer[i] - '0', i); } SFT_TEST_FUNC(LIMITS, PlainLowBufferSize1) { char buffer[1] = {0}; - auto res = stream::fmt::format_in_char(buffer, "0"); - SFT_EXPECTED_VALUE(res); + stream::fmt::format_in_char(buffer, "0"); for (int i = 0; i < 1; ++i) SFT_EQ(buffer[i] - '0', i); } -#define SFT_TEST_FUNC_LowBufferSizeArray(k) \ - SFT_TEST_FUNC(LIMITS, LowBufferSizeArray##k) { \ - char buffer[k] = {0}; \ - const char fmt_buffer[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; \ - stream::fmt::buf::StreamView format(fmt_buffer, k); \ - stream::fmt::buf::GivenStreamIOManager manager(buffer, k); \ - auto res = stream::fmt::detail::format_in_manager(manager, false, format); \ - SFT_EXPECTED_VALUE(res); \ - for (int i = 0; i < k; ++i) \ - SFT_EQ(buffer[i] - '0', i); \ +#define SFT_TEST_FUNC_LowBufferSizeArray(k) \ + SFT_TEST_FUNC(LIMITS, LowBufferSizeArray##k) { \ + char buffer[k] = {0}; \ + const char fmt_buffer[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; \ + stream::fmt::buf::StreamView format(fmt_buffer, k); \ + stream::fmt::buf::GivenStreamIOManager manager(buffer, k); \ + stream::fmt::detail::format_in_manager(manager, false, format); \ + for (int i = 0; i < k; ++i) \ + SFT_EQ(buffer[i] - '0', i); \ } SFT_TEST_FUNC_LowBufferSizeArray(10); @@ -71,8 +67,7 @@ SFT_TEST_FUNC(LIMITS, PlainLowBufferSizeArray10) { const char fmt_buffer[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; stream::fmt::buf::StreamView const fmt(fmt_buffer, 10); stream::fmt::buf::GivenStreamIOManager manager(buffer, 10); - auto res = stream::fmt::detail::format_in_manager(manager, false, fmt); - SFT_EXPECTED_VALUE(res); + stream::fmt::detail::format_in_manager(manager, false, fmt); for (int i = 0; i < 10; ++i) SFT_EQ(buffer[i] - '0', i); } @@ -82,8 +77,7 @@ SFT_TEST_FUNC(LIMITS, PlainLowBufferSizeArray1) { const char fmt_buffer[] = {'0'}; stream::fmt::buf::StreamView const fmt(fmt_buffer, 1); stream::fmt::buf::GivenStreamIOManager manager(buffer, 1); - auto res = stream::fmt::detail::format_in_manager(manager, false, fmt); - SFT_EXPECTED_VALUE(res); + stream::fmt::detail::format_in_manager(manager, false, fmt); for (int i = 0; i < 1; ++i) SFT_EQ(buffer[i] - '0', i); } @@ -94,8 +88,7 @@ SFT_TEST_FUNC(LIMITS, LowBufferSizeArray10FMT30) { '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; stream::fmt::buf::StreamView const fmt(fmt_buffer, 30); stream::fmt::buf::GivenStreamIOManager manager(buffer, 10); - auto res = stream::fmt::detail::format_in_manager(manager, false, fmt); - SFT_EXPECTED_VALUE(res); + stream::fmt::detail::format_in_manager(manager, false, fmt); for (int k = 0; k < 10; ++k) SFT_EQ(buffer[k] - '0', k); } @@ -104,9 +97,8 @@ SFT_TEST_FUNC(LIMITS, LowBufferSizeArray5Number9) { char buffer[10] = {0}; stream::fmt::buf::StreamView const fmt("{}"); stream::fmt::buf::GivenStreamIOManager manager(buffer, 10); - std::uint64_t i = 9'876'543'210; - auto res = stream::fmt::detail::format_in_manager(manager, false, fmt, i); - SFT_EXPECTED_VALUE(res); + std::uint64_t i = 9'876'543'210; + stream::fmt::detail::format_in_manager(manager, false, fmt, i); for (int k = 0; k < 10; ++k) SFT_EQ(buffer[k] - '0', 9 - k); } diff --git a/tests/fmt/text_properties.cxx b/tests/fmt/text_properties.cxx index 9b4d45b4..b11720fa 100644 --- a/tests/fmt/text_properties.cxx +++ b/tests/fmt/text_properties.cxx @@ -7,7 +7,7 @@ // NOLINTBEGIN(readability-magic-numbers) SFT_TEST_GROUP(FMT, TEXT_PROPERTIES); -#define TEST_FMT(fmt_test, expected) SFT_EQ(escaper(stream::fmt::format_string(fmt_test, 0).value()), escaper(expected)) +#define TEST_FMT(fmt_test, expected) SFT_EQ(escaper(stream::fmt::format_string(fmt_test, 0)), escaper(expected)) static std::string escaper(const std::string& str) { std::string res; @@ -77,7 +77,7 @@ SFT_TEST_FUNC(TEXT_PROPERTIES, DoubleBasicColor) { class TestFmtContextOut {}; STREAMFORMAT_AUTO_FORMATTER_T(TestFmtContextOut, "{C:red} TEST_FMT_ContextOut {} ", 0); -#define TEST_FMT_CONTEXT(fmt_test, expected) SFT_EQ(escaper(stream::fmt::format_string(fmt_test, TestFmtContextOut{}).value()), escaper(expected)) +#define TEST_FMT_CONTEXT(fmt_test, expected) SFT_EQ(escaper(stream::fmt::format_string(fmt_test, TestFmtContextOut{})), escaper(expected)) SFT_TEST_FUNC(TEXT_PROPERTIES, ContextOut) { TEST_FMT_CONTEXT("{}", "\033[31m TEST_FMT_ContextOut 0 \033[39m"); From 6e3a157fb6b2034024ce7d89d0dc2e15e7267e9d Mon Sep 17 00:00:00 2001 From: BELLIER Sacha Date: Wed, 26 Mar 2025 19:37:05 +0100 Subject: [PATCH 30/42] fix: CI --- src/stream/fmt/buf/manip.hxx | 4 +- src/stream/fmt/buf/manip_io.hxx | 8 +- src/stream/fmt/buf/read_manip.hxx | 4 +- src/stream/fmt/buf/test_manip.hxx | 26 +++--- src/stream/fmt/buf/write_manip.hxx | 1 + .../basic_context_parse_impl.hxx | 2 +- .../basic_context/text_properties_manager.cxx | 82 ++++++++++++++----- .../text_properties_manager_impl.hxx | 38 ++++----- src/stream/fmt/serializers/format_chrono.hxx | 4 +- .../fmt/serializers/std_container/map.hxx | 2 +- .../fmt/serializers/std_container/tuple.hxx | 1 - .../std_container/unordered_map.hxx | 2 +- src/stream/json/json_parser.cxx | 4 +- .../serializers/std_serializers/json_map.hxx | 6 +- .../profiler/profiler_event_creator.cxx | 13 +-- src/stream/profiler/profiler_factory.cxx | 4 +- src/stream/tester/copy_move_check.hxx | 8 +- src/stream/tester/test_suite/test_suite.cxx | 50 +++++++---- tests/fmt/limits.cxx | 18 ++-- 19 files changed, 175 insertions(+), 102 deletions(-) diff --git a/src/stream/fmt/buf/manip.hxx b/src/stream/fmt/buf/manip.hxx index 2fb590ae..0d455445 100644 --- a/src/stream/fmt/buf/manip.hxx +++ b/src/stream/fmt/buf/manip.hxx @@ -69,7 +69,7 @@ namespace stream::fmt::buf { constexpr inline void forward_force(const std::size_t count = 1) noexcept { buffer.current_pos += count; } - constexpr inline void forward(const std::size_t count = 1) noexcept { + constexpr inline void forward(const std::size_t count = 1) { if (!access().can_move_forward(count)) throw std::runtime_error("fmt error: Buffer_OutOfBoundAccess"); buffer.current_pos += count; } @@ -77,7 +77,7 @@ namespace stream::fmt::buf { constexpr inline void backward_force(const std::size_t count = 1) noexcept { buffer.current_pos -= count; } - constexpr inline void backward(const std::size_t count = 1) noexcept { + constexpr inline void backward(const std::size_t count = 1) { if (!access().can_move_backward(count)) throw std::runtime_error("fmt error: Buffer_OutOfBoundAccess"); buffer.current_pos -= count; } diff --git a/src/stream/fmt/buf/manip_io.hxx b/src/stream/fmt/buf/manip_io.hxx index 95c8d04a..ffd0814a 100644 --- a/src/stream/fmt/buf/manip_io.hxx +++ b/src/stream/fmt/buf/manip_io.hxx @@ -34,7 +34,7 @@ namespace stream::fmt::buf { return add_size(count); } - void forward(const std::size_t count = 1) noexcept { + void forward(const std::size_t count = 1) { if (reserve(count) == false) throw std::bad_alloc(); buffer.current_pos += count; } @@ -44,7 +44,7 @@ namespace stream::fmt::buf { *buffer.current_pos = c; } - void pushback(const TChar c) noexcept { + void pushback(const TChar c) { if (reserve(1) == false) throw std::bad_alloc(); *buffer.current_pos++ = c; } @@ -53,7 +53,7 @@ namespace stream::fmt::buf { } public: - void pushback(const TChar c, auto count) noexcept { + void pushback(const TChar c, auto count) { if (reserve(count) == false) throw std::bad_alloc(); while (count-- > 0) pushback_force(c); @@ -68,7 +68,7 @@ namespace stream::fmt::buf { public: template - void pushback_seq(const CharToPush... ele) noexcept { + void pushback_seq(const CharToPush... ele) { if (reserve(sizeof...(ele)) == false) throw std::bad_alloc(); pushback_seq_impl(ele...); } diff --git a/src/stream/fmt/buf/read_manip.hxx b/src/stream/fmt/buf/read_manip.hxx index fb28c7dd..53140bb9 100644 --- a/src/stream/fmt/buf/read_manip.hxx +++ b/src/stream/fmt/buf/read_manip.hxx @@ -16,7 +16,7 @@ namespace stream::fmt::buf { public: template - constexpr void fast_read_integer(T& t) noexcept { + constexpr void fast_read_integer(T& t) { bool sign = false; if constexpr (std::is_signed_v) { sign = TestManip(buffer).is_equal_to_forward('-'); @@ -37,7 +37,7 @@ namespace stream::fmt::buf { public: template - constexpr inline void fast_read_float(T& t, std::int32_t float_precision = -1) noexcept { + constexpr inline void fast_read_float(T& t, std::int32_t float_precision = -1) { T intpart = static_cast(0); TestAccess access(buffer); diff --git a/src/stream/fmt/buf/test_manip.hxx b/src/stream/fmt/buf/test_manip.hxx index 372ff95d..1f59ce67 100644 --- a/src/stream/fmt/buf/test_manip.hxx +++ b/src/stream/fmt/buf/test_manip.hxx @@ -83,7 +83,7 @@ namespace stream::fmt::buf { public: template - constexpr inline bool is_equal_to_forward(const CharToTest... ele) noexcept { + constexpr inline bool is_equal_to_forward(const CharToTest... ele) { if (access().is_equal_to(ele...)) { Manip(buffer).forward(); return true; @@ -91,7 +91,7 @@ namespace stream::fmt::buf { return false; } template - constexpr inline bool is_not_equal_forward(const CharToTest... ele) noexcept { + constexpr inline bool is_not_equal_forward(const CharToTest... ele) { if (access().is_not_equal_to(ele...)) { Manip(buffer).forward(); return true; @@ -101,7 +101,7 @@ namespace stream::fmt::buf { public: template - constexpr bool is_same_forward(const CharToTest* str, std::size_t size) noexcept { + constexpr bool is_same_forward(const CharToTest* str, std::size_t size) { if (access().is_same(str, size)) { Manip(buffer).forward(size); return true; @@ -109,7 +109,7 @@ namespace stream::fmt::buf { return false; } template - constexpr inline bool is_same_forward(std::basic_string_view sv) noexcept { + constexpr inline bool is_same_forward(std::basic_string_view sv) { if (access().is_same(sv)) { Manip(buffer).forward(sv.size()); return true; @@ -119,7 +119,7 @@ namespace stream::fmt::buf { public: template - void skip_one_of(const CharToTest... ele) noexcept { + void skip_one_of(const CharToTest... ele) { if (access().is_equal_to(ele...)) { Manip(buffer).forward(); } @@ -127,31 +127,31 @@ namespace stream::fmt::buf { } template - inline void ignore_one_of(const CharToTest... ele) noexcept { + inline void ignore_one_of(const CharToTest... ele) { if (access().is_equal_to(ele...) && Access(buffer).can_move_forward()) { Manip(buffer).forward_force(); } } template - inline void ignore_every(const CharToTest... ele) noexcept { + inline void ignore_every(const CharToTest... ele) { while (access().is_equal_to(ele...) && Access(buffer).can_move_forward()) { Manip(buffer).forward_force(); } } public: - void IgnoreOneSpace() noexcept { + void IgnoreOneSpace() { return ignore_one_of(' ', '\t'); } - void IgnoreOneBlank() noexcept { + void IgnoreOneBlank() { return ignore_one_of(' ', '\t', '\n', '\r', '\v'); } - inline void ignore_every_spaces() noexcept { + inline void ignore_every_spaces() { ignore_every(' ', '\t'); } - inline void IgnoreEveryBlanks() noexcept { + inline void IgnoreEveryBlanks() { ignore_every(' ', '\t', '\n', '\r', '\v'); } @@ -162,7 +162,7 @@ namespace stream::fmt::buf { Manip(buffer).forward_force(); } template - void go_to_forward(const CharToTest... ele) noexcept { + void go_to_forward(const CharToTest... ele) { GoTo(ele...); return Manip(buffer).forward(); } @@ -178,7 +178,7 @@ namespace stream::fmt::buf { template inline std::basic_string_view view_until(CharToTest&&... c) { - return view_exec([&] -> void { TestManip(buffer).GoTo(std::forward(c)...); }); + return view_exec([&] { TestManip(buffer).GoTo(std::forward(c)...); }); } }; } // namespace stream::fmt::buf diff --git a/src/stream/fmt/buf/write_manip.hxx b/src/stream/fmt/buf/write_manip.hxx index 0463073f..46db49af 100644 --- a/src/stream/fmt/buf/write_manip.hxx +++ b/src/stream/fmt/buf/write_manip.hxx @@ -7,6 +7,7 @@ #include #include +#include namespace stream::fmt::buf { class WriteUtils { diff --git a/src/stream/fmt/context/basic_context/basic_context_parse_impl.hxx b/src/stream/fmt/context/basic_context/basic_context_parse_impl.hxx index 40d6c40c..9dc3bd19 100644 --- a/src/stream/fmt/context/basic_context/basic_context_parse_impl.hxx +++ b/src/stream/fmt/context/basic_context/basic_context_parse_impl.hxx @@ -152,7 +152,7 @@ namespace stream::fmt::context { buf::TestAccess access(fmtstream); buf::TestManip manip(fmtstream); - std::basic_string_view name = manip.view_exec([&] -> void { buf::FMTParamsManip(fmtstream).param_go_to(' ', '=', '\'', '{', ','); }); + std::basic_string_view name = manip.view_exec([&] { buf::FMTParamsManip(fmtstream).param_go_to(' ', '=', '\'', '{', ','); }); buf::FMTParamsManip(fmtstream).param_go_to('=', '\'', '{', ','); manip.ignore_one_of('='); manip.ignore_every_spaces(); diff --git a/src/stream/fmt/context/basic_context/text_properties_manager.cxx b/src/stream/fmt/context/basic_context/text_properties_manager.cxx index fe5338bf..0c32d3e4 100644 --- a/src/stream/fmt/context/basic_context/text_properties_manager.cxx +++ b/src/stream/fmt/context/basic_context/text_properties_manager.cxx @@ -4,23 +4,44 @@ namespace stream::fmt::detail { void TextPropertiesapplyManager::reload_color_fg(const TextProperties::TextColor::ColorFG& target) { if (target.type != current_context_properties_.color.fg.type) { switch (target.type) { - case TextProperties::TextColor::ColorType::BasicColor: - return apply_color(target.data.basic_color); - case TextProperties::TextColor::ColorType::ColorCube: - return apply_color(target.data.color_cube); - case TextProperties::TextColor::ColorType::Color24b: - return apply_color(target.data.color24b); + case TextProperties::TextColor::ColorType::BasicColor: { + apply_color(target.data.basic_color); + return; + } + case TextProperties::TextColor::ColorType::ColorCube: { + apply_color(target.data.color_cube); + return; + } + case TextProperties::TextColor::ColorType::Color24b: { + apply_color(target.data.color24b); + return; + } } } else { switch (target.type) { case TextProperties::TextColor::ColorType::BasicColor: - if (current_context_properties_.color.fg.data.basic_color != target.data.basic_color) return apply_color(target.data.basic_color); + if (current_context_properties_.color.fg.data.basic_color != target.data.basic_color) { + { + apply_color(target.data.basic_color); + } + return; + } break; case TextProperties::TextColor::ColorType::ColorCube: - if (current_context_properties_.color.fg.data.color_cube != target.data.color_cube) return apply_color(target.data.color_cube); + if (current_context_properties_.color.fg.data.color_cube != target.data.color_cube) { + { + apply_color(target.data.color_cube); + } + return; + } break; case TextProperties::TextColor::ColorType::Color24b: - if (current_context_properties_.color.fg.data.color24b != target.data.color24b) return apply_color(target.data.color24b); + if (current_context_properties_.color.fg.data.color24b != target.data.color24b) { + { + apply_color(target.data.color24b); + } + return; + } break; } } @@ -29,23 +50,44 @@ namespace stream::fmt::detail { void TextPropertiesapplyManager::reload_color_bg(const TextProperties::TextColor::ColorBG& target) { if (target.type != current_context_properties_.color.bg.type) { switch (target.type) { - case TextProperties::TextColor::ColorType::BasicColor: - return apply_color(target.data.basic_color); - case TextProperties::TextColor::ColorType::ColorCube: - return apply_color(target.data.color_cube); - case TextProperties::TextColor::ColorType::Color24b: - return apply_color(target.data.color24b); + case TextProperties::TextColor::ColorType::BasicColor: { + apply_color(target.data.basic_color); + return; + } + case TextProperties::TextColor::ColorType::ColorCube: { + apply_color(target.data.color_cube); + return; + } + case TextProperties::TextColor::ColorType::Color24b: { + apply_color(target.data.color24b); + return; + } } } else { switch (target.type) { case TextProperties::TextColor::ColorType::BasicColor: - if (current_context_properties_.color.bg.data.basic_color != target.data.basic_color) return apply_color(target.data.basic_color); + if (current_context_properties_.color.bg.data.basic_color != target.data.basic_color) { + { + apply_color(target.data.basic_color); + } + return; + } break; case TextProperties::TextColor::ColorType::ColorCube: - if (current_context_properties_.color.bg.data.color_cube != target.data.color_cube) return apply_color(target.data.color_cube); + if (current_context_properties_.color.bg.data.color_cube != target.data.color_cube) { + { + apply_color(target.data.color_cube); + } + return; + } break; case TextProperties::TextColor::ColorType::Color24b: - if (current_context_properties_.color.bg.data.color24b != target.data.color24b) return apply_color(target.data.color24b); + if (current_context_properties_.color.bg.data.color24b != target.data.color24b) { + { + apply_color(target.data.color24b); + } + return; + } break; } } @@ -120,7 +162,9 @@ namespace stream::fmt::detail { // NOLINTEND(readability-function-cognitive-complexity) void TextPropertiesapplyManager::reload_front(const TextProperties::TextFront::Front& target) { - if (current_context_properties_.front == target) return; + if (current_context_properties_.front == target) { + return; + } apply_front(target.current_id); current_context_properties_.front = target; diff --git a/src/stream/fmt/context/basic_context/text_properties_manager_impl.hxx b/src/stream/fmt/context/basic_context/text_properties_manager_impl.hxx index 9823425a..06ed5161 100644 --- a/src/stream/fmt/context/basic_context/text_properties_manager_impl.hxx +++ b/src/stream/fmt/context/basic_context/text_properties_manager_impl.hxx @@ -12,52 +12,52 @@ namespace stream::fmt::detail { template void detail::TextPropertiesManager::apply_color_on_index(context::BasicContext& context, std::int32_t index) { context.args_interface.template run_func_from_type_at( - index, [this](const detail::TextProperties::TextColor::Color& data) -> void { this->reload_color(data); }); + index, [this](const detail::TextProperties::TextColor::Color& data) { this->reload_color(data); }); context.args_interface.template run_func_from_type_at( - index, [this](const detail::TextProperties::TextColor::BasicColorFG& data) -> void { this->ask_apply_color(data); }); + index, [this](const detail::TextProperties::TextColor::BasicColorFG& data) { this->ask_apply_color(data); }); context.args_interface.template run_func_from_type_at( - index, [this](const detail::TextProperties::TextColor::BasicColorBG& data) -> void { this->ask_apply_color(data); }); + index, [this](const detail::TextProperties::TextColor::BasicColorBG& data) { this->ask_apply_color(data); }); context.args_interface.template run_func_from_type_at( - index, [this](const detail::TextProperties::TextColor::ColorCubeFG& data) -> void { this->ask_apply_color(data); }); + index, [this](const detail::TextProperties::TextColor::ColorCubeFG& data) { this->ask_apply_color(data); }); context.args_interface.template run_func_from_type_at( - index, [this](const detail::TextProperties::TextColor::ColorCubeBG& data) -> void { this->ask_apply_color(data); }); + index, [this](const detail::TextProperties::TextColor::ColorCubeBG& data) { this->ask_apply_color(data); }); context.args_interface.template run_func_from_type_at( - index, [this](const detail::TextProperties::TextColor::Color24bFG& data) -> void { this->ask_apply_color(data); }); + index, [this](const detail::TextProperties::TextColor::Color24bFG& data) { this->ask_apply_color(data); }); context.args_interface.template run_func_from_type_at( - index, [this](const detail::TextProperties::TextColor::Color24bBG& data) -> void { this->ask_apply_color(data); }); + index, [this](const detail::TextProperties::TextColor::Color24bBG& data) { this->ask_apply_color(data); }); } template void detail::TextPropertiesManager::apply_front_on_index(context::BasicContext& context, std::int32_t index) { context.args_interface.template run_func_from_type_at( - index, [this](const detail::TextProperties::TextFront::Front& data) -> void { this->reload_front(data); }); + index, [this](const detail::TextProperties::TextFront::Front& data) { this->reload_front(data); }); context.args_interface.template run_func_from_type_at( - index, [this](const detail::TextProperties::TextFront::FrontID& data) -> void { this->ask_apply_front(data); }); + index, [this](const detail::TextProperties::TextFront::FrontID& data) { this->ask_apply_front(data); }); } template void detail::TextPropertiesManager::apply_style_on_index(context::BasicContext& context, std::int32_t index) { context.args_interface.template run_func_from_type_at( - index, [this](const detail::TextProperties::TextStyle::Style& data) -> void { return this->reload_style(data); }); + index, [this](const detail::TextProperties::TextStyle::Style& data) { return this->reload_style(data); }); context.args_interface.template run_func_from_type_at( - index, [this](const detail::TextProperties::TextStyle::Intensity& data) -> void { return this->ask_apply_style(data); }); + index, [this](const detail::TextProperties::TextStyle::Intensity& data) { return this->ask_apply_style(data); }); context.args_interface.template run_func_from_type_at( - index, [this](const detail::TextProperties::TextStyle::Italic& data) -> void { return this->ask_apply_style(data); }); + index, [this](const detail::TextProperties::TextStyle::Italic& data) { return this->ask_apply_style(data); }); context.args_interface.template run_func_from_type_at( - index, [this](const detail::TextProperties::TextStyle::Underline& data) -> void { return this->ask_apply_style(data); }); + index, [this](const detail::TextProperties::TextStyle::Underline& data) { return this->ask_apply_style(data); }); context.args_interface.template run_func_from_type_at( - index, [this](const detail::TextProperties::TextStyle::Blink& data) -> void { return this->ask_apply_style(data); }); + index, [this](const detail::TextProperties::TextStyle::Blink& data) { return this->ask_apply_style(data); }); context.args_interface.template run_func_from_type_at( - index, [this](const detail::TextProperties::TextStyle::Inverted& data) -> void { return this->ask_apply_style(data); }); + index, [this](const detail::TextProperties::TextStyle::Inverted& data) { return this->ask_apply_style(data); }); context.args_interface.template run_func_from_type_at( - index, [this](const detail::TextProperties::TextStyle::Ideogram& data) -> void { return this->ask_apply_style(data); }); + index, [this](const detail::TextProperties::TextStyle::Ideogram& data) { return this->ask_apply_style(data); }); context.args_interface.template run_func_from_type_at( - index, [this](const detail::TextProperties::TextStyle::Script& data) -> void { return this->ask_apply_style(data); }); + index, [this](const detail::TextProperties::TextStyle::Script& data) { return this->ask_apply_style(data); }); context.args_interface.template run_func_from_type_at( - index, [this](const detail::TextProperties::TextStyle::UnderlineColor::ColorCube& data) -> void { this->ask_apply_style(data); }); + index, [this](const detail::TextProperties::TextStyle::UnderlineColor::ColorCube& data) { this->ask_apply_style(data); }); context.args_interface.template run_func_from_type_at( - index, [this](const detail::TextProperties::TextStyle::UnderlineColor::Color24b& data) -> void { this->ask_apply_style(data); }); + index, [this](const detail::TextProperties::TextStyle::UnderlineColor::Color24b& data) { this->ask_apply_style(data); }); } template diff --git a/src/stream/fmt/serializers/format_chrono.hxx b/src/stream/fmt/serializers/format_chrono.hxx index 095bfa35..a7b83cd9 100644 --- a/src/stream/fmt/serializers/format_chrono.hxx +++ b/src/stream/fmt/serializers/format_chrono.hxx @@ -76,7 +76,7 @@ namespace stream::fmt::detail { buf::Manip(pattern).reload("%2h:%2m:%2s:%3ms"); } - auto view = buf::TestManip(pattern).view_exec([&] -> void { buf::FMTParamsManip(pattern).param_go_to('%', '#', '/'); }); + auto view = buf::TestManip(pattern).view_exec([&] { buf::FMTParamsManip(pattern).param_go_to('%', '#', '/'); }); buf::WriteManip(buffer).fast_write_string(view); while (!pattern.is_end_of_string()) { @@ -91,7 +91,7 @@ namespace stream::fmt::detail { buf::Manip(pattern).forward(); write_sub_time_(value, pattern, buffer, mode); - auto view = buf::TestManip(pattern).view_exec([&] -> void { buf::FMTParamsManip(pattern).param_go_to('%', '#', '/'); }); + auto view = buf::TestManip(pattern).view_exec([&] { buf::FMTParamsManip(pattern).param_go_to('%', '#', '/'); }); buf::WriteManip(buffer).fast_write_string(view); } } diff --git a/src/stream/fmt/serializers/std_container/map.hxx b/src/stream/fmt/serializers/std_container/map.hxx index d931aa6d..9142b947 100644 --- a/src/stream/fmt/serializers/std_container/map.hxx +++ b/src/stream/fmt/serializers/std_container/map.hxx @@ -4,7 +4,7 @@ #include "stream/fmt/context/formatter_executor/formatter_type.hxx" #include "stream/fmt/context/formatter_executor/std_enumerable.hxx" -#include "tuple.h" +#include "tuple.hxx" namespace stream::fmt { template diff --git a/src/stream/fmt/serializers/std_container/tuple.hxx b/src/stream/fmt/serializers/std_container/tuple.hxx index 00dcf8f9..fbe5fc48 100644 --- a/src/stream/fmt/serializers/std_container/tuple.hxx +++ b/src/stream/fmt/serializers/std_container/tuple.hxx @@ -36,7 +36,6 @@ namespace stream::fmt { struct FormatterType, FormatterExecutor> { static void format(const std::tuple& t, FormatterExecutor& executor) { executor.ostream.pushback('<'); - void err = {}; std::apply([&context_executor, &err](auto&&... args) { auto&& res = tuple_detail::tuple_format_rec(context_executor, args...); if (not res) { diff --git a/src/stream/fmt/serializers/std_container/unordered_map.hxx b/src/stream/fmt/serializers/std_container/unordered_map.hxx index 307e607c..a538cf15 100644 --- a/src/stream/fmt/serializers/std_container/unordered_map.hxx +++ b/src/stream/fmt/serializers/std_container/unordered_map.hxx @@ -4,7 +4,7 @@ #include "stream/fmt/context/formatter_executor/std_enumerable.hxx" #include -#include "tuple.h" +#include "tuple.hxx" namespace stream::fmt { template diff --git a/src/stream/json/json_parser.cxx b/src/stream/json/json_parser.cxx index 3a6fd8bb..43b8c73f 100644 --- a/src/stream/json/json_parser.cxx +++ b/src/stream/json/json_parser.cxx @@ -18,7 +18,9 @@ namespace stream::json::detail { manip.skip_one_of('"'); while (true) { manip.GoTo('"'); - if (fmt::buf::Access(parser.istream).get_prev_force() != '\\') break; + if (fmt::buf::Access(parser.istream).get_prev_force() != '\\') { + break; + } } manip.skip_one_of('"'); } else if (parser.is_json_number_begin()) { diff --git a/src/stream/json/serializers/std_serializers/json_map.hxx b/src/stream/json/serializers/std_serializers/json_map.hxx index 500a3a10..4050f143 100644 --- a/src/stream/json/serializers/std_serializers/json_map.hxx +++ b/src/stream/json/serializers/std_serializers/json_map.hxx @@ -20,8 +20,9 @@ namespace stream::json { static void format(const std::map& t, detail::JsonFormatter& formatter) { JsonStructSerializer::FormatBegin(formatter); std::size_t idx = 0; - for (const auto& [name, object] : t) + for (const auto& [name, object] : t) { JsonStructSerializer::FormatObject(name, object, idx++, formatter); + } JsonStructSerializer::FormatEnd(formatter); } }; @@ -41,8 +42,9 @@ namespace stream::json { static void format(const std::multimap& t, detail::JsonFormatter& formatter) { JsonStructSerializer::FormatBegin(formatter); std::size_t idx = 0; - for (const auto& [name, object] : t) + for (const auto& [name, object] : t) { JsonStructSerializer::FormatObject(name, object, idx++, formatter); + } JsonStructSerializer::FormatEnd(formatter); } }; diff --git a/src/stream/profiler/profiler_event_creator.cxx b/src/stream/profiler/profiler_event_creator.cxx index 2cf3fa94..f9937691 100644 --- a/src/stream/profiler/profiler_event_creator.cxx +++ b/src/stream/profiler/profiler_event_creator.cxx @@ -5,17 +5,18 @@ namespace stream::profiler { ScopeProfile::~ScopeProfile() { stop(); - std::chrono::microseconds us = std::chrono::duration_cast(info.duration); - std::chrono::milliseconds const millis = std::chrono::duration_cast(info.duration); - std::chrono::seconds const seconds = std::chrono::duration_cast(info.duration); + const std::chrono::microseconds us = std::chrono::duration_cast(info.duration); + const std::chrono::milliseconds millis = std::chrono::duration_cast(info.duration); + const std::chrono::seconds seconds = std::chrono::duration_cast(info.duration); // NOLINTBEGIN(readability-magic-numbers) - if (seconds.count() > 1.5) + if (seconds.count() > 1.5) { profiler_.get_logger().trace("{} : {} seconds", info.name, seconds.count()); - else if (millis.count() > 5.0) + } else if (millis.count() > 5.0) { profiler_.get_logger().trace("{} : {} ms", info.name, millis.count()); - else + } else { profiler_.get_logger().trace("{} : {} us", info.name, us.count()); + } // NOLINTEND(readability-magic-numbers) profiler_.add_event(*this); diff --git a/src/stream/profiler/profiler_factory.cxx b/src/stream/profiler/profiler_factory.cxx index 7d4964a5..d399a726 100644 --- a/src/stream/profiler/profiler_factory.cxx +++ b/src/stream/profiler/profiler_factory.cxx @@ -8,7 +8,9 @@ namespace stream::profiler { profiler.profiler_duration.stop(); profiler.events[0] = profiler.profiler_duration.info; - if (path == "") path = std::string(profiler.name) + ".json"; + if (path == "") { + path = std::string(profiler.name) + ".json"; + } std::ofstream file(path.string(), std::ios::out); json::FormatAsJson const format_profiler(profiler); diff --git a/src/stream/tester/copy_move_check.hxx b/src/stream/tester/copy_move_check.hxx index 7e6709a8..3d3790dc 100644 --- a/src/stream/tester/copy_move_check.hxx +++ b/src/stream/tester/copy_move_check.hxx @@ -24,11 +24,11 @@ namespace stream::tester { logger.info("CopyMoveCheck {} : {:C:red} ( {:C:red} )", name_, "Const Copy Constructor", "TestCopy(const TestCopy&)"); } - CopyMoveCheck(CopyMoveCheck&& other) noexcept : name_("Move of " + other.name_) { + CopyMoveCheck(CopyMoveCheck&& other) : name_("Move of " + other.name_) { logger.info("CopyMoveCheck {} : {:C:red} ( {:C:red} )", name_, "Move Constructor", "TestCopy(TestCopy&&)"); } - CopyMoveCheck(const CopyMoveCheck&& other) noexcept : name_("Move of " + other.name_) { + CopyMoveCheck(const CopyMoveCheck&& other) : name_("Move of " + other.name_) { logger.info("CopyMoveCheck {} : {:C:red} ( {:C:red} )", name_, "Const Move Constructor", "TestCopy(const TestCopy&&)"); } @@ -46,14 +46,14 @@ namespace stream::tester { return *this; } - CopyMoveCheck& operator=(CopyMoveCheck&& other) noexcept { + CopyMoveCheck& operator=(CopyMoveCheck&& other) { name_ = "Move Of " + other.name_; logger.info("CopyMoveCheck {} : {:C:red} ( {:C:red} )", name_, "Move Assignment", "TestCopy& operator=(TestCopy&&)"); return *this; } - CopyMoveCheck& operator=(const CopyMoveCheck&& other) noexcept { + CopyMoveCheck& operator=(const CopyMoveCheck&& other) { name_ = "Move Of " + other.name_; logger.info("CopyMoveCheck {} : {:C:red} ( {:C:red} )", name_, "Const Move Assignment", "TestCopy& operator=(const TestCopy&&)"); diff --git a/src/stream/tester/test_suite/test_suite.cxx b/src/stream/tester/test_suite/test_suite.cxx index cabd8070..d2b7d4cc 100644 --- a/src/stream/tester/test_suite/test_suite.cxx +++ b/src/stream/tester/test_suite/test_suite.cxx @@ -8,14 +8,16 @@ namespace stream::tester { bool TestSuitesManager::exec_all_test_suites() { detail::TestStatusBank status; - for (auto& [name, test_suite] : test_suites) + for (auto& [name, test_suite] : test_suites) { status.add(test_suite->exec_all_tests()); + } flog::BasicLogger logger("TestSuite"); - if (status.is_all_ok()) + if (status.is_all_ok()) { logger.info("{C:white}RESULT => {C:+black}{}", status); - else + } else { logger.error("{C:white}RESULT => {C:+black}{}", status); + } return status.error_status() != 0u; } @@ -23,10 +25,11 @@ namespace stream::tester { namespace stream::tester::detail { TestStatusBank TestSuite::exec_all_tests() { - if (parent == nullptr) + if (parent == nullptr) { profiler = new profiler::Profiler("TestSuite_" + name); - else + } else { profiler = &get_profiler(); + } init_logger(); logger.info("{C:+black}{}", "BEGIN"); @@ -41,12 +44,14 @@ namespace stream::tester::detail { profiler::DurationEvent current_test_duration(test->name, "Profile"); TestStatus test_status = TestStatus::fail; current_test_duration.start(); - if (TestSuitesManager::performance_test.enable == false) + if (TestSuitesManager::performance_test.enable == false) { test_status = test->run(); - else { + } else { for (std::uint32_t i = 0; i < TestSuitesManager::performance_test.nb_samples; ++i) { test_status = test->run(); - if (test_status != TestStatus::ok) break; + if (test_status != TestStatus::ok) { + break; + } } } current_test_duration.stop(); @@ -61,10 +66,11 @@ namespace stream::tester::detail { profiler::DurationEvent groups_duration("Groups", "Profile"); groups_duration.start(); for (auto& [name, test_suite] : test_suites_linked) { - if (first_test_suite) + if (first_test_suite) { first_test_suite = false; - else + } else { std::cout << std::endl; + } test_suite_status.add(test_suite->exec_all_tests()); } groups_duration.stop(); @@ -73,10 +79,11 @@ namespace stream::tester::detail { profiler->add_event(groups_duration); profiler->add_event(test_suite_duration); - if (test_suite_status.is_all_ok()) + if (test_suite_status.is_all_ok()) { logger.info("{C:+black}{}", test_suite_status); - else + } else { logger.error("{C:+black}{}", test_suite_status); + } if (parent == nullptr) { profiler::ProfilerFactory::to_json(*profiler); @@ -96,7 +103,9 @@ namespace stream::tester::detail { } std::string time_pattern; - if (TestSuitesManager::print_time) time_pattern = "[{logtime:pattern='default'}] "; + if (TestSuitesManager::print_time) { + time_pattern = "[{logtime:pattern='default'}] "; + } if (parent == nullptr) { logger.set_name(name); @@ -113,12 +122,16 @@ namespace stream::tester::detail { } std::string TestSuite::get_full_name() const { - if (parent == nullptr) return name; + if (parent == nullptr) { + return name; + } return parent->get_full_name() + "::" + name; } std::string TestSuite::get_corrected_size_name() { - if (parent == nullptr) return name; + if (parent == nullptr) { + return name; + } std::size_t biggest_name = 0; for (auto& [name, test_suite] : parent->test_suites_linked) { std::size_t const tmp = test_suite->name.size(); @@ -127,13 +140,16 @@ namespace stream::tester::detail { std::string res = get_full_name(); biggest_name -= name.size(); res.reserve(res.size() + biggest_name); - for (std::uint32_t i = 0; i < biggest_name; ++i) + for (std::uint32_t i = 0; i < biggest_name; ++i) { res.push_back(' '); + } return res; } profiler::Profiler& TestSuite::get_profiler() const { - if (parent == nullptr) return *profiler; + if (parent == nullptr) { + return *profiler; + } return parent->get_profiler(); } } // namespace stream::tester::detail diff --git a/tests/fmt/limits.cxx b/tests/fmt/limits.cxx index 12a9c137..2ff945e3 100644 --- a/tests/fmt/limits.cxx +++ b/tests/fmt/limits.cxx @@ -29,15 +29,17 @@ SFT_TEST_FUNC_LowBufferSize(1); SFT_TEST_FUNC(LIMITS, PlainLowBufferSize10) { char buffer[10] = {0}; stream::fmt::format_in_char(buffer, "0123456789"); - for (int i = 0; i < 10; ++i) + for (int i = 0; i < 10; ++i) { SFT_EQ(buffer[i] - '0', i); + } } SFT_TEST_FUNC(LIMITS, PlainLowBufferSize1) { char buffer[1] = {0}; stream::fmt::format_in_char(buffer, "0"); - for (int i = 0; i < 1; ++i) + for (int i = 0; i < 1; ++i) { SFT_EQ(buffer[i] - '0', i); + } } #define SFT_TEST_FUNC_LowBufferSizeArray(k) \ @@ -68,8 +70,9 @@ SFT_TEST_FUNC(LIMITS, PlainLowBufferSizeArray10) { stream::fmt::buf::StreamView const fmt(fmt_buffer, 10); stream::fmt::buf::GivenStreamIOManager manager(buffer, 10); stream::fmt::detail::format_in_manager(manager, false, fmt); - for (int i = 0; i < 10; ++i) + for (int i = 0; i < 10; ++i) { SFT_EQ(buffer[i] - '0', i); + } } SFT_TEST_FUNC(LIMITS, PlainLowBufferSizeArray1) { @@ -78,8 +81,9 @@ SFT_TEST_FUNC(LIMITS, PlainLowBufferSizeArray1) { stream::fmt::buf::StreamView const fmt(fmt_buffer, 1); stream::fmt::buf::GivenStreamIOManager manager(buffer, 1); stream::fmt::detail::format_in_manager(manager, false, fmt); - for (int i = 0; i < 1; ++i) + for (int i = 0; i < 1; ++i) { SFT_EQ(buffer[i] - '0', i); + } } SFT_TEST_FUNC(LIMITS, LowBufferSizeArray10FMT30) { @@ -89,8 +93,9 @@ SFT_TEST_FUNC(LIMITS, LowBufferSizeArray10FMT30) { stream::fmt::buf::StreamView const fmt(fmt_buffer, 30); stream::fmt::buf::GivenStreamIOManager manager(buffer, 10); stream::fmt::detail::format_in_manager(manager, false, fmt); - for (int k = 0; k < 10; ++k) + for (int k = 0; k < 10; ++k) { SFT_EQ(buffer[k] - '0', k); + } } SFT_TEST_FUNC(LIMITS, LowBufferSizeArray5Number9) { @@ -99,8 +104,9 @@ SFT_TEST_FUNC(LIMITS, LowBufferSizeArray5Number9) { stream::fmt::buf::GivenStreamIOManager manager(buffer, 10); std::uint64_t i = 9'876'543'210; stream::fmt::detail::format_in_manager(manager, false, fmt, i); - for (int k = 0; k < 10; ++k) + for (int k = 0; k < 10; ++k) { SFT_EQ(buffer[k] - '0', 9 - k); + } } // NOLINTEND(readability-magic-numbers) // NOLINTEND(misc-const-correctness) From cec7c4eb3d4566e057d70ea42421b97f363d5e6e Mon Sep 17 00:00:00 2001 From: BELLIER Sacha Date: Wed, 26 Mar 2025 20:16:46 +0100 Subject: [PATCH 31/42] wip: nested specs using `:` --- .../context/basic_context/basic_context.hxx | 2 +- .../basic_context_parse_impl.hxx | 16 +++++----------- tests/fmt/specifier.cxx | 19 +++++++++++++++++++ 3 files changed, 25 insertions(+), 12 deletions(-) diff --git a/src/stream/fmt/context/basic_context/basic_context.hxx b/src/stream/fmt/context/basic_context/basic_context.hxx index d108a90b..6bd7481c 100644 --- a/src/stream/fmt/context/basic_context/basic_context.hxx +++ b/src/stream/fmt/context/basic_context/basic_context.hxx @@ -71,7 +71,7 @@ namespace stream::fmt::context { void parse_format_data_base(); void parse_format_data_special(); void parse_format_data_special_shift_type(const detail::ShiftInfo::ShiftType type); - void parse_format_dataCustom(); + void parse_format_data_custom(); void parse_format_data(); void parse_variable(std::int32_t format_idx); diff --git a/src/stream/fmt/context/basic_context/basic_context_parse_impl.hxx b/src/stream/fmt/context/basic_context/basic_context_parse_impl.hxx index 9dc3bd19..0f6f9120 100644 --- a/src/stream/fmt/context/basic_context/basic_context_parse_impl.hxx +++ b/src/stream/fmt/context/basic_context/basic_context_parse_impl.hxx @@ -16,15 +16,10 @@ namespace stream::fmt::context { buf::TestAccess access(fmtstream); buf::TestManip manip(fmtstream); + manip.is_equal_to_forward(':'); manip.ignore_every_spaces(); - buf::FMTParamsManip(fmtstream).param_go_to('{', '=', ':'); - manip.ignore_every_spaces(); - manip.ignore_one_of('=', ':'); - manip.ignore_every_spaces(); - buf::FMTParamsManip(fmtstream).param_go_to('{'); const TChar* begin = fmtstream.current_pos; - manip.skip_one_of('{'); int scopes = 0; while (buf::FMTParamsManip(fmtstream).is_end_of_parameter() == false || scopes > 0) { manip.GoTo('\'', '}', '{'); @@ -39,7 +34,6 @@ namespace stream::fmt::context { scopes--; } } - manip.skip_one_of('}'); const TChar* end = fmtstream.current_pos; return std::basic_string_view(begin, end - begin); } @@ -64,7 +58,7 @@ namespace stream::fmt::context { executor.data.keep_new_style = true; } - else if (access.is_equal_to('N')) { + else if (access.is_equal_to(':')) { buf::Manip(fmtstream).forward(); executor.data.next_override = parse_next_override_format_data(); } @@ -148,7 +142,7 @@ namespace stream::fmt::context { } template - void BasicContext::parse_format_dataCustom() { + void BasicContext::parse_format_data_custom() { buf::TestAccess access(fmtstream); buf::TestManip manip(fmtstream); @@ -186,12 +180,12 @@ namespace stream::fmt::context { while (fmtstream.is_end_of_string() == false && buf::FMTParamsManip(fmtstream).is_end_of_parameter() == false) { manip.ignore_every_spaces(); - if (access.is_upper_case()) { + if (access.is_upper_case() || access.is_equal_to(':')) { parse_format_data_base(); } else if (!access.is_lower_case()) { parse_format_data_special(); } else { - parse_format_dataCustom(); + parse_format_data_custom(); } buf::FMTParamsManip(fmtstream).param_go_to(','); diff --git a/tests/fmt/specifier.cxx b/tests/fmt/specifier.cxx index 154f49fe..1d82c484 100644 --- a/tests/fmt/specifier.cxx +++ b/tests/fmt/specifier.cxx @@ -27,5 +27,24 @@ SFT_TEST_FUNC(SPECIFIER, BEGIN_END) { TEST_FMT_ARRAY_SPECIFIERS("{:join=' | ', begin='[', end=']', begin=3, size=5}", data, "[3 | 4 | 5 | 6 | 7]"); } + +SFT_TEST_FUNC(SPECIFIER, BEGIN_END_NESTED_SPECS) { + int data[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; + TEST_FMT_ARRAY_SPECIFIERS("{::x}", data, "{ 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9 }"); + + TEST_FMT_ARRAY_SPECIFIERS("{:begin=6, :x}", data, "{ 0x6, 0x7, 0x8, 0x9 }"); + TEST_FMT_ARRAY_SPECIFIERS("{:size=5, :x}", data, "{ 0x0, 0x1, 0x2, 0x3, 0x4 }"); + TEST_FMT_ARRAY_SPECIFIERS("{:begin=3, size=5, :x}", data, "{ 0x3, 0x4, 0x5, 0x6, 0x7 }"); + + TEST_FMT_ARRAY_SPECIFIERS("{:begin='{', begin=3, size=5, :x}", data, "{0x3, 0x4, 0x5, 0x6, 0x7 }"); + TEST_FMT_ARRAY_SPECIFIERS("{:end='}', begin=3, size=5, :x}", data, "{ 0x3, 0x4, 0x5, 0x6, 0x7}"); + TEST_FMT_ARRAY_SPECIFIERS("{:begin='{', end='}', begin=3, size=5, :x}", data, "{0x3, 0x4, 0x5, 0x6, 0x7}"); + TEST_FMT_ARRAY_SPECIFIERS("{:begin='[', end='}', begin=3, size=5, :x}", data, "[0x3, 0x4, 0x5, 0x6, 0x7}"); + TEST_FMT_ARRAY_SPECIFIERS("{:begin='[', end=']', begin=3, size=5, :x}", data, "[0x3, 0x4, 0x5, 0x6, 0x7]"); + + TEST_FMT_ARRAY_SPECIFIERS("{:join=' ', begin='[', end=']', begin=3, size=5, :x}", data, "[0x3 0x4 0x5 0x6 0x7]"); + + TEST_FMT_ARRAY_SPECIFIERS("{:join=' | ', begin='[', end=']', begin=3, size=5, :x}", data, "[0x3 | 0x4 | 0x5 | 0x6 | 0x7]"); +} // NOLINTEND(readability-magic-numbers) // NOLINTEND(misc-const-correctness) From 2d74619f08757ae222085aaa6e8d813d0a6a4431 Mon Sep 17 00:00:00 2001 From: Sacha Bellier Date: Wed, 26 Mar 2025 23:52:57 +0100 Subject: [PATCH 32/42] fix: specs --- src/stream/flog/detail/detail.hxx | 2 +- src/stream/fmt/buf/fmt_read_manip.hxx | 4 +- src/stream/fmt/buf/fmt_write_manip.hxx | 67 +++-- src/stream/fmt/buf/manip.hxx | 4 +- src/stream/fmt/buf/utils/buffer_utils.hxx | 4 +- src/stream/fmt/buf/write_manip.hxx | 41 ++- .../basic_context/basic_args_interface.hxx | 2 +- .../context/basic_context/basic_context.hxx | 99 ++----- .../basic_context_parse_formatdata.hxx | 212 ++++++++++++++ .../basic_context_parse_getindex.hxx | 114 ++++++++ .../basic_context_parse_impl.hxx | 273 +----------------- .../basic_context/text_properties_manager.hxx | 6 +- .../text_properties_manager_impl.hxx | 66 ++--- .../basic_formatter_executor.hxx | 23 +- ...rmat_basics_impl.hxx => format_basics.hxx} | 86 +----- ...ormatter_text_properties_executor_ansi.hxx | 6 +- .../context/formatter_executor/forwarders.hxx | 91 ++++++ .../formatter_executor/std_enumerable.hxx | 98 ------- .../parser_executor/basic_parser_executor.hxx | 8 +- .../fmt/context/utils/context_functions.hxx | 19 -- src/stream/fmt/detail/specifiers.hxx | 4 +- src/stream/fmt/serializers/format_chrono.hxx | 4 +- src/stream/fmt/serializers/format_stdlib.hxx | 6 +- .../fmt/serializers/std_container/tuple.hxx | 7 +- src/stream/json/json_serializer.hxx | 10 +- src/stream/tester/test_suite/test_suite.hxx | 22 +- tests/fmt/specifier.cxx | 22 +- 27 files changed, 612 insertions(+), 688 deletions(-) create mode 100644 src/stream/fmt/context/basic_context/basic_context_parse_formatdata.hxx create mode 100644 src/stream/fmt/context/basic_context/basic_context_parse_getindex.hxx rename src/stream/fmt/context/formatter_executor/{format_basics_impl.hxx => format_basics.hxx} (52%) create mode 100644 src/stream/fmt/context/formatter_executor/forwarders.hxx delete mode 100644 src/stream/fmt/context/formatter_executor/std_enumerable.hxx delete mode 100644 src/stream/fmt/context/utils/context_functions.hxx diff --git a/src/stream/flog/detail/detail.hxx b/src/stream/flog/detail/detail.hxx index aa4a2117..432b6822 100644 --- a/src/stream/flog/detail/detail.hxx +++ b/src/stream/flog/detail/detail.hxx @@ -30,7 +30,7 @@ namespace stream::fmt { template struct FormatterType, FormatterExecutor> { static void format(const stream::flog::AddIndentInFormat& format, FormatterExecutor& executor) { - buf::WriteManip(executor.ostream).fast_write_string_literal("{K:indent}"); + buf::WriteManip(executor.ostream).fast_write_literal("{K:indent}"); return executor.write_type(format.format); } }; diff --git a/src/stream/fmt/buf/fmt_read_manip.hxx b/src/stream/fmt/buf/fmt_read_manip.hxx index c1fb9ece..016b6925 100644 --- a/src/stream/fmt/buf/fmt_read_manip.hxx +++ b/src/stream/fmt/buf/fmt_read_manip.hxx @@ -95,7 +95,7 @@ namespace stream::fmt::buf { public: template - void read_integer_h(T& i, std::uint8_t digitSize, std::optional (&digit_lut)(TChar), TChar base_prefix = '\0', + void read_integer_h(T& i, std::uint8_t digitsize, std::optional (&digit_lut)(TChar), TChar base_prefix = '\0', detail::ShiftInfo shift = detail::ShiftInfo{}) { ShiftReadManip shift_manip(buffer); buf::TestAccess access(buffer); @@ -114,7 +114,7 @@ namespace stream::fmt::buf { T res = (T)0; std::optional get_current = digit_lut(buffer.get()); while (get_current.has_value()) { - res = res << digitSize; + res = res << digitsize; res += get_current.value(); get_current = digit_lut(buffer.get()); Manip(buffer).forward_force(); diff --git a/src/stream/fmt/buf/fmt_write_manip.hxx b/src/stream/fmt/buf/fmt_write_manip.hxx index 9b2c7fa1..a166cd38 100644 --- a/src/stream/fmt/buf/fmt_write_manip.hxx +++ b/src/stream/fmt/buf/fmt_write_manip.hxx @@ -118,18 +118,21 @@ namespace stream::fmt::buf { public: template - void write_integer_h(T i, std::uint8_t digitSize, const TChar* const lut, TChar base_prefix = '\0', detail::ShiftInfo shift = detail::ShiftInfo{}) { + void write_integer_h(T i, std::uint8_t digitsize, const TChar* const lut, TChar base_prefix = '\0', detail::ShiftInfo shift = detail::ShiftInfo{}) { ManipIO manip(buffer); - std::int32_t digit_count = sizeof(T) * 8; - { + std::int32_t digit_count = sizeof(T) * (8 / digitsize); + std::uint8_t mask = (1 << digitsize) - 1; + + if (i != 0) { // Remove leading 0 - std::int32_t last_pos_with_data = 0; - std::int32_t k = digit_count + 1; - T cpyI = i; + std::int32_t last_pos_with_data = digit_count; + std::int32_t k = digit_count; + T cpy_i = i; while (--k != 0) { - if ((cpyI & (0b1 << digitSize)) != 0) last_pos_with_data = k; - cpyI = cpyI >> digitSize; + if ((cpy_i & mask) != 0) + { last_pos_with_data = k; } + cpy_i = cpy_i >> digitsize; } digit_count -= last_pos_with_data; } @@ -139,12 +142,18 @@ namespace stream::fmt::buf { ManipIO(buffer).pushback(base_prefix); } + if (i == 0) + { + ManipIO(buffer).pushback('0'); + return; + } + manip.forward(digit_count); std::int32_t k = digit_count + 1; while (--k != 0) { Manip(buffer).backward_force(); - buffer.set(lut[i & (0b1 << digitSize)]); - i = i >> digitSize; + buffer.set(lut[i & mask]); + i = i >> digitsize; } manip.forward(digit_count); } @@ -192,7 +201,7 @@ namespace stream::fmt::buf { } const CharStr* const end = str; - WriteManip(buffer).fast_write_char_array(begin, end - begin); + WriteManip(buffer).fast_write_sv(std::basic_string_view(begin, end)); if (size > 0 && *str == '\n') { FMTManipIO(buffer).new_line_indent(); @@ -201,40 +210,30 @@ namespace stream::fmt::buf { } } } - template - void write_indent_char_bound(const CharStr* begin, const CharStr* end) { - return write_indent_char_ptr(begin, end - begin); - } - template - void write_indent_string(std::basic_string_view str) { - return write_indent_char_ptr(str.data(), str.size()); + void write_indent_sv(std::basic_string_view sv) { + return write_indent_char_ptr(sv.data(), sv.size()); } - template - void write_char_ptr(const CharStr* str, std::size_t size, detail::ShiftInfo& shift) { - if (shift.size <= 0) return WriteManip(buffer).fast_write_char_array(str, size); + void write_sv(std::basic_string_view sv, detail::ShiftInfo& shift) { + if (shift.size <= 0) { + return WriteManip(buffer).fast_write_sv(sv); + } - if (ManipIO(buffer).reserve(std::max(static_cast(shift.size), size)) == false) throw std::bad_alloc(); + if (ManipIO(buffer).reserve(std::max(static_cast(shift.size), sv.size())) == false) { + throw std::bad_alloc(); + } - if (static_cast(shift.size) > size) { - shift.size -= static_cast(size); + if (static_cast(shift.size) > sv.size()) { + shift.size -= static_cast(sv.size()); ShiftWriteManip(buffer).write_shift_begin(shift); - WriteManip(buffer).fast_write_char_array(str, size); + WriteManip(buffer).fast_write_sv(sv); ShiftWriteManip(buffer).write_shift_end(shift); } else { - WriteManip(buffer).fast_write_char_array(str, size); + WriteManip(buffer).fast_write_sv(sv); } } - template - void write_char_bound(const CharStr* begin, const CharStr* end, detail::ShiftInfo& shift) { - return write_char_ptr(begin, end - begin, shift); - } - template - void write_string(std::basic_string_view str, detail::ShiftInfo& shift) { - return write_char_ptr(str.data(), str.size(), shift); - } }; } // namespace stream::fmt::buf diff --git a/src/stream/fmt/buf/manip.hxx b/src/stream/fmt/buf/manip.hxx index 0d455445..9b840865 100644 --- a/src/stream/fmt/buf/manip.hxx +++ b/src/stream/fmt/buf/manip.hxx @@ -21,11 +21,11 @@ namespace stream::fmt::buf { constexpr inline std::remove_cv_t get_next(const std::size_t count = 1) const { if (Access(buffer).can_move_forward(count) == false) throw std::runtime_error("fmt error: Buffer_OutOfBoundAccess"); - return Manip(buffer).get_next_force(count); + return get_next_force(count); } constexpr inline std::remove_cv_t get_prev(const std::size_t count = 1) const { if (Access(buffer).can_move_backward(count) == false) throw std::runtime_error("fmt error: Buffer_OutOfBoundAccess"); - return Manip(buffer).get_prev_force(count); + return get_prev_force(count); } constexpr inline TChar get_next_force(const std::size_t count = 1) const noexcept { return *(buffer.current_pos + count); diff --git a/src/stream/fmt/buf/utils/buffer_utils.hxx b/src/stream/fmt/buf/utils/buffer_utils.hxx index 836390f7..48e67753 100644 --- a/src/stream/fmt/buf/utils/buffer_utils.hxx +++ b/src/stream/fmt/buf/utils/buffer_utils.hxx @@ -51,7 +51,7 @@ namespace stream::fmt::buf { buf::TestManip(buffer).skip_one_of('"'); while (buffer.is_end_of_string() == false) { auto view = buf::TestManip(buffer).view_until('"', '\\'); - buf::WriteManip(stringOut).fast_write_string(view); + buf::WriteManip(stringOut).fast_write_sv(view); if (buf::TestAccess(buffer).is_equal_to('"')) { break; @@ -84,7 +84,7 @@ namespace stream::fmt::buf { buf::ManipIO(buffer).pushback('"'); while (string_in.is_end_of_string() == false) { auto view = buf::TestManip(string_in).view_until('\\'); - buf::WriteManip(buffer).fast_write_string(view); + buf::WriteManip(buffer).fast_write_sv(view); if (string_in.is_end_of_string()) break; diff --git a/src/stream/fmt/buf/write_manip.hxx b/src/stream/fmt/buf/write_manip.hxx index 46db49af..f3535133 100644 --- a/src/stream/fmt/buf/write_manip.hxx +++ b/src/stream/fmt/buf/write_manip.hxx @@ -8,6 +8,7 @@ #include #include #include +#include namespace stream::fmt::buf { class WriteUtils { @@ -114,39 +115,35 @@ namespace stream::fmt::buf { } public: - template - constexpr void fast_write_char_array(const CharInput* str, std::size_t size) { - if (size == 0) return; + constexpr void fast_write_sv(const std::basic_string_view sv) { + if (sv.size() == 0) { + return; + } - if (ManipIO(buffer).reserve(size) == false) return fast_write_char_array(str, buffer.get_buffer_remaining_size()); + if (ManipIO(buffer).reserve(sv.size()) == false) { + return fast_write_sv(sv.substr(0, buffer.get_buffer_remaining_size())); + } - std::copy_n(str, size, buffer.current_pos); - buffer.current_pos += size; + std::copy(sv.begin(), sv.end(), buffer.current_pos); + buffer.current_pos += sv.size(); } - template - inline constexpr void fast_write_string(std::basic_string_view sv) { - return fast_write_char_array(sv.data(), sv.size()); - } - void fast_write_string(std::basic_string_view sv) { - return fast_write_char_array(sv.data(), sv.size()); - } - template - void fast_write_string_literal(CharInput (&str)[SIZE]) { + + template + void fast_write_literal(const TChar (&str)[SIZE]) { std::size_t size = SIZE; while (str[size - 1] == 0) { --size; } - return fast_write_char_array(str, size); + return fast_write_sv(std::basic_string_view(str, size)); } public: - template - void basic_write_type(std::basic_string_view str) { - return fast_write_string(str); + void basic_write_type(const std::basic_string_view str) { + return fast_write_sv(str); } - template - void basic_write_type(CharInput (&str)[SIZE]) { - return fast_write_string_literal(str); + template + void basic_write_type(const TChar (&str)[SIZE]) { + return fast_write_literal(str); } template requires std::is_integral_v diff --git a/src/stream/fmt/context/basic_context/basic_args_interface.hxx b/src/stream/fmt/context/basic_context/basic_args_interface.hxx index 4d7231a7..9b15f72e 100644 --- a/src/stream/fmt/context/basic_context/basic_args_interface.hxx +++ b/src/stream/fmt/context/basic_context/basic_args_interface.hxx @@ -13,7 +13,7 @@ namespace stream::fmt::context { class BasicContext; template - class context_executor; + class ContextExecutor; } // namespace stream::fmt::context namespace stream::fmt::detail { diff --git a/src/stream/fmt/context/basic_context/basic_context.hxx b/src/stream/fmt/context/basic_context/basic_context.hxx index 6bd7481c..8782abc6 100644 --- a/src/stream/fmt/context/basic_context/basic_context.hxx +++ b/src/stream/fmt/context/basic_context/basic_context.hxx @@ -18,19 +18,26 @@ namespace stream::fmt::context { template class BasicContext; - template - class context_executor { + template + class ContextExecutor { + public: + using TChar = CharType; + public: - context_executor(detail::ITextPropertiesExecutor& text_properties_executor) : data{}, text_manager{text_properties_executor} {} - virtual ~context_executor() = default; + ContextExecutor(detail::ITextPropertiesExecutor& text_properties_executor) : data{}, text_manager{text_properties_executor} {} + virtual ~ContextExecutor() = default; public: virtual void exec_settings() = 0; virtual void exec_raw_string(std::basic_string_view) = 0; + BasicContext& get_context() { return *reinterpret_cast*>(context); } + public: detail::FormatData data; detail::TextPropertiesManager text_manager; + + void* context = nullptr; }; template @@ -39,60 +46,41 @@ namespace stream::fmt::context { using TChar = CharType; public: - BasicContext(context_executor& executor, buf::StreamView fmtstream, detail::BasicArgsInterface& args_interface); - virtual ~BasicContext() = default; + BasicContext(ContextExecutor& executor, buf::StreamView fmtstream, detail::BasicArgsInterface& args_interface); + virtual ~BasicContext(); public: - context_executor& executor; + ContextExecutor& executor; buf::StreamView fmtstream; detail::BasicArgsInterface& args_interface; std::int32_t values_index; - public: - void run(); - private: - std::optional get_format_index_number(); - std::optional get_format_index_name(); - std::optional get_format_index_sub_index(); + void* old_context_attached = nullptr; public: - std::optional get_format_index(); - template - T format_read_parameter(const T& default_value); - - protected: - void formatdata_apply_next_override(); + void run(); protected: - std::basic_string_view parse_next_override_format_data(); - - void parse_format_data_base(); - void parse_format_data_special(); - void parse_format_data_special_shift_type(const detail::ShiftInfo::ShiftType type); - void parse_format_data_custom(); - void parse_format_data(); - void parse_variable(std::int32_t format_idx); void parse(); - - public: - template - inline void ExecNextFormatData(Func&& func, Args&&... args) { - if (executor.data.next_override.size() == 0) return func(std::forward(args)...); - detail::FormatData format_data_copy = executor.data; - formatdata_apply_next_override(); - func(std::forward(args)...); - executor.data = format_data_copy; - } }; } // namespace stream::fmt::context namespace stream::fmt::context { template - BasicContext::BasicContext(context_executor& executor, buf::StreamView format, detail::BasicArgsInterface& args_interface) - : executor(executor), fmtstream{format}, args_interface{args_interface}, values_index{0} {} + BasicContext::BasicContext(ContextExecutor& executor, buf::StreamView format, detail::BasicArgsInterface& args_interface) + : executor(executor), fmtstream{format}, args_interface{args_interface}, values_index{0} { + old_context_attached = executor.context; + executor.context = this; + } + + template + BasicContext::~BasicContext() + { + executor.context = old_context_attached; + } template void BasicContext::run() { @@ -110,39 +98,6 @@ namespace stream::fmt::context { } } } - - template - void BasicContext::formatdata_apply_next_override() { - if (executor.data.next_override.size() == 0) { - return; - } - - buf::StreamView overridePos(executor.data.next_override); - buf::StreamView format_pos = fmtstream; - fmtstream = overridePos; - parse_format_data(); - fmtstream = format_pos; - } - - template - template - T BasicContext::format_read_parameter(const T& default_value) { - if (!buf::TestAccess(fmtstream).is_equal_to('{')) { - T t; - buf::ReadManip(fmtstream).fast_read_integer(t); - return t; - } - - // SubIndex - buf::TestManip(fmtstream).skip_one_of('{'); - std::optional format_idx = get_format_index(); - if constexpr (std::is_convertible_v) - return args_interface.get_int_at(format_idx.value()); - else if constexpr (std::is_convertible_v>) - return args_interface.get_string_at(format_idx.value()); - - throw std::runtime_error("fmt error: Context_ArgumentIndexExpected"); - } } // namespace stream::fmt::context #include "basic_context_parse_impl.hxx" diff --git a/src/stream/fmt/context/basic_context/basic_context_parse_formatdata.hxx b/src/stream/fmt/context/basic_context/basic_context_parse_formatdata.hxx new file mode 100644 index 00000000..df09c53c --- /dev/null +++ b/src/stream/fmt/context/basic_context/basic_context_parse_formatdata.hxx @@ -0,0 +1,212 @@ +#pragma once + +#include "basic_context.hxx" + +#include "stream/fmt/buf/manip.hxx" +#include "stream/fmt/buf/test_manip.hxx" +#include "stream/fmt/buf/write_manip.hxx" +#include "stream/fmt/buf/read_manip.hxx" +#include "stream/fmt/buf/fmt_manip_io.hxx" +#include "stream/fmt/buf/fmt_read_manip.hxx" + +#include "basic_context_parse_getindex.hxx" + +namespace stream::fmt::detail { + namespace { + template + std::basic_string_view parse_next_override_format_data(Executor& executor, buf::StreamView& stream, detail::FormatData& data) { + buf::TestAccess access(stream); + buf::TestManip manip(stream); + + manip.is_equal_to_forward(':'); + manip.ignore_every_spaces(); + + const typename Executor::TChar* begin = stream.current_pos; + int scopes = 0; + while (buf::FMTParamsManip(stream).is_end_of_parameter() == false || scopes > 0) { + manip.GoTo('\'', '}', '{'); + if (access.is_equal_to('\'')) { + buf::Manip(stream).forward(); + manip.go_to_forward('\''); + } else if (access.is_equal_to('{')) { + buf::Manip(stream).forward(); + scopes++; + } else if (scopes > 0 && access.is_equal_to('}')) { + buf::Manip(stream).forward(); + scopes--; + } + } + const typename Executor::TChar* end = stream.current_pos; + return std::basic_string_view(begin, end - begin); + } + + template + void parse_format_data_base(Executor& executor, buf::StreamView& stream, detail::FormatData& data) { + buf::TestAccess access(stream); + + if (access.is_equal_to('C')) { + buf::Manip(stream).forward(); + executor.text_manager.parse_color(executor.get_context(), stream); + } else if (access.is_equal_to('S')) { + buf::Manip(stream).forward(); + executor.text_manager.parse_style(executor.get_context(), stream); + buf::Manip(stream).forward(); + } else if (access.is_equal_to('F')) { + executor.text_manager.parse_front(executor.get_context(), stream); + } + + else if (access.is_equal_to('K')) { + buf::Manip(stream).forward(); + data.keep_new_style = true; + } + } + + template + void parse_format_data_special_shift_type(Executor& executor, buf::StreamView& stream, detail::FormatData& data, const detail::ShiftInfo::ShiftType type) { + data.shift.type = type; + data.shift.size = format_read_parameter(executor, stream, -1); + if (buf::TestAccess(stream).is_equal_to(':')) { + buf::Manip(stream).forward(); + data.shift.print.before = stream.get(); + data.shift.print.after = data.shift.print.before; + buf::Manip(stream).forward(); + if (buf::TestAccess(stream).is_equal_to('|')) { + buf::Manip(stream).forward(); + data.shift.print.after = stream.get(); + buf::Manip(stream).forward(); + } + } + } + + template + bool parse_format_data_special(Executor& executor, buf::StreamView& stream, detail::FormatData& data) { + buf::TestAccess access(stream); + buf::TestManip manip(stream); + + bool local_spec = false; + + if (access.is_equal_to('{')) { + local_spec = true; + buf::Manip(stream).forward(); + std::optional format_index = get_format_index(executor, stream); + + bool ableToapply = false; + if (format_index.has_value()) { + auto applyFormatData = executor.get_context().args_interface.template get_type_at>(format_index.value()); + ableToapply |= data.testapply(applyFormatData); + auto applyFormatSpecifier = executor.get_context().args_interface.template get_type_at>(format_index.value()); + ableToapply |= data.testapply(applyFormatSpecifier); + auto applyIntegerPrintBase = executor.get_context().args_interface.template get_type_at(format_index.value()); + ableToapply |= data.testapply(applyIntegerPrintBase); + auto applyShiftInfo = executor.get_context().args_interface.template get_type_at(format_index.value()); + ableToapply |= data.testapply(applyShiftInfo); + } + + if (not ableToapply) { + throw std::runtime_error("fmt error: Context_CannotapplyType"); + } + manip.skip_one_of('}'); + } + + if (access.is_equal_to('#')) { + local_spec = true; + buf::Manip(stream).forward(); + data.prefix_suffix = true; + } + + bool is_integer_spec = access.is_equal_to('d', 'b', 'b', 'o', 'O', 'x', 'X'); + is_integer_spec = is_integer_spec && (stream.get_buffer_remaining_size() == 1 || (buf::Access(stream).get_next() > 'z' && buf::Access(stream).get_next() < 'a')); + if (is_integer_spec) { + local_spec = true; + data.integer_print = static_cast(stream.get()); + buf::Manip(stream).forward(); + } + + if (access.is_equal_to('.')) { + local_spec = true; + buf::Manip(stream).forward(); + data.float_precision = format_read_parameter(executor, stream, -1); + } + + if (access.is_equal_to('>')) { + local_spec = true; + buf::Manip(stream).forward(); + parse_format_data_special_shift_type(executor, stream, data, detail::ShiftInfo::ShiftType::Right); + } else if (access.is_equal_to('<')) { + buf::Manip(stream).forward(); + parse_format_data_special_shift_type(executor, stream, data, detail::ShiftInfo::ShiftType::Left); + } else if (access.is_equal_to('^')) { + buf::Manip(stream).forward(); + if (access.is_equal_to('<')) { + buf::Manip(stream).forward(); + parse_format_data_special_shift_type(executor, stream, data, detail::ShiftInfo::ShiftType::CenterLeft); + } else { + manip.ignore_one_of('>'); + parse_format_data_special_shift_type(executor, stream, data, detail::ShiftInfo::ShiftType::CenterRight); + } + } + + if (access.is_equal_to(':')) { + local_spec = true; + buf::Manip(stream).forward(); + data.next_override = parse_next_override_format_data(executor, stream, data); + } + + return local_spec; + } + + template + void parse_format_data_custom(Executor& executor, buf::StreamView& stream, detail::FormatData& data) { + buf::TestAccess access(stream); + buf::TestManip manip(stream); + + std::basic_string_view name = manip.view_exec([&] { buf::FMTParamsManip(stream).param_go_to(' ', '=', '\'', '{', ','); }); + buf::FMTParamsManip(stream).param_go_to('=', '\'', '{', ','); + manip.ignore_one_of('='); + manip.ignore_every_spaces(); + + if (access.is_equal_to('\'')) { + buf::Manip(stream).forward(); + std::basic_string_view value = buf::TestManip(stream).view_until('\''); + data.specifiers.concat(detail::FormatSpecifier{name, value}); + buf::Manip(stream).forward(); + } else if (access.is_a_digit()) { + std::int32_t value = 0; + buf::ReadManip(stream).fast_read_integer(value); + data.specifiers.concat(detail::FormatSpecifier{name, value}); + } else if (access.is_equal_to('{')) { + buf::Manip(stream).forward(); + std::optional idx = get_format_index(executor, stream); + // TODO / FIXME + // data.specifiers.concat(detail::FormatSpecifier{name, GetTypeAtIndexAuto(idx)}); + manip.skip_one_of('}'); + } else if (access.is_equal_to(',', '}')) { + data.specifiers.concat(detail::FormatSpecifier{name}); + } + } + } + + template + detail::FormatData parse_format_data(Executor& executor, buf::StreamView& stream) { + detail::FormatData data; + + buf::TestAccess access(stream); + + data.has_spec = true; + while (stream.is_end_of_string() == false && buf::FMTParamsManip(stream).is_end_of_parameter() == false) { + buf::TestManip(stream).ignore_every_spaces(); + + if (access.is_upper_case()) { + parse_format_data_base(executor, stream, data); + } else if (parse_format_data_special(executor, stream, data)) { + } else { + parse_format_data_custom(executor, stream, data); + } + + buf::FMTParamsManip(stream).param_go_to(','); + buf::TestManip(stream).ignore_one_of(','); + } + + return data; + } +} // namespace stream::fmt::context diff --git a/src/stream/fmt/context/basic_context/basic_context_parse_getindex.hxx b/src/stream/fmt/context/basic_context/basic_context_parse_getindex.hxx new file mode 100644 index 00000000..da358622 --- /dev/null +++ b/src/stream/fmt/context/basic_context/basic_context_parse_getindex.hxx @@ -0,0 +1,114 @@ +#pragma once + +#include "basic_context.hxx" + +#include "stream/fmt/buf/manip.hxx" +#include "stream/fmt/buf/test_manip.hxx" +#include "stream/fmt/buf/write_manip.hxx" +#include "stream/fmt/buf/read_manip.hxx" +#include "stream/fmt/buf/fmt_manip_io.hxx" +#include "stream/fmt/buf/fmt_read_manip.hxx" + +namespace stream::fmt::context { + namespace { + template + std::optional get_format_index_number(Executor& executor, buf::StreamView& stream) { + std::int32_t index = -1; + buf::ReadManip(stream).fast_read_integer(index); + if (buf::TestAccess(stream).is_equal_to(':') || buf::TestAccess(stream).is_equal_to('}')) { + if (index >= 0 && index < executor.get_context().args_interface.size()) { + return index; + } + } + return std::nullopt; + } + template + std::optional get_format_index_name(Executor& executor, buf::StreamView& stream) { + std::optional index = executor.get_context().args_interface.get_index_of_current_named_arg(stream); + if (index.has_value() == false) return std::nullopt; + if (buf::TestAccess(stream).is_equal_to(':') || buf::TestAccess(stream).is_equal_to('}')) { + if (index >= 0 && index < executor.get_context().args_interface.size()) { + return index; + } + } + return std::nullopt; + } + template + std::optional get_format_index_sub_index(Executor& executor, buf::StreamView& stream) { + buf::TestAccess access(stream); + buf::TestManip manip(stream); + + if (access.is_equal_to('{')) { + buf::Manip(stream).forward(); + std::optional rec_index = get_format_index(executor, stream); + if (rec_index.has_value() == false) { + return std::nullopt; + } + if (access.is_equal_to('}') && rec_index >= 0 && rec_index < executor.get_context().args_interface.size()) { + buf::Manip(stream).forward(); + manip.ignore_every_spaces(); + if (access.is_equal_to(':', '}')) { + std::int32_t final_rec_index = (std::int32_t)executor.get_context().args_interface.get_int_at(rec_index.value()); + if (final_rec_index >= 0 && final_rec_index < executor.get_context().args_interface.size()) { + return final_rec_index; + } + } + } + } + return std::nullopt; + } + } + + template + std::optional get_format_index(Executor& executor, buf::StreamView& stream) { + buf::TestAccess access(stream); + + // I : if there is no number specified : ':' or '}' + if (access.is_equal_to(':') || access.is_equal_to('}')) + if (executor.get_context().values_index < executor.get_context().args_interface.size()) { + return executor.get_context().values_index++; + } + + // II: A number(idx) + if (access.is_a_digit()) { + return get_format_index_number(executor, stream); + } + + // III : A name + if (access.is_lower_case() || access.is_upper_case()) { + return get_format_index_name(executor, stream); + } + + // VI : { which is a idx to an argument + if (access.is_equal_to('{')) { + const typename Executor::TChar* oldPos = stream.current_pos; + std::optional res = get_format_index_sub_index(executor, stream); + if (res.has_value() == false) { + stream.current_pos = oldPos; + return std::nullopt; + } + return res; + } + + return std::nullopt; + } + + template + T format_read_parameter(Executor& executor, buf::StreamView& stream, const T& default_value) { + if (!buf::TestAccess(stream).is_equal_to('{')) { + T t; + buf::ReadManip(stream).fast_read_integer(t); + return t; + } + + // SubIndex + buf::TestManip(stream).skip_one_of('{'); + std::optional format_idx = get_format_index(executor, stream); + if constexpr (std::is_convertible_v) + { return executor.get_context().args_interface.get_int_at(format_idx.value()); } + else if constexpr (std::is_convertible_v>) + { return executor.get_context().args_interface.get_string_at(format_idx.value()); } + + throw std::runtime_error("fmt error: Context_ArgumentIndexExpected"); + } +} // namespace stream::fmt::context diff --git a/src/stream/fmt/context/basic_context/basic_context_parse_impl.hxx b/src/stream/fmt/context/basic_context/basic_context_parse_impl.hxx index 0f6f9120..f7e8e896 100644 --- a/src/stream/fmt/context/basic_context/basic_context_parse_impl.hxx +++ b/src/stream/fmt/context/basic_context/basic_context_parse_impl.hxx @@ -9,272 +9,9 @@ #include "stream/fmt/buf/fmt_manip_io.hxx" #include "stream/fmt/buf/fmt_read_manip.hxx" -namespace stream::fmt::context { - template - std::basic_string_view BasicContext::parse_next_override_format_data() { - // TODO: check that function - buf::TestAccess access(fmtstream); - buf::TestManip manip(fmtstream); - - manip.is_equal_to_forward(':'); - manip.ignore_every_spaces(); - - const TChar* begin = fmtstream.current_pos; - int scopes = 0; - while (buf::FMTParamsManip(fmtstream).is_end_of_parameter() == false || scopes > 0) { - manip.GoTo('\'', '}', '{'); - if (access.is_equal_to('\'')) { - buf::Manip(fmtstream).forward(); - manip.go_to_forward('\''); - } else if (access.is_equal_to('{')) { - buf::Manip(fmtstream).forward(); - scopes++; - } else if (scopes > 0 && access.is_equal_to('}')) { - buf::Manip(fmtstream).forward(); - scopes--; - } - } - const TChar* end = fmtstream.current_pos; - return std::basic_string_view(begin, end - begin); - } - - template - void BasicContext::parse_format_data_base() { - buf::TestAccess access(fmtstream); - - if (access.is_equal_to('C')) { - buf::Manip(fmtstream).forward(); - executor.text_manager.parse_color(*this); - } else if (access.is_equal_to('S')) { - buf::Manip(fmtstream).forward(); - executor.text_manager.parse_style(*this); - } else if (access.is_equal_to('F')) { - buf::Manip(fmtstream).forward(); - executor.text_manager.parse_front(*this); - } - - else if (access.is_equal_to('K')) { - buf::Manip(fmtstream).forward(); - executor.data.keep_new_style = true; - } - - else if (access.is_equal_to(':')) { - buf::Manip(fmtstream).forward(); - executor.data.next_override = parse_next_override_format_data(); - } - } - - template - void BasicContext::parse_format_data_special_shift_type(const detail::ShiftInfo::ShiftType type) { - executor.data.shift.type = type; - executor.data.shift.size = format_read_parameter(-1); - if (buf::TestAccess(fmtstream).is_equal_to(':')) { - buf::Manip(fmtstream).forward(); - executor.data.shift.print.before = fmtstream.get(); - executor.data.shift.print.after = executor.data.shift.print.before; - buf::Manip(fmtstream).forward(); - if (buf::TestAccess(fmtstream).is_equal_to('|')) { - buf::Manip(fmtstream).forward(); - executor.data.shift.print.after = fmtstream.get(); - buf::Manip(fmtstream).forward(); - } - } - } - - template - void BasicContext::parse_format_data_special() { - buf::TestAccess access(fmtstream); - buf::TestManip manip(fmtstream); - - if (access.is_equal_to('{')) { - buf::Manip(fmtstream).forward(); - std::optional format_index = get_format_index(); - - bool ableToapply = false; - if (format_index.has_value()) { - auto applyFormatData = args_interface.template get_type_at>(format_index.value()); - ableToapply |= executor.data.testapply(applyFormatData); - auto applyFormatSpecifier = args_interface.template get_type_at>(format_index.value()); - ableToapply |= executor.data.testapply(applyFormatSpecifier); - auto applyIntegerPrintBase = args_interface.template get_type_at(format_index.value()); - ableToapply |= executor.data.testapply(applyIntegerPrintBase); - auto applyShiftInfo = args_interface.template get_type_at(format_index.value()); - ableToapply |= executor.data.testapply(applyShiftInfo); - } - - if (not ableToapply) { - throw std::runtime_error("fmt error: Context_CannotapplyType"); - } - manip.skip_one_of('}'); - } - - else if (access.is_equal_to('.')) { - buf::Manip(fmtstream).forward(); - executor.data.float_precision = format_read_parameter(-1); - } - - else if (access.is_equal_to('d', 'b', 'b', 'o', 'O', 'x', 'X')) { - executor.data.integer_print = static_cast(fmtstream.get()); - buf::Manip(fmtstream).forward(); - } - - else if (access.is_equal_to('#')) { - buf::Manip(fmtstream).forward(); - executor.data.prefix_suffix = true; - } - - else if (access.is_equal_to('>')) { - buf::Manip(fmtstream).forward(); - parse_format_data_special_shift_type(detail::ShiftInfo::ShiftType::Right); - } else if (access.is_equal_to('<')) { - buf::Manip(fmtstream).forward(); - parse_format_data_special_shift_type(detail::ShiftInfo::ShiftType::Left); - } else if (access.is_equal_to('^')) { - buf::Manip(fmtstream).forward(); - if (access.is_equal_to('<')) { - buf::Manip(fmtstream).forward(); - parse_format_data_special_shift_type(detail::ShiftInfo::ShiftType::CenterLeft); - } else { - manip.ignore_one_of('>'); - parse_format_data_special_shift_type(detail::ShiftInfo::ShiftType::CenterRight); - } - } - } - - template - void BasicContext::parse_format_data_custom() { - buf::TestAccess access(fmtstream); - buf::TestManip manip(fmtstream); - - std::basic_string_view name = manip.view_exec([&] { buf::FMTParamsManip(fmtstream).param_go_to(' ', '=', '\'', '{', ','); }); - buf::FMTParamsManip(fmtstream).param_go_to('=', '\'', '{', ','); - manip.ignore_one_of('='); - manip.ignore_every_spaces(); - - if (access.is_equal_to('\'')) { - buf::Manip(fmtstream).forward(); - std::basic_string_view value = buf::TestManip(fmtstream).view_until('\''); - executor.data.specifiers.concat(detail::FormatSpecifier{name, value}); - } else if (access.is_a_digit()) { - std::int32_t value = 0; - buf::ReadManip(fmtstream).fast_read_integer(value); - executor.data.specifiers.concat(detail::FormatSpecifier{name, value}); - } else if (access.is_equal_to('{')) { - buf::Manip(fmtstream).forward(); - std::optional idx = get_format_index(); - // TODO / FIXME - // executor.data.specifiers.concat(detail::FormatSpecifier{name, GetTypeAtIndexAuto(idx)}); - manip.skip_one_of('}'); - } else if (access.is_equal_to(',', '}')) { - executor.data.specifiers.concat(detail::FormatSpecifier{name}); - } - } - - /////---------- Impl ----------///// - template - void BasicContext::parse_format_data() { - buf::TestAccess access(fmtstream); - buf::TestManip manip(fmtstream); - - executor.data.has_spec = true; - while (fmtstream.is_end_of_string() == false && buf::FMTParamsManip(fmtstream).is_end_of_parameter() == false) { - manip.ignore_every_spaces(); - - if (access.is_upper_case() || access.is_equal_to(':')) { - parse_format_data_base(); - } else if (!access.is_lower_case()) { - parse_format_data_special(); - } else { - parse_format_data_custom(); - } - - buf::FMTParamsManip(fmtstream).param_go_to(','); - buf::TestManip(fmtstream).ignore_one_of(','); - } - } - - - template - std::optional BasicContext::get_format_index_number() { - std::int32_t index = -1; - buf::ReadManip(fmtstream).fast_read_integer(index); - if (buf::TestAccess(fmtstream).is_equal_to(':') || buf::TestAccess(fmtstream).is_equal_to('}')) { - if (index >= 0 && index < args_interface.size()) { - return index; - } - } - return std::nullopt; - } - template - std::optional BasicContext::get_format_index_name() { - std::optional index = args_interface.get_index_of_current_named_arg(fmtstream); - if (index.has_value() == false) return std::nullopt; - if (buf::TestAccess(fmtstream).is_equal_to(':') || buf::TestAccess(fmtstream).is_equal_to('}')) { - if (index >= 0 && index < args_interface.size()) { - return index; - } - } - return std::nullopt; - } - template - std::optional BasicContext::get_format_index_sub_index() { - buf::TestAccess access(fmtstream); - buf::TestManip manip(fmtstream); - - if (access.is_equal_to('{')) { - buf::Manip(fmtstream).forward(); - std::optional rec_index = get_format_index(); - if (rec_index.has_value() == false) { - return std::nullopt; - } - if (access.is_equal_to('}') && rec_index >= 0 && rec_index < args_interface.size()) { - buf::Manip(fmtstream).forward(); - manip.ignore_every_spaces(); - if (access.is_equal_to(':', '}')) { - std::int32_t final_rec_index = (std::int32_t)args_interface.get_int_at(rec_index.value()); - if (final_rec_index >= 0 && final_rec_index < args_interface.size()) { - return final_rec_index; - } - } - } - } - return std::nullopt; - } - - template - std::optional BasicContext::get_format_index() { - buf::TestAccess access(fmtstream); - - // I : if there is no number specified : ':' or '}' - if (access.is_equal_to(':') || access.is_equal_to('}')) - if (values_index < args_interface.size()) { - return values_index++; - } - - // II: A number(idx) - if (access.is_a_digit()) { - return get_format_index_number(); - } - - // III : A name - if (access.is_lower_case() || access.is_upper_case()) { - return get_format_index_name(); - } - - // VI : { which is a idx to an argument - if (access.is_equal_to('{')) { - const TChar* oldPos = fmtstream.current_pos; - std::optional res = get_format_index_sub_index(); - if (res.has_value() == false) { - fmtstream.current_pos = oldPos; - return std::nullopt; - } - return res; - } - - return std::nullopt; - } +#include "basic_context_parse_formatdata.hxx" +namespace stream::fmt::context { template void BasicContext::parse_variable(std::int32_t format_idx) { detail::FormatData saveFormatData = executor.data; @@ -283,7 +20,7 @@ namespace stream::fmt::context { if (buf::TestAccess(fmtstream).is_equal_to(':', '{')) { buf::Manip(fmtstream).forward(); - parse_format_data(); + executor.data = detail::parse_format_data(executor, fmtstream); } args_interface.run_type_at(format_idx); @@ -300,11 +37,11 @@ namespace stream::fmt::context { buf::Manip(fmtstream).forward(); // Ignore { if (buf::TestAccess(fmtstream).is_upper_case()) { - parse_format_data(); + executor.data = detail::parse_format_data(executor, fmtstream); return buf::FMTParamsManip(fmtstream).param_go_to_forward(); // Ignore } } - std::optional format_idx = get_format_index(); + std::optional format_idx = get_format_index(executor, fmtstream); if (format_idx.has_value()) { if (format_idx >= 0 && format_idx < args_interface.size()) { parse_variable(format_idx.value()); diff --git a/src/stream/fmt/context/basic_context/text_properties_manager.hxx b/src/stream/fmt/context/basic_context/text_properties_manager.hxx index 011f343c..d2898c24 100644 --- a/src/stream/fmt/context/basic_context/text_properties_manager.hxx +++ b/src/stream/fmt/context/basic_context/text_properties_manager.hxx @@ -172,9 +172,9 @@ namespace stream::fmt::detail { void apply_front_on_index(context::BasicContext& context, std::int32_t index); public: - void parse_color(context::BasicContext& context); - void parse_style(context::BasicContext& context); - void parse_front(context::BasicContext& context); + void parse_color(context::BasicContext& context, buf::StreamView& stream); + void parse_style(context::BasicContext& context, buf::StreamView& stream); + void parse_front(context::BasicContext& context, buf::StreamView& stream); private: std::optional get_color_code(buf::StreamView& format, std::size_t base, std::size_t brightbase); diff --git a/src/stream/fmt/context/basic_context/text_properties_manager_impl.hxx b/src/stream/fmt/context/basic_context/text_properties_manager_impl.hxx index 06ed5161..7194b5f7 100644 --- a/src/stream/fmt/context/basic_context/text_properties_manager_impl.hxx +++ b/src/stream/fmt/context/basic_context/text_properties_manager_impl.hxx @@ -61,25 +61,25 @@ namespace stream::fmt::detail { } template - void detail::TextPropertiesManager::parse_color(context::BasicContext& context) { - if (buf::TestAccess(context.fmtstream).is_equal_to(':')) { - buf::Manip(context.fmtstream).forward(); - buf::TestManip(context.fmtstream).ignore_every_spaces(); - if (buf::TestAccess(context.fmtstream).is_equal_to('{')) { - buf::Manip(context.fmtstream).forward(); - std::optional idx = context.get_format_index(); + void detail::TextPropertiesManager::parse_color(context::BasicContext& context, buf::StreamView& stream) { + if (buf::TestAccess(stream).is_equal_to(':')) { + buf::Manip(stream).forward(); + buf::TestManip(stream).ignore_every_spaces(); + if (buf::TestAccess(stream).is_equal_to('{')) { + buf::Manip(stream).forward(); + std::optional idx = get_format_index(context.executor, stream); if (idx.has_value() == false) { } apply_color_on_index(context, idx.value()); - buf::TestManip(context.fmtstream).skip_one_of('}'); + buf::TestManip(stream).skip_one_of('}'); } else { - std::optional color_fg = get_color_code(context.fmtstream, static_cast(TextProperties::TextColor::BasicColorFG::BaseStep), + std::optional color_fg = get_color_code(stream, static_cast(TextProperties::TextColor::BasicColorFG::BaseStep), static_cast(TextProperties::TextColor::BasicColorFG::BaseBrightStep)); - buf::FMTParamsManip(context.fmtstream).param_go_to('-', ','); - if (buf::TestAccess(context.fmtstream).is_equal_to('-')) { - buf::Manip(context.fmtstream).forward(); - buf::TestManip(context.fmtstream).ignore_every_spaces(); - std::optional color_bg = get_color_code(context.fmtstream, static_cast(TextProperties::TextColor::BasicColorBG::BaseStep), + buf::FMTParamsManip(stream).param_go_to('-', ','); + if (buf::TestAccess(stream).is_equal_to('-')) { + buf::Manip(stream).forward(); + buf::TestManip(stream).ignore_every_spaces(); + std::optional color_bg = get_color_code(stream, static_cast(TextProperties::TextColor::BasicColorBG::BaseStep), static_cast(TextProperties::TextColor::BasicColorBG::BaseBrightStep)); if (color_bg.has_value() && color_fg.has_value()) { return ask_apply_color(detail::TextProperties::TextColor::BasicColor{static_cast(color_fg.value()), @@ -101,25 +101,25 @@ namespace stream::fmt::detail { } template - void detail::TextPropertiesManager::parse_style(context::BasicContext& context) { - if (buf::TestAccess(context.fmtstream).is_equal_to(':')) { - buf::Manip(context.fmtstream).forward(); - if (!buf::TestAccess(context.fmtstream).is_equal_to('}', ',')) { + void detail::TextPropertiesManager::parse_style(context::BasicContext& context, buf::StreamView& stream) { + if (buf::TestAccess(stream).is_equal_to(':')) { + buf::Manip(stream).forward(); + if (!buf::TestAccess(stream).is_equal_to('}', ',')) { bool loop = true; while (loop) { - buf::TestManip(context.fmtstream).ignore_every_spaces(); - if (buf::TestAccess(context.fmtstream).is_equal_to('{')) { - buf::Manip(context.fmtstream).forward(); - std::optional idx = context.get_format_index(); + buf::TestManip(stream).ignore_every_spaces(); + if (buf::TestAccess(stream).is_equal_to('{')) { + buf::Manip(stream).forward(); + std::optional idx = get_format_index(context.executor, stream); apply_style_on_index(context, idx.value()); - buf::TestManip(context.fmtstream).skip_one_of('}'); + buf::TestManip(stream).skip_one_of('}'); } else { - parse_style_named(context.fmtstream); + parse_style_named(stream); } - buf::FMTParamsManip(context.fmtstream).param_go_to('|', ','); - loop = buf::TestAccess(context.fmtstream).is_equal_to('|'); - buf::Manip(context.fmtstream).forward(); - buf::TestManip(context.fmtstream).ignore_every_spaces(); + buf::FMTParamsManip(stream).param_go_to('|', ','); + loop = buf::TestAccess(stream).is_equal_to('|'); + buf::Manip(stream).forward(); + buf::TestManip(stream).ignore_every_spaces(); } } else { return reload_default_style(); @@ -209,14 +209,14 @@ namespace stream::fmt::detail { } template - void detail::TextPropertiesManager::parse_front(context::BasicContext& context) { + void detail::TextPropertiesManager::parse_front(context::BasicContext& context, buf::StreamView& stream) { static constexpr std::string_view frontCode[] = {"default", "front0", "front1", "front2", "front3", "front4", "front5", "front6", "front7", "front8", "front9"}; - if (buf::TestAccess(context.fmtstream).is_equal_to(':')) { - buf::Manip(context.fmtstream).forward(); - buf::TestManip(context.fmtstream).ignore_every_spaces(); + if (buf::TestAccess(stream).is_equal_to(':')) { + buf::Manip(stream).forward(); + buf::TestManip(stream).ignore_every_spaces(); - std::optional front_id = buf::UtilsManip(context.fmtstream).get_word_from_list(frontCode); + std::optional front_id = buf::UtilsManip(stream).get_word_from_list(frontCode); if (front_id.has_value()) { apply_front(static_cast(front_id.value())); diff --git a/src/stream/fmt/context/formatter_executor/basic_formatter_executor.hxx b/src/stream/fmt/context/formatter_executor/basic_formatter_executor.hxx index 79d7c09d..12659400 100644 --- a/src/stream/fmt/context/formatter_executor/basic_formatter_executor.hxx +++ b/src/stream/fmt/context/formatter_executor/basic_formatter_executor.hxx @@ -8,9 +8,9 @@ #include "formatter_type.hxx" #include "index_args.hxx" #include "named_args.hxx" -#include "std_enumerable.hxx" #include "formatter_args.hxx" +#include "forwarders.hxx" namespace stream::fmt::context { enum class EndOfStringCharMode { @@ -19,7 +19,7 @@ namespace stream::fmt::context { }; template - class BasicFormatterExecutor : public context_executor { + class BasicFormatterExecutor : public ContextExecutor { public: using TChar = CharType; @@ -31,17 +31,17 @@ namespace stream::fmt::context { ~BasicFormatterExecutor() override = default; void terminate(); - + public: buf::FMTStreamIO& ostream; EndOfStringCharMode end_of_string_char = EndOfStringCharMode::Optional; - using context_executor::data; - using context_executor::text_manager; + using ContextExecutor::data; + using ContextExecutor::text_manager; protected: void exec_raw_string(std::basic_string_view sv) override { - return buf::WriteManip(ostream).fast_write_string(sv); + return buf::WriteManip(ostream).fast_write_sv(sv); } void exec_settings() override; @@ -52,9 +52,14 @@ namespace stream::fmt::context { void run(Format&& format, Args&&... args); public: + template + void write_type(Type&& type) + { + FormatterType>::type, M_Type>::format(std::forward(type), *this); + } template void write_type(Type&& type, Rest&&... rest) { - FormatterType>::type, M_Type>::format(std::forward(type), *this); + write_type(std::forward(type)); if constexpr (sizeof...(rest) > 0) { write_type(std::forward(rest)...); } @@ -65,7 +70,7 @@ namespace stream::fmt::context { namespace stream::fmt::context { template BasicFormatterExecutor::BasicFormatterExecutor(buf::FMTStreamIO& ostream_, detail::ITextPropertiesExecutor& text_properties_executor_) - : context_executor(text_properties_executor_), ostream(ostream_) { + : ContextExecutor(text_properties_executor_), ostream(ostream_) { text_properties_executor_.link_to_executor(this); } @@ -108,5 +113,5 @@ namespace stream::fmt::context { } } // namespace stream::fmt::context -#include "format_basics_impl.hxx" +#include "format_basics.hxx" #include "format_text_properties_impl.hxx" diff --git a/src/stream/fmt/context/formatter_executor/format_basics_impl.hxx b/src/stream/fmt/context/formatter_executor/format_basics.hxx similarity index 52% rename from src/stream/fmt/context/formatter_executor/format_basics_impl.hxx rename to src/stream/fmt/context/formatter_executor/format_basics.hxx index dbf960df..3189604f 100644 --- a/src/stream/fmt/context/formatter_executor/format_basics_impl.hxx +++ b/src/stream/fmt/context/formatter_executor/format_basics.hxx @@ -4,6 +4,8 @@ #include "stream/fmt/buf/fmt_write_manip.hxx" +#include "forwarders.hxx" + namespace stream::fmt { //---------------------------------------------// //----------------- Internals -----------------// @@ -21,84 +23,18 @@ namespace stream::fmt { } }; - //----------------------------------------------// - //----------------- forwarders -----------------// - //----------------------------------------------// - - namespace detail::forwarders { - template - void format_object_array(const T* const buffer, std::size_t totalsize, FormatterExecutor& executor) { - std::size_t begin_idx = (std::size_t)executor.data.specifiers.get_as_number("begin", 0); - totalsize = executor.data.specifiers.get_as_number("totalsize", totalsize); - totalsize = executor.data.specifiers.get_as_number("end", totalsize); - - std::size_t size = executor.data.specifiers.get_as_number("size", totalsize - begin_idx); - - buf::WriteManip(executor.ostream).fast_write_string(executor.data.specifiers.get_as_text("begin", STDEnumerableUtility::DefaultBegin)); - - std::basic_string_view join = executor.data.specifiers.get_as_text("join", STDEnumerableUtility::DefaultJoin); - - bool first = true; - const T* itbegin = buffer + begin_idx; - const T* itend = buffer + size + begin_idx; - - while (itbegin < itend) { - if (first) { - first = false; - } else { - buf::FMTWriteManip(executor.ostream).write_indent_string(join); - } - executor.write_type(*itbegin++); - } - - return buf::WriteManip(executor.ostream).fast_write_string(executor.data.specifiers.get_as_text("end", STDEnumerableUtility::DefaultEnd)); - } - - template - void format_string(const T* buffer, std::size_t size, FormatterExecutor& executor) { - std::size_t begin_idx = (std::size_t)executor.data.specifiers.get_as_number("begin", 0); - size = executor.data.specifiers.get_as_number("size", size); - if (size == std::numeric_limits::max()) { - size = std::basic_string_view(buffer).size(); - } - - if (executor.data.specifiers.has("array")) return format_object_array(buffer, size, executor); - - if (begin_idx > size) return; - const T* begin = buffer + begin_idx; - - // TODO: current indent ignore shift - if (executor.data.specifiers.has("indent")) return buf::FMTWriteManip(executor.ostream).write_indent_char_ptr(begin, size); - - if (executor.data.prefix_suffix) { - buf::ManipIO(executor.ostream).pushback('\"'); - } - - if (executor.data.has_spec == false) { - buf::WriteManip(executor.ostream).fast_write_char_array(begin, size); - } else { - buf::FMTWriteManip(executor.ostream).write_char_ptr(begin, size, executor.data.shift); - } - - if (executor.data.prefix_suffix) { - buf::ManipIO(executor.ostream).pushback('\"'); - } - } - } // namespace detail::forwarders - //-----------------------------------------------// //----------------- C/CXX Types -----------------// //-----------------------------------------------// - // Bool template struct FormatterType { static void format(const bool t, FormatterExecutor& executor) { if (executor.data.prefix_suffix) { if (t == true) - return buf::WriteManip(executor.ostream).fast_write_string_literal("True"); + return buf::WriteManip(executor.ostream).fast_write_literal("True"); else - return buf::WriteManip(executor.ostream).fast_write_string_literal("False"); + return buf::WriteManip(executor.ostream).fast_write_literal("False"); } else { if (t == true) return buf::ManipIO(executor.ostream).pushback('1'); @@ -141,8 +77,8 @@ namespace stream::fmt { template struct FormatterType { static inline void format(const void* const t, FormatterExecutor& executor) { - if (t == nullptr) return buf::ManipIO(executor.ostream).fast_write_string(executor.data.get_as_text("null", "nullptr")); - return buf::WriteManip(executor.ostream).fast_write_integer(std::size_t(t)); + if (t == nullptr) return buf::ManipIO(executor.ostream).fast_write_sv(executor.data.get_as_text("null", "nullptr")); + return buf::FMTWriteManip(executor.ostream).write_integer_format_data(std::size_t(t), executor.data); } }; @@ -150,13 +86,13 @@ namespace stream::fmt { struct FormatterType { static inline void format(const T* const t, FormatterExecutor& executor) { if (t == nullptr) { - return buf::WriteManip(executor.ostream).fast_write_string(executor.data.specifiers.get_as_text("null", "nullptr")); + return buf::WriteManip(executor.ostream).fast_write_sv(executor.data.specifiers.get_as_text("null", "nullptr")); } if constexpr (detail::IsCharType::value) { - return detail::forwarders::format_string(t, std::numeric_limits::max(), executor); + detail::forwarders::format_string_view(std::basic_string_view(t), executor); } else { - detail::forwarders::format_object_array(t, std::numeric_limits::max(), executor); + detail::forwarders::format_span(std::span(t), executor); } } }; @@ -168,9 +104,9 @@ namespace stream::fmt { std::size_t size = SIZE; while (t[size - 1] == '\0') --size; - return detail::forwarders::format_string(t, size, executor); + return detail::forwarders::format_string_view(std::basic_string_view(t, size), executor); } else { - return detail::forwarders::format_object_array(t, SIZE, executor); + return detail::forwarders::format_span(std::span(t, SIZE), executor); } } }; diff --git a/src/stream/fmt/context/formatter_executor/formatter_text_properties_executor/formatter_text_properties_executor_ansi.hxx b/src/stream/fmt/context/formatter_executor/formatter_text_properties_executor/formatter_text_properties_executor_ansi.hxx index 428a2809..82478c8c 100644 --- a/src/stream/fmt/context/formatter_executor/formatter_text_properties_executor/formatter_text_properties_executor_ansi.hxx +++ b/src/stream/fmt/context/formatter_executor/formatter_text_properties_executor/formatter_text_properties_executor_ansi.hxx @@ -15,13 +15,13 @@ namespace stream::fmt::detail { public: void all_properties_reset() override { NoStrideFunction no_stride(*buffer); - return buf::WriteManip(*buffer).fast_write_string_literal("\033[0m"); + return buf::WriteManip(*buffer).fast_write_literal("\033[0m"); } public: void reset_color() override { NoStrideFunction no_stride(*buffer); - return buf::WriteManip(*buffer).fast_write_string_literal("\033[39;49m"); + return buf::WriteManip(*buffer).fast_write_literal("\033[39;49m"); } void execute_color(const TextProperties::TextColor::BasicColorFG& t) { @@ -75,7 +75,7 @@ namespace stream::fmt::detail { void reset_style() override { // TODO NoStrideFunction no_stride(*buffer); - return buf::WriteManip(*buffer).fast_write_string_literal("\033[0m"); + return buf::WriteManip(*buffer).fast_write_literal("\033[0m"); } void execute_style(const detail::TextProperties::TextStyle::Intensity& t) override { NoStrideFunction no_stride(*buffer); diff --git a/src/stream/fmt/context/formatter_executor/forwarders.hxx b/src/stream/fmt/context/formatter_executor/forwarders.hxx new file mode 100644 index 00000000..b4293025 --- /dev/null +++ b/src/stream/fmt/context/formatter_executor/forwarders.hxx @@ -0,0 +1,91 @@ +#pragma once + +#include "stream/fmt/detail/specifiers.hxx" +#include "stream/fmt/buf/fmt_write_manip.hxx" +#include "stream/fmt/context/basic_context/basic_context_parse_formatdata.hxx" + +#include + +namespace stream::fmt::detail { + template + class ContainersUtility { + public: + static constexpr std::basic_string_view default_join = ", "; + static constexpr std::basic_string_view default_begin = "{ "; + static constexpr std::basic_string_view default_end = " }"; + }; + + template + struct FunctionapplyNextOverride { + inline explicit FunctionapplyNextOverride(FormatterExecutor& executor) : executor(executor), formatdata(executor.data) { + buf::StreamView stream{executor.data.next_override}; + executor.data = parse_format_data(executor, stream); + } + + inline ~FunctionapplyNextOverride() { + executor.data = formatdata; + } + + FormatterExecutor& executor; + FormatData formatdata; + }; + + namespace forwarders { + template + void format_span(const std::span container, FormatterExecutor& executor) { + std::size_t begin_idx = (std::size_t)executor.data.specifiers.get_as_number("begin", 0); + std::size_t end = executor.data.specifiers.get_as_number("end", container.size()); + std::int32_t size_to_print = executor.data.specifiers.get_as_number("size", std::int32_t{end} - std::int32_t{begin_idx}); + + buf::FMTWriteManip(executor.ostream).write_indent_sv(executor.data.specifiers.get_as_text("begin", ContainersUtility::default_begin)); + std::basic_string_view join = executor.data.specifiers.get_as_text("join", ContainersUtility::default_join); + + if (size_to_print > 0) { + detail::FunctionapplyNextOverride apply_next_override(executor); + + bool first = true; + std::for_each_n(container.begin() + begin_idx, std::size_t{size_to_print}, [&](const auto& element) { + if (first) { + first = false; + } else { + buf::FMTWriteManip(executor.ostream).write_indent_sv(join); + } + + executor.write_type(element); + }); + } + + buf::FMTWriteManip(executor.ostream).write_indent_sv(executor.data.specifiers.get_as_text("end", ContainersUtility::default_end)); + } + + template + void format_string_view(const std::basic_string_view container, FormatterExecutor& executor) { + std::size_t begin_idx = (std::size_t)executor.data.specifiers.get_as_number("begin", 0); + std::size_t end = executor.data.specifiers.get_as_number("end", container.size()); + std::int32_t size_to_print = executor.data.specifiers.get_as_number("size", std::int32_t{end} - std::int32_t{begin_idx}); + + if (executor.data.specifiers.has("span")) { + return format_span(std::span(container), executor); + } + + if (executor.data.prefix_suffix) { + buf::ManipIO(executor.ostream).pushback('\"'); + } + + if (size_to_print > 0) { + // TODO: current indent ignore shift + if (executor.data.specifiers.has("indent")) { + return buf::FMTWriteManip(executor.ostream).write_indent_sv(std::basic_string_view(container.begin() + begin_idx, size_to_print)); + } else if (executor.data.has_spec == false) { + buf::WriteManip(executor.ostream).fast_write_sv(std::basic_string_view(container.begin() + begin_idx, size_to_print)); + } else { + buf::FMTWriteManip(executor.ostream).write_sv(std::basic_string_view(container.begin() + begin_idx, size_to_print), executor.data.shift); + } + } + + if (executor.data.prefix_suffix) { + buf::ManipIO(executor.ostream).pushback('\"'); + } + } + } // namespace detail::forwarders +} diff --git a/src/stream/fmt/context/formatter_executor/std_enumerable.hxx b/src/stream/fmt/context/formatter_executor/std_enumerable.hxx deleted file mode 100644 index 3371bd2e..00000000 --- a/src/stream/fmt/context/formatter_executor/std_enumerable.hxx +++ /dev/null @@ -1,98 +0,0 @@ -#pragma once - -#include "formatter_type.hxx" -#include "stream/fmt/context/utils/context_functions.hxx" -#include "stream/fmt/detail/prelude.hxx" - -#include -#include - -namespace stream::fmt { - class STDEnumerableUtility { - public: - static constexpr std::string_view DefaultJoin = ", "; - static constexpr std::string_view DefaultBegin = "{ "; - static constexpr std::string_view DefaultEnd = " }"; - }; - - template - class STDEnumerable { - public: - explicit inline STDEnumerable(const T& value, std::basic_string_view join_str = ", ", std::basic_string_view begin_str = "{ ", - std::basic_string_view end_str = " }", const std::int32_t begin_idx = 0, const std::int32_t size = -1) - : value_(value), join_str_(join_str), begin_str_(begin_str), end_(end_str), begin_idx_(begin_idx), size_(size < 0 ? (std::int32_t)value.size() - begin_idx : size) {} - - inline const T& get_value() const { - return value_; - } - - inline std::basic_string_view get_str_join() const { - return join_str_; - } - inline std::basic_string_view get_str_begin() const { - return begin_str_; - } - inline std::basic_string_view get_str_end() const { - return end_; - } - - inline std::int32_t get_begin_idx() const { - return begin_idx_; - } - inline std::int32_t get_size() const { - return size_; - } - - private: - const T& value_; - - std::basic_string_view join_str_; - std::basic_string_view begin_str_; - std::basic_string_view end_; - - std::int32_t begin_idx_; - std::int32_t size_; - }; - - template - struct FormatterType, FormatterExecutor> { - static void format(const STDEnumerable& enumerable, FormatterExecutor& executor) { - executor.ostream.write_indent_string_view(enumerable.get_str_begin()); - executor.ostream.add_indent(enumerable.get_str_begin().size()); - - { - // TODO: Why ? ... - detail::FunctionapplyNextOverride apply_next_override(executor); - - bool first = true; - std::for_each_n(enumerable.get_value().cbegin() + enumerable.get_begin_idx(), enumerable.get_size(), [&](const auto& element) { - if (first) { - first = false; - } else { - executor.ostream.write_indent_string_view(enumerable.get_str_join()); - } - - executor.write_type(element); - }); - } - - executor.ostream.remove_indent(enumerable.get_str_begin().size()); - executor.ostream.write_indent_string_view(enumerable.get_str_end()); - } - }; - - template - struct ForwardAsSTDEnumerable {}; - - template - struct FormatterType, FormatterExecutor> { - static inline void format(const T& container, FormatterExecutor& executor) { - STDEnumerable enumerable(container, executor.data.get_as_text("join", STDEnumerableUtility::DefaultJoin), - executor.data.get_as_text("begin", STDEnumerableUtility::DefaultBegin), executor.data.get_as_text("end", STDEnumerableUtility::DefaultEnd), - executor.data.get_as_number("begin", 0), executor.data.get_as_number("size", -1)); - - return executor.write_type(enumerable); - } - }; - -} // namespace stream::fmt diff --git a/src/stream/fmt/context/parser_executor/basic_parser_executor.hxx b/src/stream/fmt/context/parser_executor/basic_parser_executor.hxx index 55aadd3d..507ff67e 100644 --- a/src/stream/fmt/context/parser_executor/basic_parser_executor.hxx +++ b/src/stream/fmt/context/parser_executor/basic_parser_executor.hxx @@ -14,7 +14,7 @@ namespace stream::fmt::context { template - class BasicParserExecutor : public context_executor { + class BasicParserExecutor : public ContextExecutor { public: using TChar = CharType; @@ -30,8 +30,8 @@ namespace stream::fmt::context { public: buf::StreamView& istream; - using context_executor::data; - using context_executor::text_manager; + using ContextExecutor::data; + using ContextExecutor::text_manager; protected: void exec_raw_string(std::basic_string_view sv) override { @@ -57,7 +57,7 @@ namespace stream::fmt::context { namespace stream::fmt::context { template BasicParserExecutor::BasicParserExecutor(buf::StreamView& istream_, detail::ITextPropertiesExecutor& text_properties_executor_) - : context_executor(text_properties_executor_), istream{istream_} { + : ContextExecutor(text_properties_executor_), istream{istream_} { text_properties_executor_.link_to_executor(this); } diff --git a/src/stream/fmt/context/utils/context_functions.hxx b/src/stream/fmt/context/utils/context_functions.hxx deleted file mode 100644 index 33170f81..00000000 --- a/src/stream/fmt/context/utils/context_functions.hxx +++ /dev/null @@ -1,19 +0,0 @@ -#pragma once - -#include "stream/fmt/detail/specifiers.hxx" - -namespace stream::fmt::detail { - template - struct FunctionapplyNextOverride { - inline explicit FunctionapplyNextOverride(FormatterExecutor& executor) : executor(executor), formatdata(executor.data) { - executor.formatdata_apply_next_override(); - } - - inline ~FunctionapplyNextOverride() { - executor.data = formatdata; - } - - FormatterExecutor& executor; - detail::FormatData formatdata; - }; -} // namespace stream::fmt::detail diff --git a/src/stream/fmt/detail/specifiers.hxx b/src/stream/fmt/detail/specifiers.hxx index 5fcd76c1..5f1a46d6 100644 --- a/src/stream/fmt/detail/specifiers.hxx +++ b/src/stream/fmt/detail/specifiers.hxx @@ -38,8 +38,8 @@ namespace stream::fmt::detail { constexpr ShiftPrint(char before, char after) : before(before), after(after) {} public: - char before; - char after; + char before = ' '; + char after = ' '; public: constexpr bool before_is_a_digit() const { diff --git a/src/stream/fmt/serializers/format_chrono.hxx b/src/stream/fmt/serializers/format_chrono.hxx index a7b83cd9..0496b025 100644 --- a/src/stream/fmt/serializers/format_chrono.hxx +++ b/src/stream/fmt/serializers/format_chrono.hxx @@ -77,7 +77,7 @@ namespace stream::fmt::detail { } auto view = buf::TestManip(pattern).view_exec([&] { buf::FMTParamsManip(pattern).param_go_to('%', '#', '/'); }); - buf::WriteManip(buffer).fast_write_string(view); + buf::WriteManip(buffer).fast_write_sv(view); while (!pattern.is_end_of_string()) { TimePrintMode mode; @@ -92,7 +92,7 @@ namespace stream::fmt::detail { write_sub_time_(value, pattern, buffer, mode); auto view = buf::TestManip(pattern).view_exec([&] { buf::FMTParamsManip(pattern).param_go_to('%', '#', '/'); }); - buf::WriteManip(buffer).fast_write_string(view); + buf::WriteManip(buffer).fast_write_sv(view); } } } // namespace stream::fmt::detail diff --git a/src/stream/fmt/serializers/format_stdlib.hxx b/src/stream/fmt/serializers/format_stdlib.hxx index 42ec3aa8..64a3a76c 100644 --- a/src/stream/fmt/serializers/format_stdlib.hxx +++ b/src/stream/fmt/serializers/format_stdlib.hxx @@ -15,21 +15,21 @@ namespace stream::fmt { template struct FormatterType, FormatterExecutor> { static inline void format(const std::basic_string& t, FormatterExecutor& executor) { - return buf::WriteManip(executor.ostream).fast_write_string(t); + return buf::WriteManip(executor.ostream).fast_write_sv(t); } }; template struct FormatterType, FormatterExecutor> { static inline void format(std::basic_string_view t, FormatterExecutor& executor) { - return buf::WriteManip(executor.ostream).fast_write_string(t); + return buf::WriteManip(executor.ostream).fast_write_sv(t); } }; template struct FormatterType, FormatterExecutor> { static inline void format(const std::basic_stringstream& t, FormatterExecutor& executor) { - return buf::WriteManip(executor.ostream).fast_write_char_array(t.str(), t.size()); + return buf::WriteManip(executor.ostream).fast_write_sv(std::basic_string_view(t.str(), t.size())); } }; diff --git a/src/stream/fmt/serializers/std_container/tuple.hxx b/src/stream/fmt/serializers/std_container/tuple.hxx index fbe5fc48..0d351374 100644 --- a/src/stream/fmt/serializers/std_container/tuple.hxx +++ b/src/stream/fmt/serializers/std_container/tuple.hxx @@ -36,12 +36,7 @@ namespace stream::fmt { struct FormatterType, FormatterExecutor> { static void format(const std::tuple& t, FormatterExecutor& executor) { executor.ostream.pushback('<'); - std::apply([&context_executor, &err](auto&&... args) { - auto&& res = tuple_detail::tuple_format_rec(context_executor, args...); - if (not res) { - err = res.error(); - } - }, t); + std::apply([&executor](auto&&... args) { auto&& res = tuple_detail::tuple_format_rec(executor, args...); }, t); executor.ostream.pushback('>'); } }; diff --git a/src/stream/json/json_serializer.hxx b/src/stream/json/json_serializer.hxx index fce41e74..035e48a9 100644 --- a/src/stream/json/json_serializer.hxx +++ b/src/stream/json/json_serializer.hxx @@ -31,8 +31,8 @@ namespace stream::json { } static inline void format(const T&, detail::JsonFormatter& formatter) { - fmt::buf::WriteManip(formatter.ostream).fast_write_string(std::string_view("Unknown JsonFormatter for type : ")); - fmt::buf::WriteManip(formatter.ostream).fast_write_string(std::string_view(typeid(T).name())); + fmt::buf::WriteManip(formatter.ostream).fast_write_sv(std::string_view("Unknown JsonFormatter for type : ")); + fmt::buf::WriteManip(formatter.ostream).fast_write_sv(std::string_view(typeid(T).name())); #ifdef UNKOWN_TYPE_MESSAGE fmt::file_print(std::cerr, "{C:red}JsonSerializer::Format<{}> not impl", typeid(T).name()); @@ -139,9 +139,9 @@ namespace stream::json { static inline void FormatBool(const bool& t, detail::JsonFormatter& formatter) { if (t) - fmt::buf::WriteManip(formatter.ostream).fast_write_char_array("true", 5); + fmt::buf::WriteManip(formatter.ostream).fast_write_literal("true"); else - fmt::buf::WriteManip(formatter.ostream).fast_write_char_array("false", 5); + fmt::buf::WriteManip(formatter.ostream).fast_write_literal("false"); } }; @@ -264,7 +264,7 @@ namespace stream::json { } static inline void FormatNull(detail::JsonFormatter& formatter) { - fmt::buf::WriteManip(formatter.ostream).fast_write_char_array("null", 4); + fmt::buf::WriteManip(formatter.ostream).fast_write_literal("null"); } }; } // namespace stream::json diff --git a/src/stream/tester/test_suite/test_suite.hxx b/src/stream/tester/test_suite/test_suite.hxx index 6c380087..0145879b 100644 --- a/src/stream/tester/test_suite/test_suite.hxx +++ b/src/stream/tester/test_suite/test_suite.hxx @@ -162,16 +162,16 @@ namespace stream::fmt { template struct FormatterType { static void format(const stream::tester::detail::TestSuite& t, FormatterExecutor& executor) { - return executor.ostream.fast_write_string(t.name); + return executor.ostream.fast_write_sv(t.name); } }; template struct FormatterType { static void format(const stream::tester::detail::Test& t, FormatterExecutor& executor) { - buf::WriteManip(executor.ostream).fast_write_string(t.link.name); - buf::WriteManip(executor.ostream).fast_write_string_literal("::"); - buf::WriteManip(executor.ostream).fast_write_string(t.name); + buf::WriteManip(executor.ostream).fast_write_sv(t.link.name); + buf::WriteManip(executor.ostream).fast_write_literal("::"); + buf::WriteManip(executor.ostream).fast_write_sv(t.name); } }; @@ -180,11 +180,11 @@ namespace stream::fmt { static void format(const stream::tester::TestStatus& status, FormatterExecutor& executor) { switch (status) { case stream::tester::TestStatus::ok: - return executor.run("[ {C:green}OK{C} ]"); + return executor.run("[ {:C:green,^5} ]", "OK"); case stream::tester::TestStatus::fail: - return executor.run("[ {C:red}FAIL{C} ]"); + return executor.run("[ {:C:red,^5} ]", "FAIL"); case stream::tester::TestStatus::Crash: - return executor.run("[{C:magenta}Crash{C} ]"); + return executor.run("[ {:C:magenta,^5} ]", "CRASH"); } } }; @@ -192,24 +192,24 @@ namespace stream::fmt { template struct FormatterType { static void format(const stream::tester::detail::TestStatusBank& status_bank, FormatterExecutor& executor) { - buf::WriteManip(executor.ostream).fast_write_string_literal("tests_done "); + buf::WriteManip(executor.ostream).fast_write_literal("tests_done "); executor.run("{:C:white}", status_bank.tests_done); - buf::WriteManip(executor.ostream).fast_write_string_literal(" | testsOK "); + buf::WriteManip(executor.ostream).fast_write_literal(" | testsOK "); if (status_bank.tests_ok == status_bank.tests_done) { executor.run("{:C:green}", status_bank.tests_ok); } else { executor.run("{:C:yellow}", status_bank.tests_ok); } - buf::WriteManip(executor.ostream).fast_write_string_literal(" | testsFAIL "); + buf::WriteManip(executor.ostream).fast_write_literal(" | testsFAIL "); if (status_bank.tests_failed == 0) { executor.run("{:C:green}", status_bank.tests_failed); } else { executor.run("{:C:red}", status_bank.tests_failed); } - buf::WriteManip(executor.ostream).fast_write_string_literal(" | TestCrash "); + buf::WriteManip(executor.ostream).fast_write_literal(" | TestCrash "); if (status_bank.tests_crash == 0) { executor.run("{:C:green}", status_bank.tests_crash); } else { diff --git a/tests/fmt/specifier.cxx b/tests/fmt/specifier.cxx index 1d82c484..0b1d1363 100644 --- a/tests/fmt/specifier.cxx +++ b/tests/fmt/specifier.cxx @@ -30,21 +30,21 @@ SFT_TEST_FUNC(SPECIFIER, BEGIN_END) { SFT_TEST_FUNC(SPECIFIER, BEGIN_END_NESTED_SPECS) { int data[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; - TEST_FMT_ARRAY_SPECIFIERS("{::x}", data, "{ 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9 }"); + TEST_FMT_ARRAY_SPECIFIERS("{::#x}", data, "{ 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9 }"); - TEST_FMT_ARRAY_SPECIFIERS("{:begin=6, :x}", data, "{ 0x6, 0x7, 0x8, 0x9 }"); - TEST_FMT_ARRAY_SPECIFIERS("{:size=5, :x}", data, "{ 0x0, 0x1, 0x2, 0x3, 0x4 }"); - TEST_FMT_ARRAY_SPECIFIERS("{:begin=3, size=5, :x}", data, "{ 0x3, 0x4, 0x5, 0x6, 0x7 }"); + TEST_FMT_ARRAY_SPECIFIERS("{:begin=6, :#x}", data, "{ 0x6, 0x7, 0x8, 0x9 }"); + TEST_FMT_ARRAY_SPECIFIERS("{:size=5, :#x}", data, "{ 0x0, 0x1, 0x2, 0x3, 0x4 }"); + TEST_FMT_ARRAY_SPECIFIERS("{:begin=3, size=5, :#x}", data, "{ 0x3, 0x4, 0x5, 0x6, 0x7 }"); - TEST_FMT_ARRAY_SPECIFIERS("{:begin='{', begin=3, size=5, :x}", data, "{0x3, 0x4, 0x5, 0x6, 0x7 }"); - TEST_FMT_ARRAY_SPECIFIERS("{:end='}', begin=3, size=5, :x}", data, "{ 0x3, 0x4, 0x5, 0x6, 0x7}"); - TEST_FMT_ARRAY_SPECIFIERS("{:begin='{', end='}', begin=3, size=5, :x}", data, "{0x3, 0x4, 0x5, 0x6, 0x7}"); - TEST_FMT_ARRAY_SPECIFIERS("{:begin='[', end='}', begin=3, size=5, :x}", data, "[0x3, 0x4, 0x5, 0x6, 0x7}"); - TEST_FMT_ARRAY_SPECIFIERS("{:begin='[', end=']', begin=3, size=5, :x}", data, "[0x3, 0x4, 0x5, 0x6, 0x7]"); + TEST_FMT_ARRAY_SPECIFIERS("{:begin='{', begin=3, size=5, :#x}", data, "{0x3, 0x4, 0x5, 0x6, 0x7 }"); + TEST_FMT_ARRAY_SPECIFIERS("{:end='}', begin=3, size=5, :#x}", data, "{ 0x3, 0x4, 0x5, 0x6, 0x7}"); + TEST_FMT_ARRAY_SPECIFIERS("{:begin='{', end='}', begin=3, size=5, :#x}", data, "{0x3, 0x4, 0x5, 0x6, 0x7}"); + TEST_FMT_ARRAY_SPECIFIERS("{:begin='[', end='}', begin=3, size=5, :#x}", data, "[0x3, 0x4, 0x5, 0x6, 0x7}"); + TEST_FMT_ARRAY_SPECIFIERS("{:begin='[', end=']', begin=3, size=5, :#x}", data, "[0x3, 0x4, 0x5, 0x6, 0x7]"); - TEST_FMT_ARRAY_SPECIFIERS("{:join=' ', begin='[', end=']', begin=3, size=5, :x}", data, "[0x3 0x4 0x5 0x6 0x7]"); + TEST_FMT_ARRAY_SPECIFIERS("{:join=' ', begin='[', end=']', begin=3, size=5, :#x}", data, "[0x3 0x4 0x5 0x6 0x7]"); - TEST_FMT_ARRAY_SPECIFIERS("{:join=' | ', begin='[', end=']', begin=3, size=5, :x}", data, "[0x3 | 0x4 | 0x5 | 0x6 | 0x7]"); + TEST_FMT_ARRAY_SPECIFIERS("{:join=' | ', begin='[', end=']', begin=3, size=5, :#x}", data, "[0x3 | 0x4 | 0x5 | 0x6 | 0x7]"); } // NOLINTEND(readability-magic-numbers) // NOLINTEND(misc-const-correctness) From d184306a71457eb91d81b567d3b8c6cd3e5e0507 Mon Sep 17 00:00:00 2001 From: Sacha Bellier Date: Wed, 26 Mar 2025 23:54:31 +0100 Subject: [PATCH 33/42] fix: clang-format --- src/stream/fmt/buf/fmt_write_manip.hxx | 14 ++++---- .../context/basic_context/basic_context.hxx | 13 ++++---- .../basic_context_parse_formatdata.hxx | 32 ++++++++++--------- .../basic_context_parse_getindex.hxx | 15 +++++---- .../basic_formatter_executor.hxx | 5 ++- .../context/formatter_executor/forwarders.hxx | 6 ++-- 6 files changed, 44 insertions(+), 41 deletions(-) diff --git a/src/stream/fmt/buf/fmt_write_manip.hxx b/src/stream/fmt/buf/fmt_write_manip.hxx index a166cd38..929b1a87 100644 --- a/src/stream/fmt/buf/fmt_write_manip.hxx +++ b/src/stream/fmt/buf/fmt_write_manip.hxx @@ -122,16 +122,17 @@ namespace stream::fmt::buf { ManipIO manip(buffer); std::int32_t digit_count = sizeof(T) * (8 / digitsize); - std::uint8_t mask = (1 << digitsize) - 1; - + std::uint8_t mask = (1 << digitsize) - 1; + if (i != 0) { // Remove leading 0 std::int32_t last_pos_with_data = digit_count; std::int32_t k = digit_count; - T cpy_i = i; + T cpy_i = i; while (--k != 0) { - if ((cpy_i & mask) != 0) - { last_pos_with_data = k; } + if ((cpy_i & mask) != 0) { + last_pos_with_data = k; + } cpy_i = cpy_i >> digitsize; } digit_count -= last_pos_with_data; @@ -142,8 +143,7 @@ namespace stream::fmt::buf { ManipIO(buffer).pushback(base_prefix); } - if (i == 0) - { + if (i == 0) { ManipIO(buffer).pushback('0'); return; } diff --git a/src/stream/fmt/context/basic_context/basic_context.hxx b/src/stream/fmt/context/basic_context/basic_context.hxx index 8782abc6..65fc73b1 100644 --- a/src/stream/fmt/context/basic_context/basic_context.hxx +++ b/src/stream/fmt/context/basic_context/basic_context.hxx @@ -31,7 +31,9 @@ namespace stream::fmt::context { virtual void exec_settings() = 0; virtual void exec_raw_string(std::basic_string_view) = 0; - BasicContext& get_context() { return *reinterpret_cast*>(context); } + BasicContext& get_context() { + return *reinterpret_cast*>(context); + } public: detail::FormatData data; @@ -72,13 +74,12 @@ namespace stream::fmt::context { template BasicContext::BasicContext(ContextExecutor& executor, buf::StreamView format, detail::BasicArgsInterface& args_interface) : executor(executor), fmtstream{format}, args_interface{args_interface}, values_index{0} { - old_context_attached = executor.context; - executor.context = this; - } + old_context_attached = executor.context; + executor.context = this; + } template - BasicContext::~BasicContext() - { + BasicContext::~BasicContext() { executor.context = old_context_attached; } diff --git a/src/stream/fmt/context/basic_context/basic_context_parse_formatdata.hxx b/src/stream/fmt/context/basic_context/basic_context_parse_formatdata.hxx index df09c53c..08908921 100644 --- a/src/stream/fmt/context/basic_context/basic_context_parse_formatdata.hxx +++ b/src/stream/fmt/context/basic_context/basic_context_parse_formatdata.hxx @@ -13,8 +13,9 @@ namespace stream::fmt::detail { namespace { - template - std::basic_string_view parse_next_override_format_data(Executor& executor, buf::StreamView& stream, detail::FormatData& data) { + template + std::basic_string_view parse_next_override_format_data(Executor& executor, buf::StreamView& stream, + detail::FormatData& data) { buf::TestAccess access(stream); buf::TestManip manip(stream); @@ -22,7 +23,7 @@ namespace stream::fmt::detail { manip.ignore_every_spaces(); const typename Executor::TChar* begin = stream.current_pos; - int scopes = 0; + int scopes = 0; while (buf::FMTParamsManip(stream).is_end_of_parameter() == false || scopes > 0) { manip.GoTo('\'', '}', '{'); if (access.is_equal_to('\'')) { @@ -40,8 +41,8 @@ namespace stream::fmt::detail { return std::basic_string_view(begin, end - begin); } - template - void parse_format_data_base(Executor& executor, buf::StreamView& stream, detail::FormatData& data) { + template + void parse_format_data_base(Executor& executor, buf::StreamView& stream, detail::FormatData& data) { buf::TestAccess access(stream); if (access.is_equal_to('C')) { @@ -61,8 +62,9 @@ namespace stream::fmt::detail { } } - template - void parse_format_data_special_shift_type(Executor& executor, buf::StreamView& stream, detail::FormatData& data, const detail::ShiftInfo::ShiftType type) { + template + void parse_format_data_special_shift_type(Executor& executor, buf::StreamView& stream, detail::FormatData& data, + const detail::ShiftInfo::ShiftType type) { data.shift.type = type; data.shift.size = format_read_parameter(executor, stream, -1); if (buf::TestAccess(stream).is_equal_to(':')) { @@ -78,8 +80,8 @@ namespace stream::fmt::detail { } } - template - bool parse_format_data_special(Executor& executor, buf::StreamView& stream, detail::FormatData& data) { + template + bool parse_format_data_special(Executor& executor, buf::StreamView& stream, detail::FormatData& data) { buf::TestAccess access(stream); buf::TestManip manip(stream); @@ -115,9 +117,9 @@ namespace stream::fmt::detail { } bool is_integer_spec = access.is_equal_to('d', 'b', 'b', 'o', 'O', 'x', 'X'); - is_integer_spec = is_integer_spec && (stream.get_buffer_remaining_size() == 1 || (buf::Access(stream).get_next() > 'z' && buf::Access(stream).get_next() < 'a')); + is_integer_spec = is_integer_spec && (stream.get_buffer_remaining_size() == 1 || (buf::Access(stream).get_next() > 'z' && buf::Access(stream).get_next() < 'a')); if (is_integer_spec) { - local_spec = true; + local_spec = true; data.integer_print = static_cast(stream.get()); buf::Manip(stream).forward(); } @@ -155,8 +157,8 @@ namespace stream::fmt::detail { return local_spec; } - template - void parse_format_data_custom(Executor& executor, buf::StreamView& stream, detail::FormatData& data) { + template + void parse_format_data_custom(Executor& executor, buf::StreamView& stream, detail::FormatData& data) { buf::TestAccess access(stream); buf::TestManip manip(stream); @@ -184,7 +186,7 @@ namespace stream::fmt::detail { data.specifiers.concat(detail::FormatSpecifier{name}); } } - } + } // namespace template detail::FormatData parse_format_data(Executor& executor, buf::StreamView& stream) { @@ -209,4 +211,4 @@ namespace stream::fmt::detail { return data; } -} // namespace stream::fmt::context +} // namespace stream::fmt::detail diff --git a/src/stream/fmt/context/basic_context/basic_context_parse_getindex.hxx b/src/stream/fmt/context/basic_context/basic_context_parse_getindex.hxx index da358622..83995cb7 100644 --- a/src/stream/fmt/context/basic_context/basic_context_parse_getindex.hxx +++ b/src/stream/fmt/context/basic_context/basic_context_parse_getindex.hxx @@ -57,7 +57,7 @@ namespace stream::fmt::context { } return std::nullopt; } - } + } // namespace template std::optional get_format_index(Executor& executor, buf::StreamView& stream) { @@ -81,8 +81,8 @@ namespace stream::fmt::context { // VI : { which is a idx to an argument if (access.is_equal_to('{')) { - const typename Executor::TChar* oldPos = stream.current_pos; - std::optional res = get_format_index_sub_index(executor, stream); + const typename Executor::TChar* oldPos = stream.current_pos; + std::optional res = get_format_index_sub_index(executor, stream); if (res.has_value() == false) { stream.current_pos = oldPos; return std::nullopt; @@ -104,10 +104,11 @@ namespace stream::fmt::context { // SubIndex buf::TestManip(stream).skip_one_of('{'); std::optional format_idx = get_format_index(executor, stream); - if constexpr (std::is_convertible_v) - { return executor.get_context().args_interface.get_int_at(format_idx.value()); } - else if constexpr (std::is_convertible_v>) - { return executor.get_context().args_interface.get_string_at(format_idx.value()); } + if constexpr (std::is_convertible_v) { + return executor.get_context().args_interface.get_int_at(format_idx.value()); + } else if constexpr (std::is_convertible_v>) { + return executor.get_context().args_interface.get_string_at(format_idx.value()); + } throw std::runtime_error("fmt error: Context_ArgumentIndexExpected"); } diff --git a/src/stream/fmt/context/formatter_executor/basic_formatter_executor.hxx b/src/stream/fmt/context/formatter_executor/basic_formatter_executor.hxx index 12659400..33918cf4 100644 --- a/src/stream/fmt/context/formatter_executor/basic_formatter_executor.hxx +++ b/src/stream/fmt/context/formatter_executor/basic_formatter_executor.hxx @@ -31,7 +31,7 @@ namespace stream::fmt::context { ~BasicFormatterExecutor() override = default; void terminate(); - + public: buf::FMTStreamIO& ostream; EndOfStringCharMode end_of_string_char = EndOfStringCharMode::Optional; @@ -53,8 +53,7 @@ namespace stream::fmt::context { public: template - void write_type(Type&& type) - { + void write_type(Type&& type) { FormatterType>::type, M_Type>::format(std::forward(type), *this); } template diff --git a/src/stream/fmt/context/formatter_executor/forwarders.hxx b/src/stream/fmt/context/formatter_executor/forwarders.hxx index b4293025..322fdc69 100644 --- a/src/stream/fmt/context/formatter_executor/forwarders.hxx +++ b/src/stream/fmt/context/formatter_executor/forwarders.hxx @@ -26,7 +26,7 @@ namespace stream::fmt::detail { executor.data = formatdata; } - FormatterExecutor& executor; + FormatterExecutor& executor; FormatData formatdata; }; @@ -87,5 +87,5 @@ namespace stream::fmt::detail { buf::ManipIO(executor.ostream).pushback('\"'); } } - } // namespace detail::forwarders -} + } // namespace forwarders +} // namespace stream::fmt::detail From 581f271a7f1ddab96b359ff4cf18954fde302e68 Mon Sep 17 00:00:00 2001 From: BELLIER Sacha Date: Thu, 27 Mar 2025 00:12:30 +0100 Subject: [PATCH 34/42] fix: MSVC --- src/stream/fmt/buf/fmt_write_manip.hxx | 9 ++++----- src/stream/fmt/buf/write_manip.hxx | 2 +- .../fmt/context/formatter_executor/format_basics.hxx | 4 ++-- .../fmt/context/formatter_executor/forwarders.hxx | 12 ++++++------ src/stream/fmt/serializers/format_stdlib.hxx | 2 +- src/stream/fmt/serializers/std_container/array.hxx | 4 ++-- src/stream/fmt/serializers/std_container/deque.hxx | 4 ++-- .../fmt/serializers/std_container/forward_list.hxx | 4 ++-- src/stream/fmt/serializers/std_container/list.hxx | 4 ++-- src/stream/fmt/serializers/std_container/map.hxx | 6 +++--- src/stream/fmt/serializers/std_container/set.hxx | 6 +++--- .../fmt/serializers/std_container/unordered_map.hxx | 6 +++--- .../fmt/serializers/std_container/unordered_set.hxx | 6 +++--- src/stream/fmt/serializers/std_container/vector.hxx | 4 ++-- 14 files changed, 36 insertions(+), 37 deletions(-) diff --git a/src/stream/fmt/buf/fmt_write_manip.hxx b/src/stream/fmt/buf/fmt_write_manip.hxx index 929b1a87..4dc70544 100644 --- a/src/stream/fmt/buf/fmt_write_manip.hxx +++ b/src/stream/fmt/buf/fmt_write_manip.hxx @@ -192,16 +192,15 @@ namespace stream::fmt::buf { } public: - template - void write_indent_char_ptr(const CharStr* str, std::size_t size) { + void write_indent_char_ptr(const TChar* str, std::size_t size) { while (size > 0) { - const CharStr* const begin = str; + const TChar* const begin = str; while (size > 0 && *str != '\n') { ++str, --size; } - const CharStr* const end = str; + const TChar* const end = str; - WriteManip(buffer).fast_write_sv(std::basic_string_view(begin, end)); + WriteManip(buffer).fast_write_sv(std::basic_string_view(begin, end)); if (size > 0 && *str == '\n') { FMTManipIO(buffer).new_line_indent(); diff --git a/src/stream/fmt/buf/write_manip.hxx b/src/stream/fmt/buf/write_manip.hxx index f3535133..d2c591ec 100644 --- a/src/stream/fmt/buf/write_manip.hxx +++ b/src/stream/fmt/buf/write_manip.hxx @@ -134,7 +134,7 @@ namespace stream::fmt::buf { while (str[size - 1] == 0) { --size; } - return fast_write_sv(std::basic_string_view(str, size)); + return fast_write_sv(std::basic_string_view(str, size)); } public: diff --git a/src/stream/fmt/context/formatter_executor/format_basics.hxx b/src/stream/fmt/context/formatter_executor/format_basics.hxx index 3189604f..17cc06f0 100644 --- a/src/stream/fmt/context/formatter_executor/format_basics.hxx +++ b/src/stream/fmt/context/formatter_executor/format_basics.hxx @@ -90,7 +90,7 @@ namespace stream::fmt { } if constexpr (detail::IsCharType::value) { - detail::forwarders::format_string_view(std::basic_string_view(t), executor); + detail::forwarders::format_string_view(std::basic_string_view(t), executor); } else { detail::forwarders::format_span(std::span(t), executor); } @@ -104,7 +104,7 @@ namespace stream::fmt { std::size_t size = SIZE; while (t[size - 1] == '\0') --size; - return detail::forwarders::format_string_view(std::basic_string_view(t, size), executor); + return detail::forwarders::format_string_view(std::basic_string_view(t, size), executor); } else { return detail::forwarders::format_span(std::span(t, SIZE), executor); } diff --git a/src/stream/fmt/context/formatter_executor/forwarders.hxx b/src/stream/fmt/context/formatter_executor/forwarders.hxx index 322fdc69..8cc0eb78 100644 --- a/src/stream/fmt/context/formatter_executor/forwarders.hxx +++ b/src/stream/fmt/context/formatter_executor/forwarders.hxx @@ -35,7 +35,7 @@ namespace stream::fmt::detail { void format_span(const std::span container, FormatterExecutor& executor) { std::size_t begin_idx = (std::size_t)executor.data.specifiers.get_as_number("begin", 0); std::size_t end = executor.data.specifiers.get_as_number("end", container.size()); - std::int32_t size_to_print = executor.data.specifiers.get_as_number("size", std::int32_t{end} - std::int32_t{begin_idx}); + std::int32_t size_to_print = executor.data.specifiers.get_as_number("size", static_cast(end) - static_cast(begin_idx)); buf::FMTWriteManip(executor.ostream).write_indent_sv(executor.data.specifiers.get_as_text("begin", ContainersUtility::default_begin)); std::basic_string_view join = executor.data.specifiers.get_as_text("join", ContainersUtility::default_join); @@ -44,7 +44,7 @@ namespace stream::fmt::detail { detail::FunctionapplyNextOverride apply_next_override(executor); bool first = true; - std::for_each_n(container.begin() + begin_idx, std::size_t{size_to_print}, [&](const auto& element) { + std::for_each_n(container.begin() + begin_idx, static_cast(size_to_print), [&](const auto& element) { if (first) { first = false; } else { @@ -62,7 +62,7 @@ namespace stream::fmt::detail { void format_string_view(const std::basic_string_view container, FormatterExecutor& executor) { std::size_t begin_idx = (std::size_t)executor.data.specifiers.get_as_number("begin", 0); std::size_t end = executor.data.specifiers.get_as_number("end", container.size()); - std::int32_t size_to_print = executor.data.specifiers.get_as_number("size", std::int32_t{end} - std::int32_t{begin_idx}); + std::int32_t size_to_print = executor.data.specifiers.get_as_number("size", static_cast(end) - static_cast(begin_idx)); if (executor.data.specifiers.has("span")) { return format_span(std::span(container), executor); @@ -75,11 +75,11 @@ namespace stream::fmt::detail { if (size_to_print > 0) { // TODO: current indent ignore shift if (executor.data.specifiers.has("indent")) { - return buf::FMTWriteManip(executor.ostream).write_indent_sv(std::basic_string_view(container.begin() + begin_idx, size_to_print)); + return buf::FMTWriteManip(executor.ostream).write_indent_sv(container.substr(begin_idx, static_cast(size_to_print))); } else if (executor.data.has_spec == false) { - buf::WriteManip(executor.ostream).fast_write_sv(std::basic_string_view(container.begin() + begin_idx, size_to_print)); + buf::WriteManip(executor.ostream).fast_write_sv(container.substr(begin_idx, static_cast(size_to_print))); } else { - buf::FMTWriteManip(executor.ostream).write_sv(std::basic_string_view(container.begin() + begin_idx, size_to_print), executor.data.shift); + buf::FMTWriteManip(executor.ostream).write_sv(container.substr(begin_idx, static_cast(size_to_print)), executor.data.shift); } } diff --git a/src/stream/fmt/serializers/format_stdlib.hxx b/src/stream/fmt/serializers/format_stdlib.hxx index 64a3a76c..92f19b71 100644 --- a/src/stream/fmt/serializers/format_stdlib.hxx +++ b/src/stream/fmt/serializers/format_stdlib.hxx @@ -29,7 +29,7 @@ namespace stream::fmt { template struct FormatterType, FormatterExecutor> { static inline void format(const std::basic_stringstream& t, FormatterExecutor& executor) { - return buf::WriteManip(executor.ostream).fast_write_sv(std::basic_string_view(t.str(), t.size())); + return buf::WriteManip(executor.ostream).fast_write_sv(std::basic_string_view(t.str(), t.size())); } }; diff --git a/src/stream/fmt/serializers/std_container/array.hxx b/src/stream/fmt/serializers/std_container/array.hxx index 40e1b029..863a8c3e 100644 --- a/src/stream/fmt/serializers/std_container/array.hxx +++ b/src/stream/fmt/serializers/std_container/array.hxx @@ -1,7 +1,7 @@ #pragma once #include "stream/fmt/context/formatter_executor/formatter_type.hxx" -#include "stream/fmt/context/formatter_executor/std_enumerable.hxx" +#include "stream/fmt/context/formatter_executor/forwarders.hxx" #include @@ -9,7 +9,7 @@ namespace stream::fmt { template struct FormatterType, FormatterExecutor> { static void format(const std::array& t, FormatterExecutor& executor) { - return FormatterType>, FormatterExecutor>::format(t, executor); + detail::forwarders::format_span(std::span(t), executor); } }; } // namespace stream::fmt diff --git a/src/stream/fmt/serializers/std_container/deque.hxx b/src/stream/fmt/serializers/std_container/deque.hxx index 1381532d..b23111e5 100644 --- a/src/stream/fmt/serializers/std_container/deque.hxx +++ b/src/stream/fmt/serializers/std_container/deque.hxx @@ -1,7 +1,7 @@ #pragma once #include "stream/fmt/context/formatter_executor/formatter_type.hxx" -#include "stream/fmt/context/formatter_executor/std_enumerable.hxx" +#include "stream/fmt/context/formatter_executor/forwarders.hxx" #include @@ -9,7 +9,7 @@ namespace stream::fmt { template struct FormatterType, FormatterExecutor> { static void format(const std::deque& t, FormatterExecutor& executor) { - return FormatterType>, FormatterExecutor>::format(t, executor); + detail::forwarders::format_span(std::span(t), executor); } }; } // namespace stream::fmt diff --git a/src/stream/fmt/serializers/std_container/forward_list.hxx b/src/stream/fmt/serializers/std_container/forward_list.hxx index 1ff27b4a..bbf6b5ba 100644 --- a/src/stream/fmt/serializers/std_container/forward_list.hxx +++ b/src/stream/fmt/serializers/std_container/forward_list.hxx @@ -1,7 +1,7 @@ #pragma once #include "stream/fmt/context/formatter_executor/formatter_type.hxx" -#include "stream/fmt/context/formatter_executor/std_enumerable.hxx" +#include "stream/fmt/context/formatter_executor/forwarders.hxx" #include @@ -9,7 +9,7 @@ namespace stream::fmt { template struct FormatterType, FormatterExecutor> { static void format(const std::forward_list& t, FormatterExecutor& executor) { - return FormatterType>, FormatterExecutor>::format(t, executor); + detail::forwarders::format_span(std::span(t), executor); } }; } // namespace stream::fmt diff --git a/src/stream/fmt/serializers/std_container/list.hxx b/src/stream/fmt/serializers/std_container/list.hxx index 152a433e..74462f46 100644 --- a/src/stream/fmt/serializers/std_container/list.hxx +++ b/src/stream/fmt/serializers/std_container/list.hxx @@ -1,7 +1,7 @@ #pragma once #include "stream/fmt/context/formatter_executor/formatter_type.hxx" -#include "stream/fmt/context/formatter_executor/std_enumerable.hxx" +#include "stream/fmt/context/formatter_executor/forwarders.hxx" #include @@ -9,7 +9,7 @@ namespace stream::fmt { template struct FormatterType, FormatterExecutor> { static void format(const std::list& t, FormatterExecutor& executor) { - return FormatterType>, FormatterExecutor>::format(t, executor); + detail::forwarders::format_span(std::span(t), executor); } }; } // namespace stream::fmt diff --git a/src/stream/fmt/serializers/std_container/map.hxx b/src/stream/fmt/serializers/std_container/map.hxx index 9142b947..780477a6 100644 --- a/src/stream/fmt/serializers/std_container/map.hxx +++ b/src/stream/fmt/serializers/std_container/map.hxx @@ -2,7 +2,7 @@ #include #include "stream/fmt/context/formatter_executor/formatter_type.hxx" -#include "stream/fmt/context/formatter_executor/std_enumerable.hxx" +#include "stream/fmt/context/formatter_executor/forwarders.hxx" #include "tuple.hxx" @@ -10,14 +10,14 @@ namespace stream::fmt { template struct FormatterType, FormatterExecutor> { static void format(const std::map& t, FormatterExecutor& executor) { - return FormatterType>, FormatterExecutor>::format(t, executor); + detail::forwarders::format_span(std::span(t), executor); } }; template struct FormatterType, FormatterExecutor> { static void format(const std::multimap& t, FormatterExecutor& executor) { - return FormatterType>, FormatterExecutor>::format(t, executor); + detail::forwarders::format_span(std::span(t), executor); } }; } // namespace stream::fmt diff --git a/src/stream/fmt/serializers/std_container/set.hxx b/src/stream/fmt/serializers/std_container/set.hxx index d26b7e1d..d3b6bf91 100644 --- a/src/stream/fmt/serializers/std_container/set.hxx +++ b/src/stream/fmt/serializers/std_container/set.hxx @@ -1,7 +1,7 @@ #pragma once #include "stream/fmt/context/formatter_executor/formatter_type.hxx" -#include "stream/fmt/context/formatter_executor/std_enumerable.hxx" +#include "stream/fmt/context/formatter_executor/forwarders.hxx" #include @@ -9,14 +9,14 @@ namespace stream::fmt { template struct FormatterType, FormatterExecutor> { static void format(const std::set& t, FormatterExecutor& executor) { - return FormatterType>, FormatterExecutor>::format(t, executor); + detail::forwarders::format_span(std::span(t), executor); } }; template struct FormatterType, FormatterExecutor> { static void format(const std::multiset& t, FormatterExecutor& executor) { - return FormatterType>, FormatterExecutor>::format(t, executor); + detail::forwarders::format_span(std::span(t), executor); } }; } // namespace stream::fmt diff --git a/src/stream/fmt/serializers/std_container/unordered_map.hxx b/src/stream/fmt/serializers/std_container/unordered_map.hxx index a538cf15..4434f1d2 100644 --- a/src/stream/fmt/serializers/std_container/unordered_map.hxx +++ b/src/stream/fmt/serializers/std_container/unordered_map.hxx @@ -1,7 +1,7 @@ #pragma once #include "stream/fmt/context/formatter_executor/formatter_type.hxx" -#include "stream/fmt/context/formatter_executor/std_enumerable.hxx" +#include "stream/fmt/context/formatter_executor/forwarders.hxx" #include #include "tuple.hxx" @@ -10,14 +10,14 @@ namespace stream::fmt { template struct FormatterType, FormatterExecutor> { static void format(const std::unordered_map& t, FormatterExecutor& executor) { - return FormatterType>, FormatterExecutor>::format(t, executor); + detail::forwarders::format_span(std::span(t), executor); } }; template struct FormatterType, FormatterExecutor> { static void format(const std::unordered_multimap& t, FormatterExecutor& executor) { - return FormatterType>, FormatterExecutor>::format(t, executor); + detail::forwarders::format_span(std::span(t), executor); } }; } // namespace stream::fmt diff --git a/src/stream/fmt/serializers/std_container/unordered_set.hxx b/src/stream/fmt/serializers/std_container/unordered_set.hxx index 6f0c824b..2e92383b 100644 --- a/src/stream/fmt/serializers/std_container/unordered_set.hxx +++ b/src/stream/fmt/serializers/std_container/unordered_set.hxx @@ -1,7 +1,7 @@ #pragma once #include "stream/fmt/context/formatter_executor/formatter_type.hxx" -#include "stream/fmt/context/formatter_executor/std_enumerable.hxx" +#include "stream/fmt/context/formatter_executor/forwarders.hxx" #include @@ -9,14 +9,14 @@ namespace stream::fmt { template struct FormatterType, FormatterExecutor> { static void format(const std::unordered_set& t, FormatterExecutor& executor) { - return FormatterType>, FormatterExecutor>::format(t, executor); + detail::forwarders::format_span(std::span(t), executor); } }; template struct FormatterType, FormatterExecutor> { static void format(const std::unordered_multiset& t, FormatterExecutor& executor) { - return FormatterType>, FormatterExecutor>::format(t, executor); + detail::forwarders::format_span(std::span(t), executor); } }; } // namespace stream::fmt diff --git a/src/stream/fmt/serializers/std_container/vector.hxx b/src/stream/fmt/serializers/std_container/vector.hxx index ba3faade..11387dff 100644 --- a/src/stream/fmt/serializers/std_container/vector.hxx +++ b/src/stream/fmt/serializers/std_container/vector.hxx @@ -1,7 +1,7 @@ #pragma once #include "stream/fmt/context/formatter_executor/formatter_type.hxx" -#include "stream/fmt/context/formatter_executor/std_enumerable.hxx" +#include "stream/fmt/context/formatter_executor/forwarders.hxx" #include @@ -9,7 +9,7 @@ namespace stream::fmt { template struct FormatterType, FormatterExecutor> { static void format(const std::vector& t, FormatterExecutor& executor) { - return FormatterType>, FormatterExecutor>::format(t, executor); + detail::forwarders::format_span(std::span(t), executor); } }; } // namespace stream::fmt From a9562f67acdec1c463bad56af719c2bbc6ced264 Mon Sep 17 00:00:00 2001 From: BELLIER Sacha Date: Tue, 1 Apr 2025 19:19:14 +0200 Subject: [PATCH 35/42] fix: remove false positive clang-tidy --- .../fmt/context/basic_context/basic_context_parse_impl.hxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/stream/fmt/context/basic_context/basic_context_parse_impl.hxx b/src/stream/fmt/context/basic_context/basic_context_parse_impl.hxx index f7e8e896..f6b2e2f6 100644 --- a/src/stream/fmt/context/basic_context/basic_context_parse_impl.hxx +++ b/src/stream/fmt/context/basic_context/basic_context_parse_impl.hxx @@ -20,7 +20,7 @@ namespace stream::fmt::context { if (buf::TestAccess(fmtstream).is_equal_to(':', '{')) { buf::Manip(fmtstream).forward(); - executor.data = detail::parse_format_data(executor, fmtstream); + executor.data = ::stream::fmt::detail::parse_format_data(executor, fmtstream); } args_interface.run_type_at(format_idx); From 01ce9e156a5b42ae19240ab4815b216046041a06 Mon Sep 17 00:00:00 2001 From: BELLIER Sacha Date: Tue, 1 Apr 2025 19:56:22 +0200 Subject: [PATCH 36/42] fix: remove mutual inclusion --- .../context/basic_context/basic_context_parse_formatdata.hxx | 2 -- .../fmt/context/basic_context/basic_context_parse_impl.hxx | 2 +- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/src/stream/fmt/context/basic_context/basic_context_parse_formatdata.hxx b/src/stream/fmt/context/basic_context/basic_context_parse_formatdata.hxx index 08908921..5f30329e 100644 --- a/src/stream/fmt/context/basic_context/basic_context_parse_formatdata.hxx +++ b/src/stream/fmt/context/basic_context/basic_context_parse_formatdata.hxx @@ -1,7 +1,5 @@ #pragma once -#include "basic_context.hxx" - #include "stream/fmt/buf/manip.hxx" #include "stream/fmt/buf/test_manip.hxx" #include "stream/fmt/buf/write_manip.hxx" diff --git a/src/stream/fmt/context/basic_context/basic_context_parse_impl.hxx b/src/stream/fmt/context/basic_context/basic_context_parse_impl.hxx index f6b2e2f6..f7e8e896 100644 --- a/src/stream/fmt/context/basic_context/basic_context_parse_impl.hxx +++ b/src/stream/fmt/context/basic_context/basic_context_parse_impl.hxx @@ -20,7 +20,7 @@ namespace stream::fmt::context { if (buf::TestAccess(fmtstream).is_equal_to(':', '{')) { buf::Manip(fmtstream).forward(); - executor.data = ::stream::fmt::detail::parse_format_data(executor, fmtstream); + executor.data = detail::parse_format_data(executor, fmtstream); } args_interface.run_type_at(format_idx); From 19cfc567c32db06f2c977cba4e64a9d81e99829f Mon Sep 17 00:00:00 2001 From: BELLIER Sacha Date: Tue, 1 Apr 2025 22:03:21 +0200 Subject: [PATCH 37/42] fix: remove mutual inclusion --- .../fmt/context/basic_context/basic_context_parse_getindex.hxx | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/stream/fmt/context/basic_context/basic_context_parse_getindex.hxx b/src/stream/fmt/context/basic_context/basic_context_parse_getindex.hxx index 83995cb7..b43014e7 100644 --- a/src/stream/fmt/context/basic_context/basic_context_parse_getindex.hxx +++ b/src/stream/fmt/context/basic_context/basic_context_parse_getindex.hxx @@ -1,7 +1,5 @@ #pragma once -#include "basic_context.hxx" - #include "stream/fmt/buf/manip.hxx" #include "stream/fmt/buf/test_manip.hxx" #include "stream/fmt/buf/write_manip.hxx" From 63e641e9a23285ff608d05efcb6d0dc2c5ffd989 Mon Sep 17 00:00:00 2001 From: BELLIER Sacha Date: Tue, 1 Apr 2025 23:30:41 +0200 Subject: [PATCH 38/42] feat: clang-tidy for c++ checks --- conf | 2 +- scripts/clang-tidy.sh | 2 +- .../text_properties_manager_impl.hxx | 2 -- src/stream/fmt/serializers/parse_stdlib.hxx | 6 ++-- .../fmt/serializers/std_container/queue.hxx | 2 +- .../fmt/serializers/std_container/tuple.hxx | 4 +-- src/stream/json/json_parser.cxx | 12 ++++---- src/stream/profiler/event.hxx | 2 +- src/stream/profiler/get_pid.cxx | 8 ++++-- .../profiler/profiler_event_creator.cxx | 19 +++++++++++-- .../profiler/profiler_event_creator.hxx | 3 ++ src/stream/tester/copy_move_check.hxx | 6 ++-- src/stream/tester/test_suite/test_suite.cxx | 2 ++ src/stream/tester/tests_macros.hxx | 6 ++-- tests/fmt/complex_pattern.cxx | 2 ++ tests/fmt/globber.cxx | 2 ++ tests/fmt/index.cxx | 2 ++ tests/fmt/limits.cxx | 21 ++++++++++++-- tests/fmt/shift.cxx | 2 ++ tests/fmt/specifier.cxx | 10 +++++++ tests/fmt/text_properties.cxx | 28 +++++++++++-------- 21 files changed, 103 insertions(+), 40 deletions(-) diff --git a/conf b/conf index e0a36c8f..2f37cb3e 160000 --- a/conf +++ b/conf @@ -1 +1 @@ -Subproject commit e0a36c8f57c036f7b0dd6be93a285c73ddb4ead0 +Subproject commit 2f37cb3e05200727490262d2bf9c9b22cfbabe77 diff --git a/scripts/clang-tidy.sh b/scripts/clang-tidy.sh index 128a0613..c0e3b159 100755 --- a/scripts/clang-tidy.sh +++ b/scripts/clang-tidy.sh @@ -1,3 +1,3 @@ #!/bin/bash -./conf/linter/clang-tidy.sh //custom:compile_commands_tests --enable-headers $* +./conf/scripts/clang-tidy.py //custom:compile_commands_tests --enable-headers $* --config=./conf/checker/.clang-tidy --config=./conf/linter/RustLike/.clang-tidy diff --git a/src/stream/fmt/context/basic_context/text_properties_manager_impl.hxx b/src/stream/fmt/context/basic_context/text_properties_manager_impl.hxx index 7194b5f7..dcefb92f 100644 --- a/src/stream/fmt/context/basic_context/text_properties_manager_impl.hxx +++ b/src/stream/fmt/context/basic_context/text_properties_manager_impl.hxx @@ -1,7 +1,5 @@ #pragma once -#include "text_properties_manager.hxx" - #include "stream/fmt/buf/manip.hxx" #include "stream/fmt/buf/manip_io.hxx" #include "stream/fmt/buf/test_manip.hxx" diff --git a/src/stream/fmt/serializers/parse_stdlib.hxx b/src/stream/fmt/serializers/parse_stdlib.hxx index 25c5fae5..c2de309a 100644 --- a/src/stream/fmt/serializers/parse_stdlib.hxx +++ b/src/stream/fmt/serializers/parse_stdlib.hxx @@ -6,6 +6,6 @@ #include #include -namespace stream::fmt { - // TODO: -} + + + diff --git a/src/stream/fmt/serializers/std_container/queue.hxx b/src/stream/fmt/serializers/std_container/queue.hxx index 43004603..9f3315cf 100644 --- a/src/stream/fmt/serializers/std_container/queue.hxx +++ b/src/stream/fmt/serializers/std_container/queue.hxx @@ -6,7 +6,7 @@ namespace stream::fmt { template struct FormatterType, FormatterExecutor> { - static void format(const std::queue& t, FormatterExecutor& executor) { + static void format(const std::queue& /*t*/, FormatterExecutor& /*executor*/) { throw std::runtime_error("fmt error: FunctionNotImpl"); } }; diff --git a/src/stream/fmt/serializers/std_container/tuple.hxx b/src/stream/fmt/serializers/std_container/tuple.hxx index 0d351374..bc2aceb5 100644 --- a/src/stream/fmt/serializers/std_container/tuple.hxx +++ b/src/stream/fmt/serializers/std_container/tuple.hxx @@ -10,7 +10,7 @@ namespace stream::fmt::tuple_detail { template constexpr NthTypeOf& get(Args&&... args) { - std::tuple tuple(args...); + std::tuple tuple(std::forward(args)...); return std::get(tuple); } @@ -27,7 +27,7 @@ namespace stream::fmt::tuple_detail { executor.write_type(t); executor.ostream.pushback(','); executor.ostream.pushback(' '); - return tuple_format_rec(executor, args...); + return tuple_format_rec(executor, std::forward(args)...); } } // namespace stream::fmt::tuple_detail diff --git a/src/stream/json/json_parser.cxx b/src/stream/json/json_parser.cxx index 43b8c73f..f252d0ac 100644 --- a/src/stream/json/json_parser.cxx +++ b/src/stream/json/json_parser.cxx @@ -1,5 +1,7 @@ #include "detail.hxx" +#include + #include #include #include @@ -24,13 +26,13 @@ namespace stream::json::detail { } manip.skip_one_of('"'); } else if (parser.is_json_number_begin()) { - float k; + float k = NAN; JsonNumberSerializer::ParseFloat(k, parser); } else if (parser.is_json_boolean_begin()) { - bool k; + bool k = false; JsonBooleanSerializer::ParseBool(k, parser); } else if (parser.is_json_struct_begin()) { - JsonStructSerializer::LoadAllSubObjects(*this, parser, [](JsonParser::Intermediate&, std::size_t, std::string&&, JsonParser& json_parser) { + JsonStructSerializer::LoadAllSubObjects(*this, parser, [](JsonParser::Intermediate&, std::size_t, [[maybe_unused]] std::string&& str, JsonParser& json_parser) { JsonParser::Intermediate intermediate; intermediate.parse(json_parser); }); @@ -52,7 +54,7 @@ namespace stream::json::detail { [](JsonParser::StructIntermediate& t, std::size_t, std::string&& name, JsonParser& json_parser) { JsonParser::Intermediate intermediate; intermediate.parse(json_parser); - t.Objects.insert({std::move(name), std::move(intermediate)}); + t.Objects.insert({std::move(name), intermediate}); }); }; @@ -60,7 +62,7 @@ namespace stream::json::detail { JsonArraySerializer::LoadAllSubObjects(*this, parser, [](JsonParser::ArrayIntermediate& t, std::size_t, JsonParser& json_parser) { JsonParser::Intermediate intermediate; intermediate.parse(json_parser); - t.Objects.emplace_back(std::move(intermediate)); + t.Objects.emplace_back(intermediate); }); }; } // namespace stream::json::detail diff --git a/src/stream/profiler/event.hxx b/src/stream/profiler/event.hxx index f789471d..5ac58082 100644 --- a/src/stream/profiler/event.hxx +++ b/src/stream/profiler/event.hxx @@ -14,7 +14,7 @@ namespace stream::profiler { int get_pid(); - + enum class EventType : char { Unknow = '.', diff --git a/src/stream/profiler/get_pid.cxx b/src/stream/profiler/get_pid.cxx index 78ab09ab..35ec6bb7 100644 --- a/src/stream/profiler/get_pid.cxx +++ b/src/stream/profiler/get_pid.cxx @@ -9,10 +9,12 @@ #include #endif +// NOLINTBEGIN(misc-use-internal-linkage) + namespace stream::profiler { int get_pid() { #ifdef STREAMFORMAT_PLATFORM_LINUX - return getpid(); + #define return getpid(); #endif #ifdef STREAMFORMAT_PLATFORM_WINDOWS @@ -20,4 +22,6 @@ namespace stream::profiler { #endif return 0; } -} // namespace stream::profiler \ No newline at end of file +} // namespace stream::profiler + +// NOLINTEND(misc-use-internal-linkage) diff --git a/src/stream/profiler/profiler_event_creator.cxx b/src/stream/profiler/profiler_event_creator.cxx index f9937691..f4bef63f 100644 --- a/src/stream/profiler/profiler_event_creator.cxx +++ b/src/stream/profiler/profiler_event_creator.cxx @@ -2,7 +2,15 @@ #include "profiler.hxx" namespace stream::profiler { + // TODO(sacha): + // NOLINTBEGIN(bugprone-exception-escape) ScopeProfile::~ScopeProfile() { + terminate(); + } + // NOLINTEND(bugprone-exception-escape) + + void ScopeProfile::terminate() + { stop(); const std::chrono::microseconds us = std::chrono::duration_cast(info.duration); @@ -10,24 +18,28 @@ namespace stream::profiler { const std::chrono::seconds seconds = std::chrono::duration_cast(info.duration); // NOLINTBEGIN(readability-magic-numbers) - if (seconds.count() > 1.5) { + // NOLINTBEGIN(cppcoreguidelines-avoid-magic-numbers) + if (seconds.count() > 2) { profiler_.get_logger().trace("{} : {} seconds", info.name, seconds.count()); - } else if (millis.count() > 5.0) { + } else if (millis.count() > 5) { profiler_.get_logger().trace("{} : {} ms", info.name, millis.count()); } else { profiler_.get_logger().trace("{} : {} us", info.name, us.count()); } + // NOLINTEND(cppcoreguidelines-avoid-magic-numbers) // NOLINTEND(readability-magic-numbers) profiler_.add_event(*this); } + ObjectTracker::ObjectTracker(Profiler& profiler, const std::string& name, const std::string& category) : profiler_(profiler), name_(name), category_(category) { Event const created(name_, category_, EventType::Objectcreated); profiler_.add_event(created); } // NOLINTBEGIN(readability-magic-numbers) +// NOLINTBEGIN(cppcoreguidelines-avoid-magic-numbers) ObjectTracker::ObjectTracker(Profiler& profiler, std::string&& name, std::string&& category) : profiler_(profiler), name_(std::move(name)), category_(std::move(category)) { Event created(name_, category_, EventType::Objectcreated); created.info.id = 10; @@ -45,7 +57,8 @@ namespace stream::profiler { snapshot.info.id = 10; profiler_.add_event(snapshot); } - // NOLINTEND(readability-magic-numbers) + // NOLINTEND(cppcoreguidelines-avoid-magic-numbers) +// NOLINTEND(readability-magic-numbers) void EventCounter::snapshot() { idx_++; diff --git a/src/stream/profiler/profiler_event_creator.hxx b/src/stream/profiler/profiler_event_creator.hxx index ba88984f..f982fca2 100644 --- a/src/stream/profiler/profiler_event_creator.hxx +++ b/src/stream/profiler/profiler_event_creator.hxx @@ -17,6 +17,9 @@ namespace stream::profiler { ~ScopeProfile() override; + public: + void terminate(); + private: Profiler& profiler_; }; diff --git a/src/stream/tester/copy_move_check.hxx b/src/stream/tester/copy_move_check.hxx index 3d3790dc..ae2ec020 100644 --- a/src/stream/tester/copy_move_check.hxx +++ b/src/stream/tester/copy_move_check.hxx @@ -3,16 +3,17 @@ #include "stream/flog.hxx" namespace stream::tester { + // NOLINTBEGIN class CopyMoveCheck { public: static inline flog::BasicLogger logger; public: - CopyMoveCheck(const std::string& name) : name_(name) { + explicit CopyMoveCheck(const std::string& name) : name_(name) { logger.info("CopyMoveCheck {} : {:C:red} ( {:C:red} )", name_, "Default (copy string) Constructor", "TestCopy(const std::string& name)"); } - CopyMoveCheck(std::string&& name) : name_(std::move(name)) { + explicit CopyMoveCheck(std::string&& name) : name_(std::move(name)) { logger.info("CopyMoveCheck {} : {:C:red} ( {:C:red} )", name_, "Default (move string) Constructor", "TestCopy(std::string&& name)"); } @@ -63,4 +64,5 @@ namespace stream::tester { private: std::string name_; }; + // NOLINTEND } // namespace stream::tester diff --git a/src/stream/tester/test_suite/test_suite.cxx b/src/stream/tester/test_suite/test_suite.cxx index d2b7d4cc..a3f39bd2 100644 --- a/src/stream/tester/test_suite/test_suite.cxx +++ b/src/stream/tester/test_suite/test_suite.cxx @@ -26,7 +26,9 @@ namespace stream::tester { namespace stream::tester::detail { TestStatusBank TestSuite::exec_all_tests() { if (parent == nullptr) { + // NOLINTBEGIN(cppcoreguidelines-owning-memory) profiler = new profiler::Profiler("TestSuite_" + name); + // NOLINTEND(cppcoreguidelines-owning-memory) } else { profiler = &get_profiler(); } diff --git a/src/stream/tester/tests_macros.hxx b/src/stream/tester/tests_macros.hxx index 315dddfe..aabadc12 100644 --- a/src/stream/tester/tests_macros.hxx +++ b/src/stream/tester/tests_macros.hxx @@ -34,14 +34,14 @@ namespace stream::test { // Check if equal with file printed #define STREAMFORMAT_TEST_EQ(x, y) \ - if (x == y) \ + if ((x) == (y)) \ STREAMFORMAT_TEST_OK("{C:green}{} == {}", #x, #y); \ else \ STREAMFORMAT_TEST_FAIL("{C:red}{} == {}", #x, #y) // Check if not equal with file printed #define STREAMFORMAT_TEST_NEQ(x, y) \ - if (x != y) \ + if ((x) != (y)) \ STREAMFORMAT_TEST_OK("{C:green}{} != {}", #x, #y); \ else \ STREAMFORMAT_TEST_FAIL("{C:red}{} != {}", #x, #y) @@ -49,7 +49,7 @@ namespace stream::test { #define STREAMFORMAT_TEST_FN(fn, resExpected) \ { \ auto res = fn; \ - if (res == resExpected) \ + if (res == (resExpected)) \ STREAMFORMAT_TEST_OK("{C:green}{} return {}", #fn, res); \ else \ STREAMFORMAT_TEST_FAIL("{C:red}{} return {} instead of {}", #fn, res, resExpected); \ diff --git a/tests/fmt/complex_pattern.cxx b/tests/fmt/complex_pattern.cxx index 3d97ab52..d4b27667 100644 --- a/tests/fmt/complex_pattern.cxx +++ b/tests/fmt/complex_pattern.cxx @@ -5,6 +5,7 @@ // NOLINTBEGIN(misc-const-correctness) // NOLINTBEGIN(readability-magic-numbers) +// NOLINTBEGIN(cppcoreguidelines-avoid-magic-numbers) SFT_TEST_GROUP(FMT, COMPLEX_PATTERN); #define TEST_FMT(fmt_test, expected, ...) SFT_EQ(stream::fmt::format_string(fmt_test, __VA_ARGS__), std::string(expected)) @@ -14,5 +15,6 @@ SFT_TEST_FUNC(COMPLEX_PATTERN, UNESCAPED_ESCAPE_PATTERN) { TEST_FMT("{{0}|", "{9|", 9); TEST_FMT("{{0},", "{9,", 9); } +// NOLINTEND(cppcoreguidelines-avoid-magic-numbers) // NOLINTEND(readability-magic-numbers) // NOLINTEND(misc-const-correctness) diff --git a/tests/fmt/globber.cxx b/tests/fmt/globber.cxx index 6d89fd79..50a77d79 100644 --- a/tests/fmt/globber.cxx +++ b/tests/fmt/globber.cxx @@ -6,6 +6,7 @@ // NOLINTBEGIN(misc-const-correctness) // NOLINTBEGIN(readability-magic-numbers) +// NOLINTBEGIN(cppcoreguidelines-avoid-magic-numbers) SFT_TEST_GROUP(FMT, GLOBBER); #define TEST_GLOBBER(data, glob) \ { \ @@ -67,5 +68,6 @@ SFT_TEST_FUNC(PARSE_GLOBBER, PG_BASIC_WILDCARD) { // SFT_EQ(std::string(test), std::string("test")); } } +// NOLINTEND(cppcoreguidelines-avoid-magic-numbers) // NOLINTEND(readability-magic-numbers) // NOLINTEND(misc-const-correctness) diff --git a/tests/fmt/index.cxx b/tests/fmt/index.cxx index 515951ba..479a8a44 100644 --- a/tests/fmt/index.cxx +++ b/tests/fmt/index.cxx @@ -5,6 +5,7 @@ // NOLINTBEGIN(misc-const-correctness) // NOLINTBEGIN(readability-magic-numbers) +// NOLINTBEGIN(cppcoreguidelines-avoid-magic-numbers) /* SFT_TEST_GROUP(FMT, INDEX); @@ -12,5 +13,6 @@ SFT_TEST_FUNC(INDEX, ReIndexing) { } */ +// NOLINTEND(cppcoreguidelines-avoid-magic-numbers) // NOLINTEND(readability-magic-numbers) // NOLINTEND(misc-const-correctness) diff --git a/tests/fmt/limits.cxx b/tests/fmt/limits.cxx index 2ff945e3..d98f8208 100644 --- a/tests/fmt/limits.cxx +++ b/tests/fmt/limits.cxx @@ -5,13 +5,22 @@ // NOLINTBEGIN(misc-const-correctness) // NOLINTBEGIN(readability-magic-numbers) +// NOLINTBEGIN(cppcoreguidelines-avoid-c-arrays) +// NOLINTBEGIN(hicpp-avoid-c-arrays) +// NOLINTBEGIN(modernize-avoid-c-arrays) +// NOLINTBEGIN(cppcoreguidelines-avoid-magic-numbers) +// NOLINTBEGIN(cppcoreguidelines-pro-bounds-constant-array-index) + +// NOLINTBEGIN(cppcoreguidelines-pro-bounds-array-to-pointer-decay) +// NOLINTBEGIN(hicpp-no-array-decay) + SFT_TEST_GROUP(FMT, LIMITS); #define SFT_TEST_FUNC_LowBufferSize(k) \ SFT_TEST_FUNC(LIMITS, LowBufferSize##k) { \ char buffer[k] = {0}; \ stream::fmt::format_in_char(buffer, "0123456789"); \ - for (int i = 0; i < k; ++i) \ + for (int i = 0; i < (k); ++i) \ SFT_EQ(buffer[i] - '0', i); \ } @@ -49,7 +58,7 @@ SFT_TEST_FUNC(LIMITS, PlainLowBufferSize1) { stream::fmt::buf::StreamView format(fmt_buffer, k); \ stream::fmt::buf::GivenStreamIOManager manager(buffer, k); \ stream::fmt::detail::format_in_manager(manager, false, format); \ - for (int i = 0; i < k; ++i) \ + for (int i = 0; i < (k); ++i) \ SFT_EQ(buffer[i] - '0', i); \ } @@ -108,5 +117,13 @@ SFT_TEST_FUNC(LIMITS, LowBufferSizeArray5Number9) { SFT_EQ(buffer[k] - '0', 9 - k); } } +// NOLINTEND(hicpp-no-array-decay) +// NOLINTEND(cppcoreguidelines-pro-bounds-array-to-pointer-decay) + +// NOLINTEND(cppcoreguidelines-pro-bounds-constant-array-index) +// NOLINTEND(cppcoreguidelines-avoid-magic-numbers) +// NOLINTEND(modernize-avoid-c-arrays) +// NOLINTEND(hicpp-avoid-c-arrays) +// NOLINTEND(cppcoreguidelines-avoid-c-arrays) // NOLINTEND(readability-magic-numbers) // NOLINTEND(misc-const-correctness) diff --git a/tests/fmt/shift.cxx b/tests/fmt/shift.cxx index 82b6e191..eaaae73a 100644 --- a/tests/fmt/shift.cxx +++ b/tests/fmt/shift.cxx @@ -5,6 +5,7 @@ // NOLINTBEGIN(misc-const-correctness) // NOLINTBEGIN(readability-magic-numbers) +// NOLINTBEGIN(cppcoreguidelines-avoid-magic-numbers) SFT_TEST_GROUP(FMT, SHIFT); #define TEST_FMT(fmt_test, expected, ...) SFT_EQ(stream::fmt::format_string(fmt_test, __VA_ARGS__), expected) @@ -301,5 +302,6 @@ SFT_TEST_FUNC(POINTER, CenterLeft) { TEST_FMT("|{:^<11:<|>, size=4}|", "|<<>>>|", test_with_size); TEST_FMT("|{:^<11:>|<, size=4}|", "|>>>test<<<<|", test_with_size); } +// NOLINTEND(cppcoreguidelines-avoid-magic-numbers) // NOLINTEND(readability-magic-numbers) // NOLINTEND(misc-const-correctness) diff --git a/tests/fmt/specifier.cxx b/tests/fmt/specifier.cxx index 0b1d1363..daa3ccdc 100644 --- a/tests/fmt/specifier.cxx +++ b/tests/fmt/specifier.cxx @@ -5,6 +5,11 @@ // NOLINTBEGIN(misc-const-correctness) // NOLINTBEGIN(readability-magic-numbers) +// NOLINTBEGIN(cppcoreguidelines-avoid-c-arrays) +// NOLINTBEGIN(hicpp-avoid-c-arrays) +// NOLINTBEGIN(modernize-avoid-c-arrays) +// NOLINTBEGIN(cppcoreguidelines-avoid-magic-numbers) +// NOLINTBEGIN(cppcoreguidelines-pro-bounds-constant-array-index) SFT_TEST_GROUP(FMT, SPECIFIER); #define TEST_FMT_ARRAY_SPECIFIERS(fmt_test, test_data, expected) SFT_EQ(stream::fmt::format_string(fmt_test, test_data), expected) @@ -46,5 +51,10 @@ SFT_TEST_FUNC(SPECIFIER, BEGIN_END_NESTED_SPECS) { TEST_FMT_ARRAY_SPECIFIERS("{:join=' | ', begin='[', end=']', begin=3, size=5, :#x}", data, "[0x3 | 0x4 | 0x5 | 0x6 | 0x7]"); } +// NOLINTEND(cppcoreguidelines-pro-bounds-constant-array-index) +// NOLINTEND(cppcoreguidelines-avoid-magic-numbers) +// NOLINTEND(modernize-avoid-c-arrays) +// NOLINTEND(hicpp-avoid-c-arrays) +// NOLINTEND(cppcoreguidelines-avoid-c-arrays) // NOLINTEND(readability-magic-numbers) // NOLINTEND(misc-const-correctness) diff --git a/tests/fmt/text_properties.cxx b/tests/fmt/text_properties.cxx index b11720fa..f9ecc045 100644 --- a/tests/fmt/text_properties.cxx +++ b/tests/fmt/text_properties.cxx @@ -5,23 +5,26 @@ // NOLINTBEGIN(misc-const-correctness) // NOLINTBEGIN(readability-magic-numbers) +// NOLINTBEGIN(cppcoreguidelines-avoid-magic-numbers) SFT_TEST_GROUP(FMT, TEXT_PROPERTIES); #define TEST_FMT(fmt_test, expected) SFT_EQ(escaper(stream::fmt::format_string(fmt_test, 0)), escaper(expected)) -static std::string escaper(const std::string& str) { - std::string res; - for (char const c : str) { - if (c != '\033') { - res.push_back(c); - continue; +namespace { + std::string escaper(const std::string& str) { + std::string res; + for (char const c : str) { + if (c != '\033') { + res.push_back(c); + continue; + } + + res.push_back('\\'); + res.push_back('e'); } - - res.push_back('\\'); - res.push_back('e'); - } - return res; + return res; } +} // namespace SFT_TEST_GROUP(TEXT_PROPERTIES, ESCAPER_VALIDATING); #define TEST_ESCAPER(str, str_res) SFT_EQ(escaper(str), str_res) @@ -84,10 +87,11 @@ SFT_TEST_FUNC(TEXT_PROPERTIES, ContextOut) { TEST_FMT_CONTEXT("{} 123 ", "\033[31m TEST_FMT_ContextOut 0 \033[39m 123 "); - // TODO : check before doing a detail::TextPropertiesExecution, should only have one \033[31m + // TODO(sacha): check before doing a detail::TextPropertiesExecution, should only have one \033[31m TEST_FMT_CONTEXT("{C:red}{} 123 ", "\033[31m TEST_FMT_ContextOut 0 123 \033[39m"); TEST_FMT_CONTEXT("{C:+red}{} 123 ", "\033[91m\033[31m TEST_FMT_ContextOut 0 \033[91m 123 \033[39m"); } +// NOLINTEND(cppcoreguidelines-avoid-magic-numbers) // NOLINTEND(readability-magic-numbers) // NOLINTEND(misc-const-correctness) From 5b0db598ef64f2f2b2adc24429ea56b42a8bd23c Mon Sep 17 00:00:00 2001 From: BELLIER Sacha Date: Tue, 1 Apr 2025 23:32:03 +0200 Subject: [PATCH 39/42] fix: clang-format --- src/stream/fmt/serializers/parse_stdlib.hxx | 4 ---- src/stream/fmt/serializers/std_container/queue.hxx | 2 +- src/stream/json/json_parser.cxx | 3 ++- src/stream/profiler/event.hxx | 2 +- src/stream/profiler/get_pid.cxx | 2 +- src/stream/profiler/profiler_event_creator.cxx | 11 +++++------ src/stream/tester/tests_macros.hxx | 6 +++--- tests/fmt/limits.cxx | 4 ++-- tests/fmt/text_properties.cxx | 2 +- 9 files changed, 16 insertions(+), 20 deletions(-) diff --git a/src/stream/fmt/serializers/parse_stdlib.hxx b/src/stream/fmt/serializers/parse_stdlib.hxx index c2de309a..ed988593 100644 --- a/src/stream/fmt/serializers/parse_stdlib.hxx +++ b/src/stream/fmt/serializers/parse_stdlib.hxx @@ -5,7 +5,3 @@ #include #include #include - - - - diff --git a/src/stream/fmt/serializers/std_container/queue.hxx b/src/stream/fmt/serializers/std_container/queue.hxx index 9f3315cf..8d4220d1 100644 --- a/src/stream/fmt/serializers/std_container/queue.hxx +++ b/src/stream/fmt/serializers/std_container/queue.hxx @@ -6,7 +6,7 @@ namespace stream::fmt { template struct FormatterType, FormatterExecutor> { - static void format(const std::queue& /*t*/, FormatterExecutor& /*executor*/) { + static void format(const std::queue& /*t*/, FormatterExecutor& /*executor*/) { throw std::runtime_error("fmt error: FunctionNotImpl"); } }; diff --git a/src/stream/json/json_parser.cxx b/src/stream/json/json_parser.cxx index f252d0ac..30a0fe8e 100644 --- a/src/stream/json/json_parser.cxx +++ b/src/stream/json/json_parser.cxx @@ -32,7 +32,8 @@ namespace stream::json::detail { bool k = false; JsonBooleanSerializer::ParseBool(k, parser); } else if (parser.is_json_struct_begin()) { - JsonStructSerializer::LoadAllSubObjects(*this, parser, [](JsonParser::Intermediate&, std::size_t, [[maybe_unused]] std::string&& str, JsonParser& json_parser) { + JsonStructSerializer::LoadAllSubObjects( + *this, parser, [](JsonParser::Intermediate&, std::size_t, [[maybe_unused]] std::string&& str, JsonParser& json_parser) { JsonParser::Intermediate intermediate; intermediate.parse(json_parser); }); diff --git a/src/stream/profiler/event.hxx b/src/stream/profiler/event.hxx index 5ac58082..f789471d 100644 --- a/src/stream/profiler/event.hxx +++ b/src/stream/profiler/event.hxx @@ -14,7 +14,7 @@ namespace stream::profiler { int get_pid(); - + enum class EventType : char { Unknow = '.', diff --git a/src/stream/profiler/get_pid.cxx b/src/stream/profiler/get_pid.cxx index 35ec6bb7..f1a967b1 100644 --- a/src/stream/profiler/get_pid.cxx +++ b/src/stream/profiler/get_pid.cxx @@ -14,7 +14,7 @@ namespace stream::profiler { int get_pid() { #ifdef STREAMFORMAT_PLATFORM_LINUX - #define return getpid(); +#define return getpid(); #endif #ifdef STREAMFORMAT_PLATFORM_WINDOWS diff --git a/src/stream/profiler/profiler_event_creator.cxx b/src/stream/profiler/profiler_event_creator.cxx index f4bef63f..91cb9ee0 100644 --- a/src/stream/profiler/profiler_event_creator.cxx +++ b/src/stream/profiler/profiler_event_creator.cxx @@ -2,15 +2,14 @@ #include "profiler.hxx" namespace stream::profiler { - // TODO(sacha): - // NOLINTBEGIN(bugprone-exception-escape) + // TODO(sacha): + // NOLINTBEGIN(bugprone-exception-escape) ScopeProfile::~ScopeProfile() { terminate(); } // NOLINTEND(bugprone-exception-escape) - void ScopeProfile::terminate() - { + void ScopeProfile::terminate() { stop(); const std::chrono::microseconds us = std::chrono::duration_cast(info.duration); @@ -39,7 +38,7 @@ namespace stream::profiler { } // NOLINTBEGIN(readability-magic-numbers) -// NOLINTBEGIN(cppcoreguidelines-avoid-magic-numbers) + // NOLINTBEGIN(cppcoreguidelines-avoid-magic-numbers) ObjectTracker::ObjectTracker(Profiler& profiler, std::string&& name, std::string&& category) : profiler_(profiler), name_(std::move(name)), category_(std::move(category)) { Event created(name_, category_, EventType::Objectcreated); created.info.id = 10; @@ -58,7 +57,7 @@ namespace stream::profiler { profiler_.add_event(snapshot); } // NOLINTEND(cppcoreguidelines-avoid-magic-numbers) -// NOLINTEND(readability-magic-numbers) + // NOLINTEND(readability-magic-numbers) void EventCounter::snapshot() { idx_++; diff --git a/src/stream/tester/tests_macros.hxx b/src/stream/tester/tests_macros.hxx index aabadc12..38c1da3f 100644 --- a/src/stream/tester/tests_macros.hxx +++ b/src/stream/tester/tests_macros.hxx @@ -34,14 +34,14 @@ namespace stream::test { // Check if equal with file printed #define STREAMFORMAT_TEST_EQ(x, y) \ - if ((x) == (y)) \ + if ((x) == (y)) \ STREAMFORMAT_TEST_OK("{C:green}{} == {}", #x, #y); \ else \ STREAMFORMAT_TEST_FAIL("{C:red}{} == {}", #x, #y) // Check if not equal with file printed #define STREAMFORMAT_TEST_NEQ(x, y) \ - if ((x) != (y)) \ + if ((x) != (y)) \ STREAMFORMAT_TEST_OK("{C:green}{} != {}", #x, #y); \ else \ STREAMFORMAT_TEST_FAIL("{C:red}{} != {}", #x, #y) @@ -49,7 +49,7 @@ namespace stream::test { #define STREAMFORMAT_TEST_FN(fn, resExpected) \ { \ auto res = fn; \ - if (res == (resExpected)) \ + if (res == (resExpected)) \ STREAMFORMAT_TEST_OK("{C:green}{} return {}", #fn, res); \ else \ STREAMFORMAT_TEST_FAIL("{C:red}{} return {} instead of {}", #fn, res, resExpected); \ diff --git a/tests/fmt/limits.cxx b/tests/fmt/limits.cxx index d98f8208..661420a4 100644 --- a/tests/fmt/limits.cxx +++ b/tests/fmt/limits.cxx @@ -20,7 +20,7 @@ SFT_TEST_GROUP(FMT, LIMITS); SFT_TEST_FUNC(LIMITS, LowBufferSize##k) { \ char buffer[k] = {0}; \ stream::fmt::format_in_char(buffer, "0123456789"); \ - for (int i = 0; i < (k); ++i) \ + for (int i = 0; i < (k); ++i) \ SFT_EQ(buffer[i] - '0', i); \ } @@ -58,7 +58,7 @@ SFT_TEST_FUNC(LIMITS, PlainLowBufferSize1) { stream::fmt::buf::StreamView format(fmt_buffer, k); \ stream::fmt::buf::GivenStreamIOManager manager(buffer, k); \ stream::fmt::detail::format_in_manager(manager, false, format); \ - for (int i = 0; i < (k); ++i) \ + for (int i = 0; i < (k); ++i) \ SFT_EQ(buffer[i] - '0', i); \ } diff --git a/tests/fmt/text_properties.cxx b/tests/fmt/text_properties.cxx index f9ecc045..51d76167 100644 --- a/tests/fmt/text_properties.cxx +++ b/tests/fmt/text_properties.cxx @@ -23,7 +23,7 @@ namespace { res.push_back('e'); } return res; -} + } } // namespace SFT_TEST_GROUP(TEXT_PROPERTIES, ESCAPER_VALIDATING); From ccea07b79218a4ecbd8a114c873b290f31255339 Mon Sep 17 00:00:00 2001 From: BELLIER Sacha Date: Tue, 1 Apr 2025 23:34:38 +0200 Subject: [PATCH 40/42] fix: update index --- conf | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/conf b/conf index 2f37cb3e..bf665290 160000 --- a/conf +++ b/conf @@ -1 +1 @@ -Subproject commit 2f37cb3e05200727490262d2bf9c9b22cfbabe77 +Subproject commit bf66529061acd7f9d9ff751f701c5f2f302e7d11 From 01a531f37b03babc9b927ce92a06f91c8367f1d4 Mon Sep 17 00:00:00 2001 From: BELLIER Sacha Date: Tue, 1 Apr 2025 23:38:37 +0200 Subject: [PATCH 41/42] fix: clang-format ci --- .github/workflows/linter.yml | 2 +- conf | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/linter.yml b/.github/workflows/linter.yml index 4a81efd4..903db544 100644 --- a/.github/workflows/linter.yml +++ b/.github/workflows/linter.yml @@ -16,7 +16,7 @@ jobs: run: sudo apt install clang-format - name: Version run: clang-format --version - - run: ./conf/linter/clang-format.sh + - run: ./conf/script/clang-format.sh clang-tidy: runs-on: ubuntu-latest diff --git a/conf b/conf index bf665290..1645a278 160000 --- a/conf +++ b/conf @@ -1 +1 @@ -Subproject commit bf66529061acd7f9d9ff751f701c5f2f302e7d11 +Subproject commit 1645a278316e6e8e410ecf1240fbf4b56cd508ad From 2ae0d41be10beaf57b0b36c540c877802fa8df41 Mon Sep 17 00:00:00 2001 From: BELLIER Sacha Date: Tue, 1 Apr 2025 23:40:57 +0200 Subject: [PATCH 42/42] fix: clang-format ci --- .github/workflows/linter.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/linter.yml b/.github/workflows/linter.yml index 903db544..78c922df 100644 --- a/.github/workflows/linter.yml +++ b/.github/workflows/linter.yml @@ -16,7 +16,7 @@ jobs: run: sudo apt install clang-format - name: Version run: clang-format --version - - run: ./conf/script/clang-format.sh + - run: ./conf/scripts/clang-format.py clang-tidy: runs-on: ubuntu-latest