From e04ae605a0830f0aed38b148aa85f54772046dcb Mon Sep 17 00:00:00 2001 From: OmniaX-Dev Date: Fri, 20 Mar 2026 22:44:10 +0100 Subject: [PATCH] Big refactor, removed ostd::Utils class and split all functionality into more specific files --- CMakeLists.txt | 4 +- other/build.nr | 2 +- src/ogfx/PixelRenderer.cpp | 8 +- src/ogfx/RawTextInput.hpp | 2 +- src/ostd/data_types/BaseObject.cpp | 1 - src/ostd/data_types/Color.cpp | 19 +- src/ostd/io/Console.cpp | 25 +- src/ostd/io/Console.hpp | 11 +- src/ostd/io/Errors.cpp | 4 +- src/ostd/io/Errors.hpp | 1 - src/ostd/io/FileSystem.cpp | 38 ++ src/ostd/io/FileSystem.hpp | 4 + src/ostd/io/Memory.cpp | 130 +++++ src/ostd/io/Memory.hpp | 58 ++ src/ostd/io/Midi.hpp | 1 - src/ostd/io/OutputHandlers.cpp | 4 +- src/ostd/io/Serial.cpp | 8 +- src/ostd/math/MathUtils.cpp | 31 + src/ostd/math/MathUtils.hpp | 34 ++ src/ostd/math/ShuntingYard.cpp | 8 +- src/ostd/string/String.cpp | 77 ++- src/ostd/string/String.hpp | 9 + src/ostd/utils/{md5.cpp => Hash.cpp} | 42 +- src/ostd/utils/Hash.hpp | 37 ++ src/ostd/utils/Time.cpp | 611 +++++++++++++++++++- src/ostd/utils/Time.hpp | 14 + src/ostd/utils/Utils.cpp | 818 --------------------------- src/ostd/utils/Utils.hpp | 99 ---- src/test.cpp | 8 +- 29 files changed, 1120 insertions(+), 988 deletions(-) create mode 100644 src/ostd/io/Memory.cpp create mode 100644 src/ostd/io/Memory.hpp create mode 100644 src/ostd/math/MathUtils.cpp create mode 100644 src/ostd/math/MathUtils.hpp rename src/ostd/utils/{md5.cpp => Hash.cpp} (85%) create mode 100644 src/ostd/utils/Hash.hpp delete mode 100755 src/ostd/utils/Utils.cpp delete mode 100755 src/ostd/utils/Utils.hpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 7fc71fa..8bbcb8d 100755 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -57,6 +57,7 @@ list(APPEND OSTD_SOURCE_FILES ${CMAKE_CURRENT_LIST_DIR}/src/ostd/io/Midi.cpp ${CMAKE_CURRENT_LIST_DIR}/src/ostd/io/OutputHandlers.cpp ${CMAKE_CURRENT_LIST_DIR}/src/ostd/io/Serial.cpp + ${CMAKE_CURRENT_LIST_DIR}/src/ostd/io/Memory.cpp # math ${CMAKE_CURRENT_LIST_DIR}/src/ostd/math/Geometry.cpp @@ -71,12 +72,11 @@ list(APPEND OSTD_SOURCE_FILES # utils ${CMAKE_CURRENT_LIST_DIR}/src/ostd/utils/Logic.cpp - ${CMAKE_CURRENT_LIST_DIR}/src/ostd/utils/md5.cpp + ${CMAKE_CURRENT_LIST_DIR}/src/ostd/utils/Hash.cpp ${CMAKE_CURRENT_LIST_DIR}/src/ostd/utils/PathFinder.cpp ${CMAKE_CURRENT_LIST_DIR}/src/ostd/utils/QuadTree.cpp ${CMAKE_CURRENT_LIST_DIR}/src/ostd/utils/Signals.cpp ${CMAKE_CURRENT_LIST_DIR}/src/ostd/utils/Time.cpp - ${CMAKE_CURRENT_LIST_DIR}/src/ostd/utils/Utils.cpp ) list(APPEND OGFX_SOURCE_FILES ${CMAKE_CURRENT_LIST_DIR}/src/ogfx/FontUtils.cpp diff --git a/other/build.nr b/other/build.nr index cfa5180..661b0f2 100644 --- a/other/build.nr +++ b/other/build.nr @@ -1 +1 @@ -2022 +2025 diff --git a/src/ogfx/PixelRenderer.cpp b/src/ogfx/PixelRenderer.cpp index 3dd1579..1f530a9 100644 --- a/src/ogfx/PixelRenderer.cpp +++ b/src/ogfx/PixelRenderer.cpp @@ -1,6 +1,6 @@ #include "PixelRenderer.hpp" #include "WindowBase.hpp" -#include "../ostd/utils/Utils.hpp" +#include "../ostd/io/Memory.hpp" namespace ogfx { @@ -107,7 +107,7 @@ namespace ogfx PixelRenderer::~PixelRenderer(void) { if (isInvalid()) return; - ostd::Utils::destroyArray(m_pixels); + ostd::Memory::destroyArray(m_pixels); SDL_DestroyTexture(m_texture); } @@ -117,7 +117,7 @@ namespace ogfx if (!parent.isValid() || !parent.isInitialized()) return; //TODO: Error m_parent = &parent; - m_pixels = ostd::Utils::createArray(parent.getWindowWidth() * parent.getWindowHeight()); + m_pixels = ostd::Memory::createArray(parent.getWindowWidth() * parent.getWindowHeight()); m_texture = SDL_CreateTexture(parent.getSDLRenderer(), SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, parent.getWindowWidth(), parent.getWindowHeight()); m_windowWidth = parent.getWindowWidth(); m_windowHeight = parent.getWindowHeight(); @@ -132,7 +132,7 @@ namespace ogfx if (isInvalid()) return; if (signal.ID == ostd::tBuiltinSignals::WindowResized) { - m_pixels = ostd::Utils::resizeArray(m_pixels, m_parent->getWindowWidth() * m_parent->getWindowHeight()); + m_pixels = ostd::Memory::resizeArray(m_pixels, m_parent->getWindowWidth() * m_parent->getWindowHeight()); SDL_DestroyTexture(m_texture); m_texture = SDL_CreateTexture(m_parent->getSDLRenderer(), SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, m_parent->getWindowWidth(), m_parent->getWindowHeight()); m_windowWidth = m_parent->getWindowWidth(); diff --git a/src/ogfx/RawTextInput.hpp b/src/ogfx/RawTextInput.hpp index 3277f3d..7908fd6 100644 --- a/src/ogfx/RawTextInput.hpp +++ b/src/ogfx/RawTextInput.hpp @@ -21,7 +21,7 @@ #pragma once #include -#include +#include namespace ogfx { diff --git a/src/ostd/data_types/BaseObject.cpp b/src/ostd/data_types/BaseObject.cpp index 6aabc0a..0644f16 100755 --- a/src/ostd/data_types/BaseObject.cpp +++ b/src/ostd/data_types/BaseObject.cpp @@ -1,7 +1,6 @@ #include "BaseObject.hpp" #include "../utils/Signals.hpp" #include "../io/IOHandlers.hpp" -#include "../utils/Utils.hpp" namespace ostd { diff --git a/src/ostd/data_types/Color.cpp b/src/ostd/data_types/Color.cpp index d494983..902c2e5 100755 --- a/src/ostd/data_types/Color.cpp +++ b/src/ostd/data_types/Color.cpp @@ -1,6 +1,5 @@ #include "Color.hpp" #include -#include "../utils/Utils.hpp" #include "../io/Logger.hpp" #include "../io/IOHandlers.hpp" @@ -110,7 +109,7 @@ namespace ostd } if (se.startsWith("0x")) { - int64_t ic = Utils::strToInt(se); + int64_t ic = se.toInt(); union uC32 { uint8_t data[4]; uint32_t value; @@ -131,11 +130,11 @@ namespace ostd OX_WARN("ox::Color::set(const String&) -> Invalid rgb string format: %s.", color_string.c_str()); return *this; } - r = Utils::strToInt(tokens.next()); - g = Utils::strToInt(tokens.next()); - b = Utils::strToInt(tokens.next()); + r = tokens.next().toInt(); + g = tokens.next().toInt(); + b = tokens.next().toInt(); if (tokens.hasNext()) - a = Utils::strToInt(tokens.next()); + a = tokens.next().toInt(); } else { @@ -156,11 +155,11 @@ namespace ostd String Color::hexString(bool include_alpha, String prefix) const { String hex = ""; - hex += Utils::getHexStr(r, false, 1); - hex += Utils::getHexStr(g, false, 1); - hex += Utils::getHexStr(b, false, 1); + hex += String::getHexStr(r, false, 1); + hex += String::getHexStr(g, false, 1); + hex += String::getHexStr(b, false, 1); if (include_alpha) - hex += Utils::getHexStr(a, false, 1); + hex += String::getHexStr(a, false, 1); hex = prefix + String(hex).toUpper(); return hex; } diff --git a/src/ostd/io/Console.cpp b/src/ostd/io/Console.cpp index 44d39d9..d1bc07f 100644 --- a/src/ostd/io/Console.cpp +++ b/src/ostd/io/Console.cpp @@ -1,6 +1,5 @@ #include "Console.hpp" #include "../vendor/TermColor.hpp" -#include "../utils/Utils.hpp" namespace ostd { @@ -53,7 +52,7 @@ void Utils::setConsoleCursorPosition(int32_t x, int32_t y) #include #include -void Utils::clearConsole(void) +void BasicConsole::clearConsole(void) { if (!cur_term) { @@ -65,7 +64,7 @@ void Utils::clearConsole(void) putp(tigetstr( "clear" )); } -void Utils::getConsoleSize(int32_t& outColumns, int32_t& outRows) +void BasicConsole::getConsoleSize(int32_t& outColumns, int32_t& outRows) { struct winsize w; ioctl(STDOUT_FILENO, TIOCGWINSZ, &w); @@ -73,7 +72,7 @@ void Utils::getConsoleSize(int32_t& outColumns, int32_t& outRows) outColumns = w.ws_col; } -void Utils::setConsoleCursorPosition(int32_t x, int32_t y) +void BasicConsole::setConsoleCursorPosition(int32_t x, int32_t y) { printf("\033[%d;%dH",x+1,y+1); } @@ -84,14 +83,14 @@ void Utils::setConsoleCursorPosition(int32_t x, int32_t y) #include #include -void Utils::clearConsole(void) +void BasicConsole::clearConsole(void) { // ANSI escape sequence: clear screen + move cursor to top-left std::printf("\033[2J\033[H"); std::fflush(stdout); } -void Utils::getConsoleSize(int32_t& outColumns, int32_t& outRows) +void BasicConsole::getConsoleSize(int32_t& outColumns, int32_t& outRows) { struct winsize w; ioctl(STDOUT_FILENO, TIOCGWINSZ, &w); @@ -99,7 +98,7 @@ void Utils::getConsoleSize(int32_t& outColumns, int32_t& outRows) outColumns = w.ws_col; } -void Utils::setConsoleCursorPosition(int32_t x, int32_t y) +void BasicConsole::setConsoleCursorPosition(int32_t x, int32_t y) { // ANSI escape sequence: move cursor to (y+1, x+1) std::printf("\033[%d;%dH", y + 1, x + 1); @@ -109,14 +108,14 @@ void Utils::setConsoleCursorPosition(int32_t x, int32_t y) #endif -int32_t Utils::getConsoleWidth(void) +int32_t BasicConsole::getConsoleWidth(void) { int32_t rows = 0, cols = 0; getConsoleSize(cols, rows); return cols; } -int32_t Utils::getConsoleHeight(void) +int32_t BasicConsole::getConsoleHeight(void) { int32_t rows = 0, cols = 0; getConsoleSize(rows, cols); @@ -297,19 +296,19 @@ OutputHandlerBase& InteractiveConsole::reset(void) OutputHandlerBase& InteractiveConsole::clear(void) { - Utils::clearConsole(); + BasicConsole::clearConsole(); return *this; } void InteractiveConsole::getConsoleSize(int32_t& outColumns, int32_t& outRows) { - Utils::getConsoleSize(outColumns, outRows); + BasicConsole::getConsoleSize(outColumns, outRows); } IPoint InteractiveConsole::getConsoleSize(void) { int32_t x = 0, y = 0; - Utils::getConsoleSize(x, y); + BasicConsole::getConsoleSize(x, y); return { x, y }; } @@ -321,7 +320,7 @@ void InteractiveConsole::update(void) void InteractiveConsole::__set_cursor(void) { - Utils::setConsoleCursorPosition(m_cursorPosition.x, m_cursorPosition.y); + BasicConsole::setConsoleCursorPosition(m_cursorPosition.x, m_cursorPosition.y); } void InteractiveConsole::__construct_buffer(void) diff --git a/src/ostd/io/Console.hpp b/src/ostd/io/Console.hpp index bd90ec8..a28dd4f 100644 --- a/src/ostd/io/Console.hpp +++ b/src/ostd/io/Console.hpp @@ -20,7 +20,6 @@ #pragma once -#include #include #include #include @@ -34,6 +33,16 @@ namespace ostd { + class BasicConsole + { + public: + static void clearConsole(void); + static void getConsoleSize(int32_t& outColumns, int32_t& outRows); + static void setConsoleCursorPosition(int32_t x, int32_t y); + static int32_t getConsoleWidth(void); + static int32_t getConsoleHeight(void); + }; + class InteractiveConsole : public OutputHandlerBase { public: enum class eMode { Direct = 0, Buffered = 1 }; diff --git a/src/ostd/io/Errors.cpp b/src/ostd/io/Errors.cpp index 2ea69b8..8e73e85 100755 --- a/src/ostd/io/Errors.cpp +++ b/src/ostd/io/Errors.cpp @@ -24,8 +24,8 @@ namespace ostd if (userData.isValid()) errorMessage += "USER_DATA:\n" + userData.toString() + "\n"; String msgEdit = ""; - msgEdit.add(Utils::getHexStr(m_errGroup)).add("//"); - msgEdit.add(Utils::getHexStr(m_errCode, true, 8)).add(" :: "); + msgEdit.add(String::getHexStr(m_errGroup)).add("//"); + msgEdit.add(String::getHexStr(m_errCode, true, 8)).add(" :: "); if (_file_name != "") { msgEdit.add(_file_name).add(" "); diff --git a/src/ostd/io/Errors.hpp b/src/ostd/io/Errors.hpp index ffbe250..c0c05d8 100755 --- a/src/ostd/io/Errors.hpp +++ b/src/ostd/io/Errors.hpp @@ -22,7 +22,6 @@ #include #include -#include #define ERROR_DATA() String(CPP_STR(__LINE__)), String(__FILE__) diff --git a/src/ostd/io/FileSystem.cpp b/src/ostd/io/FileSystem.cpp index ce0e14e..51c8ab5 100644 --- a/src/ostd/io/FileSystem.cpp +++ b/src/ostd/io/FileSystem.cpp @@ -301,4 +301,42 @@ namespace ostd return ePathStatus::ValidNewFile; return ePathStatus::Invalid; } + + + bool FileSystem::readTextFile(String fileName, std::vector& outLines) + { + String line; + std::ifstream file(fileName.cpp_str()); + if (file.fail()) return false; + outLines.clear(); + while (std::getline(file, line.cpp_str_ref())) + outLines.push_back(line); + return true; + } + + bool FileSystem::readTextFileRaw(String fileName, String& outString) + { + std::vector lines; + if (!readTextFile(fileName, lines)) + return false; + outString.clr(); + for (const auto& line : lines) + outString.add(line).add("\n"); + return true; + } + + bool FileSystem::loadFileFromHppResource(String output_file_path, const char* resource_buffer, unsigned int size) + { + unsigned char ext_len = resource_buffer[0]; + String ext = ""; + for (unsigned char i = 0; i < ext_len; i++) + ext += (char)(resource_buffer[i + 1]); + if (String(output_file_path).trim().toLower().endsWith(ext)) + ext = ""; + std::fstream bin (output_file_path.cpp_str() + ext.cpp_str(), std::ios::out | std::ios::binary); + if (!bin.is_open()) return false; + bin.write(resource_buffer + ext_len + 1, size - ext_len - 1); + bin.close(); + return true; + } } diff --git a/src/ostd/io/FileSystem.hpp b/src/ostd/io/FileSystem.hpp index 3fee6e8..92c4142 100644 --- a/src/ostd/io/FileSystem.hpp +++ b/src/ostd/io/FileSystem.hpp @@ -52,5 +52,9 @@ namespace ostd static bool isValidFileCreationPath(const ostd::String& filePath); static bool isValidDirectoryCreationPath(const ostd::String& directoryPath); static ePathStatus getPathStatus(const ostd::String& path); + + static bool readTextFile(String fileName, std::vector& outLines); + static bool readTextFileRaw(String fileName, String& outString); + static bool loadFileFromHppResource(String output_file_path, const char* resource_buffer, unsigned int size); }; } diff --git a/src/ostd/io/Memory.cpp b/src/ostd/io/Memory.cpp new file mode 100644 index 0000000..c11af87 --- /dev/null +++ b/src/ostd/io/Memory.cpp @@ -0,0 +1,130 @@ +/* + OmniaFramework - A collection of useful functionality + Copyright (C) 2025 OmniaX-Dev + + This file is part of OmniaFramework. + + OmniaFramework is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + OmniaFramework is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with OmniaFramework. If not, see . +*/ + +#include "Memory.hpp" +#include + +namespace ostd +{ + void Memory::printByteStream(const ByteStream& data, StreamIndex start, uint8_t line_len, uint16_t n_rows, OutputHandlerBase& out, int32_t addrHighlight, uint32_t highlightRange, const String& title) + { + StreamIndex end = start + (n_rows * line_len); + if (end > data.size()) end = data.size(); + String titleEdit(title); + if (titleEdit.len() > 12) + titleEdit = titleEdit.substr(0, 12); + else if (titleEdit.len() < 12) + { + int32_t diff = 12 - titleEdit.len(); + for (int32_t i = 0; i < diff; i++) + titleEdit.addChar(' '); + } + bool highlight = addrHighlight >= 0; + uint8_t i = 1; + ByteStream tmp; + uint16_t linew = 1 + 1 + 6 + 1 + 1 + 2 + ((2 + 2) * line_len) + 1 + 4; + out.fg(ConsoleColors::BrightBlue).p(String::duplicateChar('=', linew)).nl(); + if (line_len <= 0xFF) + { + out.fg(ConsoleColors::BrightBlue).p("|"); + out.fg(ConsoleColors::BrightMagenta).p(titleEdit); + out.fg(ConsoleColors::BrightBlue).p("| "); + for (int32_t i = 0; i < line_len; i++) + out.fg(ConsoleColors::Green).p(String::getHexStr(i, false, 1)).p(" "); + out.fg(ConsoleColors::BrightBlue).p("|").nl(); + out.fg(ConsoleColors::BrightBlue).p(String::duplicateChar('=', linew)).nl(); + } + out.fg(ConsoleColors::BrightBlue).p("| "); + out.fg(ConsoleColors::BrightGray).p("0x"); + out.fg(ConsoleColors::BrightCyan).p(String::getHexStr(start, false, 4)).fg(ConsoleColors::BrightBlue).p(" | "); + for (StreamIndex addr = start; addr < end; addr++) + { + tmp.push_back(data[addr]); + if (highlight && (addr >= (uint32_t)addrHighlight && addr < (uint32_t)(addrHighlight + highlightRange))) + out.fg(ConsoleColors::Red); + else if (data[addr] == 0) + out.fg(ConsoleColors::BrightGray); + else + out.fg(ConsoleColors::White); + out.p(String::getHexStr(data[addr], false)).p(" "); + if (i++ % line_len == 0 || addr == end - 1) + { + i = 1; + out.fg(ConsoleColors::BrightBlue).p("|"); + out.nl(); + out.fg(ConsoleColors::BrightBlue).p("|"); + out.fg(ConsoleColors::BrightGray).p(" -------- ").fg(ConsoleColors::BrightBlue).p("|").fg(ConsoleColors::BrightGray).p(" "); + for (const auto& c : tmp) + { + if (isprint(c)) out.fg(ConsoleColors::BrightYellow).pChar((char)c).fg(ConsoleColors::BrightGray).p(" "); + else out.fg(ConsoleColors::BrightGray).p(". "); + } + out.fg(ConsoleColors::BrightBlue).p("| "); + tmp.clear(); + out.reset(); + if (addr == end - 1) break; + out.nl(); + out.fg(ConsoleColors::BrightBlue).p("| "); + out.fg(ConsoleColors::BrightGray).p("0x"); + out.fg(ConsoleColors::BrightCyan).p(String::getHexStr(addr + 1, false, 4)).fg(ConsoleColors::BrightBlue).p(" | "); + } + } + out.nl().fg(ConsoleColors::BrightBlue).p(String::duplicateChar('=', linew)).nl().reset(); + } + + bool Memory::saveByteStreamToFile(const ByteStream& stream, const String& filePath) + { + std::ofstream writeFile; + writeFile.open(filePath.cpp_str(), std::ios::out | std::ios::binary); + writeFile.write((char*)(&stream[0]), stream.size()); + writeFile.close(); + return true; + } + + bool Memory::loadByteStreamFromFile(const String& filePath, ByteStream& outStream) + { + std::ifstream rf(filePath.cpp_str(), std::ios::out | std::ios::binary); + if(!rf) return false; //TODO: Error + uint8_t cell = 0; + while(rf.read((char*)&cell, sizeof(cell))) + outStream.push_back(cell); + if (outStream.size() == 0) return false; //TODO: Error + return true; + } + + ByteStream Memory::stringToByteStream(const String& data) + { + ByteStream bstream; + for (auto& c : data) + bstream.push_back((int8_t)c); + return bstream; + } + + String Memory::byteStreamToString(const ByteStream& data) + { + String out_string = ""; + for (int64_t i = 0; i < data.size(); i++) + { + if (data[i] == 0) break; + out_string.addChar((char)data[i]); + } + return out_string; + } +} diff --git a/src/ostd/io/Memory.hpp b/src/ostd/io/Memory.hpp new file mode 100644 index 0000000..535f684 --- /dev/null +++ b/src/ostd/io/Memory.hpp @@ -0,0 +1,58 @@ +/* + OmniaFramework - A collection of useful functionality + Copyright (C) 2025 OmniaX-Dev + + This file is part of OmniaFramework. + + OmniaFramework is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + OmniaFramework is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with OmniaFramework. If not, see . +*/ + +#pragma once + +#include +#include +#include + +#define STDVEC_CONTAINS(vec, elem) (std::find(vec.begin(), vec.end(), elem) != vec.end()) + +namespace ostd +{ + class Memory + { + public: + static void printByteStream(const ByteStream& data, StreamIndex start, uint8_t line_len, uint16_t n_rows, OutputHandlerBase& out, int32_t addrHighlight = -1, uint32_t highlightRange = 1, const String& title = ""); + static bool saveByteStreamToFile(const ByteStream& stream, const String& filePath); + static bool loadByteStreamFromFile(const String& filePath, ByteStream& outStream); + static ByteStream stringToByteStream(const String& data); + static String byteStreamToString(const ByteStream& data); + + //Array helpers + template + static inline T* createArray(size_t size) + { + T* array = (T*)malloc(size * sizeof(T)); + return array; + } + template + static inline T* resizeArray(T* array, size_t new_size) + { + T* new_array = (T*)realloc(array, new_size * sizeof(T)); + return new_array; + } + static inline void destroyArray(void* array) + { + free(array); + } + }; +} diff --git a/src/ostd/io/Midi.hpp b/src/ostd/io/Midi.hpp index 4d7329c..9ab5028 100644 --- a/src/ostd/io/Midi.hpp +++ b/src/ostd/io/Midi.hpp @@ -21,7 +21,6 @@ #pragma once #include -#include namespace ostd { diff --git a/src/ostd/io/OutputHandlers.cpp b/src/ostd/io/OutputHandlers.cpp index fd7e929..944af72 100755 --- a/src/ostd/io/OutputHandlers.cpp +++ b/src/ostd/io/OutputHandlers.cpp @@ -1,4 +1,3 @@ -#include "../utils/Utils.hpp" #include #include #include "Logger.hpp" @@ -7,6 +6,7 @@ #include "../data_types/BaseObject.hpp" #include "../string/TextStyleParser.hpp" #include "../string/String.hpp" +#include "io/Console.hpp" namespace ostd { @@ -210,7 +210,7 @@ namespace ostd OutputHandlerBase& ConsoleOutputHandler::clear(void) { - Utils::clearConsole(); + BasicConsole::clearConsole(); return *this; } } diff --git a/src/ostd/io/Serial.cpp b/src/ostd/io/Serial.cpp index 540f27a..6b2a739 100755 --- a/src/ostd/io/Serial.cpp +++ b/src/ostd/io/Serial.cpp @@ -1,5 +1,5 @@ #include "Serial.hpp" -#include "../utils/Utils.hpp" +#include "io/Memory.hpp" namespace ostd { @@ -401,7 +401,7 @@ namespace ostd bool SerialIO::w_String(StreamIndex addr, const String& str, bool store_size, bool null_terminate) { m_statuWriting = true; - auto stream = Utils::stringToByteStream(str); + auto stream = Memory::stringToByteStream(str); uint32_t stream_size = stream.size(); if (store_size && !null_terminate) { @@ -446,12 +446,12 @@ namespace ostd uint64_t power = 1; while(power < size()) power *= 2; - Utils::printByteStream(m_data, start, line_len, power / line_len, out); + Memory::printByteStream(m_data, start, line_len, power / line_len, out); } bool SerialIO::saveToFile(const String& filePath) { - return Utils::saveByteStreamToFile(getData(), filePath); + return Memory::saveByteStreamToFile(getData(), filePath); } } } diff --git a/src/ostd/math/MathUtils.cpp b/src/ostd/math/MathUtils.cpp new file mode 100644 index 0000000..5e90585 --- /dev/null +++ b/src/ostd/math/MathUtils.cpp @@ -0,0 +1,31 @@ +/* + OmniaFramework - A collection of useful functionality + Copyright (C) 2025 OmniaX-Dev + + This file is part of OmniaFramework. + + OmniaFramework is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + OmniaFramework is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with OmniaFramework. If not, see . +*/ + +#include "MathUtils.hpp" +#include + +namespace ostd +{ + float MathUtils::map_value(float input, float input_start, float input_end, float output_start, float output_end) + { + float slope = 1.0 * (output_end - output_start) / (input_end - input_start); + return output_start + round(slope * (input - input_start)); + } +} diff --git a/src/ostd/math/MathUtils.hpp b/src/ostd/math/MathUtils.hpp new file mode 100644 index 0000000..0865c84 --- /dev/null +++ b/src/ostd/math/MathUtils.hpp @@ -0,0 +1,34 @@ +/* + OmniaFramework - A collection of useful functionality + Copyright (C) 2025 OmniaX-Dev + + This file is part of OmniaFramework. + + OmniaFramework is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + OmniaFramework is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with OmniaFramework. If not, see . +*/ + +#pragma once + +#include + +namespace ostd +{ + class MathUtils + { + public: + static float map_value(float input, float input_start, float input_end, float output_start, float output_end); + //Implemented in + static int32_t solveIntegerExpression(const String& expr); + }; +} diff --git a/src/ostd/math/ShuntingYard.cpp b/src/ostd/math/ShuntingYard.cpp index 4a1b2f1..ed8259b 100644 --- a/src/ostd/math/ShuntingYard.cpp +++ b/src/ostd/math/ShuntingYard.cpp @@ -1,4 +1,4 @@ -#include "../utils/Utils.hpp" +#include "MathUtils.hpp" #include "../string/String.hpp" #include #include @@ -89,13 +89,13 @@ namespace ostd } const auto s = std::string(b, p); //--------HACKED HEXADECIMAL SUPPORT-------------- - if (!Utils::isInt(s)) + if (!String(s).isInt()) { printf("Invalid character (%s)\n", s.c_str()); exit(0); return {}; } - int64_t tmpInt = Utils::strToInt(s); + int64_t tmpInt = String(s).toInt(); //------------------------------------------------- tokens.push_back(Token { Token::Type::Number, String().add(tmpInt) }); --p; @@ -253,7 +253,7 @@ namespace ostd return queue; } - int32_t Utils::solveIntegerExpression(const String& expr) + int32_t MathUtils::solveIntegerExpression(const String& expr) { // printf("Tokenize\n"); // printf(reportFmt, "Token", "Queue", "Stack", ""); diff --git a/src/ostd/string/String.cpp b/src/ostd/string/String.cpp index cfcb9a2..af0e588 100644 --- a/src/ostd/string/String.cpp +++ b/src/ostd/string/String.cpp @@ -1,8 +1,9 @@ #include "String.hpp" #include #include +#include +#include #include -#include "../utils/Utils.hpp" namespace ostd { @@ -431,7 +432,20 @@ namespace ostd int64_t String::toInt(void) const { if (!isNumeric(false)) return 0; - return Utils::strToInt(m_data); + ostd::String str = String(m_data).trim().toLower(); + if (!str.isInt()) return 0; + int32_t base = 10; + if (str.cpp_str().rfind("0x", 0) == 0) + { + str = str.substr(2); + base = 16; + } + else if (str.cpp_str().rfind("0b", 0) == 0) + { + str = str.substr(2); + base = 2; + } + return strtol(str.c_str(), NULL, base); } float String::toFloat(void) const @@ -455,7 +469,26 @@ namespace ostd iss >> std::noskipws >> f; return iss.eof() && !iss.fail(); } - return Utils::isInt(m_data); + return isInt(); + } + + bool String::isInt(void) const + { + ostd::String str = String(m_data).trim().toLower(); + bool isNumber = std::ranges::all_of(str.begin(), str.end(), [](char c){ return isdigit(c) != 0; }); + return str.isHex() || str.isBin() || isNumber; + } + + bool String::isHex(void) const + { + ostd::String hex = String(m_data).trim().toLower(); + return hex.cpp_str().compare(0, 2, "0x") == 0 && hex.cpp_str().size() > 2 && hex.cpp_str().find_first_not_of("0123456789abcdef", 2) == std::string::npos; + } + + bool String::isBin(void) const + { + ostd::String bin = String(m_data).trim().toLower(); + return bin.cpp_str().compare(0, 2, "0b") == 0 && bin.cpp_str().size() > 2 && bin.cpp_str().find_first_not_of("01", 2) == std::string::npos; } bool String::contains(char c) const @@ -561,6 +594,44 @@ namespace ostd return tokens; } + String String::getHexStr(uint64_t value, bool prefix, uint8_t nbytes) + { + union { + uint64_t val; + uint8_t bytes[8]; + } __tmp_editor; + __tmp_editor.val = value; + if (nbytes < 1 || nbytes > 8) nbytes = 1; + std::ostringstream oss; + if (prefix) oss << "0x"; + for (int8_t b = nbytes - 1; b >= 0; b--) + oss << std::setw(2) << std::setfill('0') << std::uppercase << std::hex << (int)__tmp_editor.bytes[b]; + return oss.str(); + } + + String String::getBinStr(uint64_t value, bool prefix, uint8_t nbytes) + { + union { + uint64_t val; + uint8_t bytes[8]; + } __tmp_editor; + __tmp_editor.val = value; + if (nbytes < 1 || nbytes > 8) nbytes = 1; + std::ostringstream oss; + if (prefix) oss << "0b "; + for (int8_t b = nbytes - 1; b >= 0; b--) + oss << std::bitset<8>((char)__tmp_editor.bytes[b]) << " "; + return oss.str(); + } + + String String::duplicateChar(unsigned char c, uint16_t count) + { + String str = ""; + for (uint16_t i = 0; i < count; i++) + str = str += c; + return str; + } + String operator+(const cpp_string& str1, const String& str) diff --git a/src/ostd/string/String.hpp b/src/ostd/string/String.hpp index cab5602..d00b20e 100644 --- a/src/ostd/string/String.hpp +++ b/src/ostd/string/String.hpp @@ -24,6 +24,8 @@ #include #include +#define STR_BOOL(b) (b ? "true" : "false") + namespace ostd { class String @@ -153,6 +155,9 @@ namespace ostd float toFloat(void) const; double toDouble(void) const; bool isNumeric(bool decimal = false) const; + bool isInt(void) const; + bool isHex(void) const; + bool isBin(void) const; bool contains(char c) const; bool contains(const String& str) const; bool startsWith(const String& str) const; @@ -164,6 +169,10 @@ namespace ostd int32_t lastIndexOf(const String& str) const; Tokens tokenize(const String& delimiter = " ", bool trim_tokens = true, bool allow_white_space_only_tokens = false) const; + static String getHexStr(uint64_t value, bool prefix = true, uint8_t nbytes = 1); + static String getBinStr(uint64_t value, bool prefix = true, uint8_t nbytes = 1); + static String duplicateChar(unsigned char c, uint16_t count); + friend std::ostream& operator<<(std::ostream& out, const String& val); private: diff --git a/src/ostd/utils/md5.cpp b/src/ostd/utils/Hash.cpp similarity index 85% rename from src/ostd/utils/md5.cpp rename to src/ostd/utils/Hash.cpp index f89a852..67a1e39 100644 --- a/src/ostd/utils/md5.cpp +++ b/src/ostd/utils/Hash.cpp @@ -1,4 +1,24 @@ -#include "Utils.hpp" +/* + OmniaFramework - A collection of useful functionality + Copyright (C) 2025 OmniaX-Dev + + This file is part of OmniaFramework. + + OmniaFramework is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + OmniaFramework is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with OmniaFramework. If not, see . +*/ + +#include "Hash.hpp" #include #include #include @@ -53,7 +73,7 @@ namespace { } } -ostd::String ostd::Utils::md5(const ostd::String& _str) { +ostd::String ostd::Hash::md5(const ostd::String& _str) { std::string str = _str.cpp_str(); // Initial state (RFC 1321) uint32_t state[4] = { @@ -67,7 +87,7 @@ ostd::String ostd::Utils::md5(const ostd::String& _str) { // Process full 64-byte chunks size_t i = 0; for (; i + 63 < inputLen; i += 64) { - transform(input + i, state); + __md5_transform(input + i, state); } // Buffer for remaining bytes + padding + length @@ -84,7 +104,7 @@ ostd::String ostd::Utils::md5(const ostd::String& _str) { if (rem > 56) { // Not enough space for length: pad and process this block std::memset(buffer + rem, 0, 64 - rem); - transform(buffer, state); + __md5_transform(buffer, state); // New block with zeros up to 56 std::memset(buffer, 0, 56); } else { @@ -99,11 +119,11 @@ ostd::String ostd::Utils::md5(const ostd::String& _str) { } // Final transform - transform(buffer, state); + __md5_transform(buffer, state); // Output digest (little-endian) uint8_t digest[16]; - encode(digest, state, 16); + __md5_encode(digest, state, 16); std::ostringstream oss; oss << std::hex << std::setfill('0'); @@ -113,14 +133,14 @@ ostd::String ostd::Utils::md5(const ostd::String& _str) { return oss.str(); } -void ostd::Utils::transform(const uint8_t block[64], uint32_t state[4]) { +void ostd::Hash::__md5_transform(const uint8_t block[64], uint32_t state[4]) { uint32_t a = state[0]; uint32_t b = state[1]; uint32_t c = state[2]; uint32_t d = state[3]; uint32_t x[16]; - decode(x, block, 64); + __md5_decode(x, block, 64); // Round 1 FF(a, b, c, d, x[ 0], S11, 0xd76aa478); // 1 @@ -200,7 +220,7 @@ void ostd::Utils::transform(const uint8_t block[64], uint32_t state[4]) { state[3] += d; } -void ostd::Utils::encode(uint8_t* output, const uint32_t* input, size_t len) { +void ostd::Hash::__md5_encode(uint8_t* output, const uint32_t* input, size_t len) { // Convert 32-bit words to bytes (little-endian) for (size_t i = 0, j = 0; j < len; ++i, j += 4) { output[j + 0] = static_cast( input[i] & 0xFF); @@ -210,7 +230,7 @@ void ostd::Utils::encode(uint8_t* output, const uint32_t* input, size_t len) { } } -void ostd::Utils::decode(uint32_t* output, const uint8_t* input, size_t len) { +void ostd::Hash::__md5_decode(uint32_t* output, const uint8_t* input, size_t len) { // Convert bytes to 32-bit words (little-endian) for (size_t i = 0, j = 0; j < len; ++i, j += 4) { output[i] = static_cast(input[j + 0]) @@ -218,4 +238,4 @@ void ostd::Utils::decode(uint32_t* output, const uint8_t* input, size_t len) { | (static_cast(input[j + 2]) << 16) | (static_cast(input[j + 3]) << 24); } -} \ No newline at end of file +} diff --git a/src/ostd/utils/Hash.hpp b/src/ostd/utils/Hash.hpp new file mode 100644 index 0000000..5f70de2 --- /dev/null +++ b/src/ostd/utils/Hash.hpp @@ -0,0 +1,37 @@ +/* + OmniaFramework - A collection of useful functionality + Copyright (C) 2025 OmniaX-Dev + + This file is part of OmniaFramework. + + OmniaFramework is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + OmniaFramework is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with OmniaFramework. If not, see . +*/ + +#pragma once + +#include + +namespace ostd +{ + class Hash + { + public: + static String md5(const String& str); + + private: + static void __md5_transform(const uint8_t block[64], uint32_t state[4]); + static void __md5_encode(uint8_t* output, const uint32_t* input, size_t len); + static void __md5_decode(uint32_t* output, const uint8_t* input, size_t len); + }; +} diff --git a/src/ostd/utils/Time.cpp b/src/ostd/utils/Time.cpp index ff5d067..148ff0e 100644 --- a/src/ostd/utils/Time.cpp +++ b/src/ostd/utils/Time.cpp @@ -1,9 +1,602 @@ #include "Time.hpp" -#include "Utils.hpp" #include +#include "../vendor/TermColor.hpp" +#include "../io/IOHandlers.hpp" + +#define __get_local_time() \ + std::time_t __cur_t = std::time(0); \ + std::tm* __now_t = std::localtime(&__cur_t); namespace ostd { + GameClock::GameClock(void) + { + minutes = 0; + hours = 0; + days = 0; + months = 0; + years = 2022; + m_timeOfDay = 0.0f; + m_totalSeconds = 0.0f; + } + + const float& GameClock::start(void) + { + m_rtClock.start(false, "", eTimeUnits::Seconds); + m_timeOfDay = CAP((1.0f / ((float)(TM_G_MINUTES_FOR_G_HOUR * TM_G_HOURS_FOR_G_DAY))) * ((hours * TM_G_MINUTES_FOR_G_HOUR) + (minutes)), 1.0f); + return m_timeOfDay; + } + + String GameClock::asString(void) + { + std::ostringstream ss; + ss << "Time: " << getFormattedTime() << " / "; + ss << (int32_t)(days + 1) << " " << convertMonth() << " " << (int32_t)(years); + return String(ss.str()); + } + + void GameClock::update(void) + { + int64_t elapsed = m_rtClock.start(false, "", eTimeUnits::Seconds); + if (hours == 255) + hours = TM_G_HOURS_FOR_G_DAY - 1; + else if (hours >= TM_G_HOURS_FOR_G_DAY) + hours = 0; + if (elapsed >= TM_R_SECONDS_FOR_G_MINUTE) + { + minutes++; + if (minutes >= TM_G_MINUTES_FOR_G_HOUR) + { + hours++; + if (hours >= TM_G_HOURS_FOR_G_DAY) + { + days++; + if ((months == (uint8_t)eMonths::January || months == (uint8_t)eMonths::March || + months == (uint8_t)eMonths::May || months == (uint8_t)eMonths::July || + months == (uint8_t)eMonths::August || months == (uint8_t)eMonths::October || + months == (uint8_t)eMonths::December) && days >= TM_G_DAYS_FOR_G_LONG_MONTH) + { + months++; + if (months > (uint8_t)eMonths::December) + { + years++; + months = (uint8_t)eMonths::January; + } + days = 0; + } + else if ((months == (uint8_t)eMonths::April || months == (uint8_t)eMonths::June || + months == (uint8_t)eMonths::September || months == (uint8_t)eMonths::November) && days >= TM_G_DAYS_FOR_G_MEDIUM_MONTH) + { + months++; + days = 0; + } + else if (months == (uint8_t)eMonths::February) + { + if ((years % 4 == 0 && days >= TM_G_DAYS_FOR_G_SHORT_MONTH + 1) || + (years % 4 != 0 && days >= TM_G_DAYS_FOR_G_SHORT_MONTH)) + { + months++; + days = 0; + } + } + hours = 0; + } + minutes = 0; + } + m_totalSeconds += elapsed; + m_rtClock.start(false, "", eTimeUnits::Seconds); + m_timeOfDay = CAP((1.0f / ((float)(TM_G_MINUTES_FOR_G_HOUR * TM_G_HOURS_FOR_G_DAY))) * ((hours * TM_G_MINUTES_FOR_G_HOUR) + (minutes)), 1.0f); + } + } + + String GameClock::getFormattedTime(void) + { + bool zh = (int32_t)(hours / 10) < 1; + bool zm = (int32_t)(minutes / 10) < 1; + std::ostringstream ss; + ss << (zh ? "0" : "") << (int32_t)hours << ":" << (zm ? "0" : "") << (int32_t)minutes; + return String(ss.str()); + } + + String GameClock::convertMonth(void) + { + switch (months) + { + case (uint8_t)eMonths::January: + return "January"; + case (uint8_t)eMonths::February: + return "February"; + case (uint8_t)eMonths::March: + return "March"; + case (uint8_t)eMonths::April: + return "April"; + case (uint8_t)eMonths::May: + return "May"; + case (uint8_t)eMonths::June: + return "June"; + case (uint8_t)eMonths::July: + return "July"; + case (uint8_t)eMonths::August: + return "August"; + case (uint8_t)eMonths::September: + return "September"; + case (uint8_t)eMonths::October: + return "October"; + case (uint8_t)eMonths::November: + return "November"; + case (uint8_t)eMonths::December: + return "December"; + default: + break; + } + return "_MONTH_"; + } + + + + String LocalTime::getFullString(bool include_date, bool include_time, bool day_name, bool month_as_name, bool include_seconds) const + { + std::ostringstream ss; + if (include_date) + { + if (day_name) ss << sWeekDay(true) << " "; + ss << sday(true); + if (month_as_name) ss << " " << smonth(false, true) << " "; + else ss << "." << smonth(true, false) << "."; + ss << syear(); + } + if (include_time) + { + if (include_date) ss << " - "; + ss << shours(true) << ":" << sminutes(true); + if (include_seconds) ss << ":" << sseconds(true); + } + return ss.str(); + } + + int32_t LocalTime::hours(void) const + { + __get_local_time(); + return __now_t->tm_hour; + } + + int32_t LocalTime::minutes(void) const + { + __get_local_time(); + return __now_t->tm_min; + } + + int32_t LocalTime::seconds(void) const + { + __get_local_time(); + return __now_t->tm_sec; + } + + int32_t LocalTime::day(void) const + { + __get_local_time(); + return __now_t->tm_mday; + } + + int32_t LocalTime::month(void) const + { + __get_local_time(); + return __now_t->tm_mon + 1; + } + + int32_t LocalTime::year(void) const + { + __get_local_time(); + return __now_t->tm_year + 1900; + } + + int32_t LocalTime::weekDay(void) const + { + __get_local_time(); + return __now_t->tm_wday; + } + + String LocalTime::shours(bool leading_zero) const + { + std::ostringstream ss; + int32_t h = hours(); + if (leading_zero && h < 10) + ss << "0" << (int32_t)h; + else + ss << (int32_t)h; + return ss.str(); + } + + String LocalTime::sminutes(bool leading_zero) const + { + std::ostringstream ss; + int32_t h = minutes(); + if (leading_zero && h < 10) + ss << "0" << (int32_t)h; + else + ss << (int32_t)h; + return ss.str(); + } + + String LocalTime::sseconds(bool leading_zero) const + { + std::ostringstream ss; + int32_t h = seconds(); + if (leading_zero && h < 10) + ss << "0" << (int32_t)h; + else + ss << (int32_t)h; + return ss.str(); + } + + String LocalTime::sday(bool leading_zero) const + { + std::ostringstream ss; + int32_t h = day(); + if (leading_zero && h < 10) + ss << "0" << (int32_t)h; + else + ss << (int32_t)h; + return ss.str(); + } + + String LocalTime::smonth(bool leading_zero, bool month_name) const + { + int32_t h = month(); + if (month_name) return monthToText(h); + std::ostringstream ss; + if (leading_zero && h < 10) + ss << "0" << (int32_t)h; + else + ss << (int32_t)h; + return ss.str(); + } + + String LocalTime::syear(void) const + { + std::ostringstream ss; + int32_t h = year(); + ss << (int32_t)h; + return ss.str(); + } + + String LocalTime::sWeekDay(bool day_name) const + { + int32_t h = weekDay(); + if (day_name) + return weekDayToText(h); + std::ostringstream ss; + ss << (int32_t)h; + return ss.str(); + } + + String LocalTime::monthToText(int32_t month) const + { + switch (month) + { + case 1: return "January"; + case 2: return "February"; + case 3: return "March"; + case 4: return "April"; + case 5: return "May"; + case 6: return "June"; + case 7: return "July"; + case 8: return "August"; + case 9: return "September"; + case 10: return "October"; + case 11: return "November"; + case 12: return "December"; + default: return "Unknown Month"; + } + } + + String LocalTime::weekDayToText(int32_t day) const + { + switch (day) + { + case 0: return "Sun"; + case 1: return "Mon"; + case 2: return "Tue"; + case 3: return "Wed"; + case 4: return "Thu"; + case 5: return "Fri"; + case 6: return "Sat"; + default: return "Unknown Day"; + } + } + + String LocalTime_IT::monthToText(int32_t month) const + { + switch (month) + { + case 1: return "Gennaio"; + case 2: return "Febraio"; + case 3: return "Marzo"; + case 4: return "Aprile"; + case 5: return "Maggio"; + case 6: return "Giugno"; + case 7: return "Luglio"; + case 8: return "Agosto"; + case 9: return "Settembre"; + case 10: return "Ottobre"; + case 11: return "Novembre"; + case 12: return "Dicembre"; + default: return "Mese sconosciuto"; + } + } + + String LocalTime_IT::weekDayToText(int32_t day) const + { + switch (day) + { + case 0: return "Dom"; + case 1: return "Lun"; + case 2: return "Mar"; + case 3: return "Mer"; + case 4: return "Gio"; + case 5: return "Ven"; + case 6: return "Sab"; + default: return "Giorno Sconosciuto"; + } + } + + String LocalTime_ES::monthToText(int32_t month) const + { + switch (month) + { + case 1: return "Enero"; + case 2: return "Febrero"; + case 3: return "Marzo"; + case 4: return "Abril"; + case 5: return "Mayo"; + case 6: return "Junio"; + case 7: return "Julio"; + case 8: return "Agosto"; + case 9: return "Septiembre"; + case 10: return "Octubre"; + case 11: return "Noviembre"; + case 12: return "Diciembre"; + default: return "Mes desconocido"; + } + } + + String LocalTime_ES::weekDayToText(int32_t day) const + { + switch (day) + { + case 0: return "Domingo"; + case 1: return "Lunes"; + case 2: return "Martes"; + case 3: return "Miercoles"; + case 4: return "Jueves"; + case 5: return "Viernes"; + case 6: return "Sabado"; + default: return "Dia desconoscido"; + } + } + + String LocalTime_DE::monthToText(int32_t month) const + { + switch (month) + { + case 1: return "Januar"; + case 2: return "Februar"; + case 3: return "Marz"; + case 4: return "April"; + case 5: return "May"; + case 6: return "Juni"; + case 7: return "July"; + case 8: return "August"; + case 9: return "September"; + case 10: return "Oktuber"; + case 11: return "November"; + case 12: return "Dizember"; + default: return "Unknown day"; + } + } + + String LocalTime_DE::weekDayToText(int32_t day) const + { + switch (day) + { + case 0: return "So"; + case 1: return "Mo"; + case 2: return "Di"; + case 3: return "Mi"; + case 4: return "Do"; + case 5: return "Fr"; + case 6: return "Sa"; + default: return "Unknown day"; + } + } + + + + uint64_t Timer::start(bool print, String name, eTimeUnits timeUnit, OutputHandlerBase* __destination) + { + m_timeUnit = timeUnit; + m_started = true; + m_name = name; + if (print) + { + if (__destination == nullptr) + { + std::cout << "\n" << termcolor::magenta << "====> "; + std::cout << termcolor::cyan << "Starting test for ["; + std::cout << termcolor::green << m_name; + std::cout << termcolor::cyan << "]"; + std::cout << termcolor::magenta << " <===="; + std::cout << termcolor::reset << "\n"; + } + else + { + m_dest = __destination; + m_dest->nl().fg("magenta").p("====> "); + m_dest->fg("cyan").p("Starting test for ["); + m_dest->fg("green").p(m_name); + m_dest->fg("cyan").p("]"); + m_dest->fg("magenta").p(" <===="); + m_dest->reset().nl(); + } + } + switch (m_timeUnit) + { + case eTimeUnits::Nanoseconds: + m_current = std::chrono::duration_cast (std::chrono::system_clock::now().time_since_epoch()).count(); + return m_current; + case eTimeUnits::Microseconds: + m_current = std::chrono::duration_cast (std::chrono::system_clock::now().time_since_epoch()).count(); + return m_current; + case eTimeUnits::Milliseconds: + m_current = std::chrono::duration_cast (std::chrono::system_clock::now().time_since_epoch()).count(); + return m_current; + case eTimeUnits::Seconds: + m_current = std::chrono::duration_cast (std::chrono::system_clock::now().time_since_epoch()).count(); + return m_current; + default: m_started = false; return 0; + } + m_started = false; + return 0; + } + + uint64_t Timer::startCount(eTimeUnits timeUnit) + { + m_timeUnit = timeUnit; + m_started = true; + switch (m_timeUnit) + { + case eTimeUnits::Nanoseconds: + m_current = std::chrono::duration_cast (std::chrono::system_clock::now().time_since_epoch()).count(); + return m_current; + case eTimeUnits::Microseconds: + m_current = std::chrono::duration_cast (std::chrono::system_clock::now().time_since_epoch()).count(); + return m_current; + case eTimeUnits::Milliseconds: + m_current = std::chrono::duration_cast (std::chrono::system_clock::now().time_since_epoch()).count(); + return m_current; + case eTimeUnits::Seconds: + m_current = std::chrono::duration_cast (std::chrono::system_clock::now().time_since_epoch()).count(); + return m_current; + default: m_started = false; return 0; + } + m_started = false; + return 0; + } + + uint64_t Timer::end(bool print) + { + if (!m_started) return 0; + m_started = false; + m_dest = nullptr; + int64_t diff; + String unit; + switch (m_timeUnit) + { + case eTimeUnits::Nanoseconds: + diff = std::chrono::duration_cast (std::chrono::system_clock::now().time_since_epoch()).count(); + unit = " ns"; + break; + case eTimeUnits::Microseconds: + diff = std::chrono::duration_cast (std::chrono::system_clock::now().time_since_epoch()).count(); + unit = " us"; + break; + case eTimeUnits::Milliseconds: + diff = std::chrono::duration_cast (std::chrono::system_clock::now().time_since_epoch()).count(); + unit = " ms"; + break; + case eTimeUnits::Seconds: + diff = std::chrono::duration_cast (std::chrono::system_clock::now().time_since_epoch()).count(); + unit = " s"; + break; + default: return 0; + } + diff -= m_current; + if (print) + { + if (m_dest == nullptr) + { + std::cout << termcolor::magenta << "====> "; + std::cout << termcolor::cyan << "Test for ["; + std::cout << termcolor::green << m_name; + std::cout << termcolor::cyan << "] took "; + std::cout << termcolor::bright_blue << diff << unit; + std::cout << termcolor::magenta << " <===="; + std::cout << termcolor::reset << "\n"; + } + else + { + m_dest->fg("magenta").p("====> "); + m_dest->fg("cyan").p("Test for ["); + m_dest->fg("green").p(m_name); + m_dest->fg("cyan").p("] took "); + m_dest->fg("b-blue").p(diff).p(unit); + m_dest->nl().nl().fg("magenta").p(" <===="); + m_dest->reset().nl(); + } + } + return diff; + } + + uint64_t Timer::endCount(bool stop) + { + if (!m_started) return 0; + m_started = !stop; + int64_t diff; + switch (m_timeUnit) + { + case eTimeUnits::Nanoseconds: + diff = std::chrono::duration_cast (std::chrono::system_clock::now().time_since_epoch()).count(); + break; + case eTimeUnits::Microseconds: + diff = std::chrono::duration_cast (std::chrono::system_clock::now().time_since_epoch()).count(); + break; + case eTimeUnits::Milliseconds: + diff = std::chrono::duration_cast (std::chrono::system_clock::now().time_since_epoch()).count(); + break; + case eTimeUnits::Seconds: + diff = std::chrono::duration_cast (std::chrono::system_clock::now().time_since_epoch()).count(); + break; + default: return 0; + } + diff -= m_current; + return diff; + } + + uint64_t Timer::restart(eTimeUnits timeUnit) + { + if (!m_started) + { + startCount(timeUnit); + return 0; + } + uint64_t elapsed = endCount(); + startCount(timeUnit); + return elapsed; + } + + uint64_t Timer::getEpoch(eTimeUnits timeUnit) + { + switch (timeUnit) + { + case eTimeUnits::Nanoseconds: + return std::chrono::duration_cast (std::chrono::system_clock::now().time_since_epoch()).count(); + break; + case eTimeUnits::Microseconds: + return std::chrono::duration_cast (std::chrono::system_clock::now().time_since_epoch()).count(); + break; + case eTimeUnits::Milliseconds: + return std::chrono::duration_cast (std::chrono::system_clock::now().time_since_epoch()).count(); + break; + case eTimeUnits::Seconds: + return std::chrono::duration_cast (std::chrono::system_clock::now().time_since_epoch()).count(); + break; + default: return 0; + } + return 0; + } + + + StepTimer& StepTimer::create(double updatesPerSecond, StepTimer::Callback callback) { m_targetDt = 1.0 / updatesPerSecond; @@ -50,8 +643,13 @@ namespace ostd - // Utils - void Utils::sleep(uint32_t __time, eTimeUnits __unit) + + void Time::startRunningTimer(void) + { + s_startTime_ms = std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); + } + + void Time::sleep(uint32_t __time, eTimeUnits __unit) { switch (__unit) { @@ -70,12 +668,13 @@ namespace ostd default: break; } } - uint64_t Utils::getRunningTime_ms(void) + + uint64_t Time::getRunningTime_ms(void) { - return std::chrono::duration_cast (std::chrono::system_clock::now().time_since_epoch()).count() - Utils::s_startTime_ms; + return std::chrono::duration_cast (std::chrono::system_clock::now().time_since_epoch()).count() - s_startTime_ms; } - String Utils::secondsToFormattedString(int32_t totalSeconds) + String Time::secondsToFormattedString(int32_t totalSeconds) { int32_t hours = totalSeconds / 3600; int32_t minutes = (totalSeconds % 3600) / 60; diff --git a/src/ostd/utils/Time.hpp b/src/ostd/utils/Time.hpp index 1eaf75c..627d923 100644 --- a/src/ostd/utils/Time.hpp +++ b/src/ostd/utils/Time.hpp @@ -211,4 +211,18 @@ namespace ostd String monthToText(int32_t month) const override; String weekDayToText(int32_t day) const override; }; + + class Time + { + public: + static void startRunningTimer(void); + static inline const uint64_t getStartTime(void) { return s_startTime_ms; } + static void sleep(uint32_t __time, eTimeUnits __unit = eTimeUnits::Milliseconds); + static uint64_t getRunningTime_ms(void); + static String secondsToFormattedString(int32_t totalSeconds); + + private: + inline static uint64_t s_startTime_ms; + + }; } diff --git a/src/ostd/utils/Utils.cpp b/src/ostd/utils/Utils.cpp deleted file mode 100755 index 6291d58..0000000 --- a/src/ostd/utils/Utils.cpp +++ /dev/null @@ -1,818 +0,0 @@ -#include "Utils.hpp" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "../vendor/TermColor.hpp" -#include "../string/String.hpp" -#include "../io/IOHandlers.hpp" - -#define __get_local_time() \ - std::time_t __cur_t = std::time(0); \ - std::tm* __now_t = std::localtime(&__cur_t); - -namespace ostd -{ - GameClock::GameClock(void) - { - minutes = 0; - hours = 0; - days = 0; - months = 0; - years = 2022; - m_timeOfDay = 0.0f; - m_totalSeconds = 0.0f; - } - - const float& GameClock::start(void) - { - m_rtClock.start(false, "", eTimeUnits::Seconds); - m_timeOfDay = CAP((1.0f / ((float)(TM_G_MINUTES_FOR_G_HOUR * TM_G_HOURS_FOR_G_DAY))) * ((hours * TM_G_MINUTES_FOR_G_HOUR) + (minutes)), 1.0f); - return m_timeOfDay; - } - - String GameClock::asString(void) - { - std::ostringstream ss; - ss << "Time: " << getFormattedTime() << " / "; - ss << (int32_t)(days + 1) << " " << convertMonth() << " " << (int32_t)(years); - return String(ss.str()); - } - - void GameClock::update(void) - { - int64_t elapsed = m_rtClock.start(false, "", eTimeUnits::Seconds); - if (hours == 255) - hours = TM_G_HOURS_FOR_G_DAY - 1; - else if (hours >= TM_G_HOURS_FOR_G_DAY) - hours = 0; - if (elapsed >= TM_R_SECONDS_FOR_G_MINUTE) - { - minutes++; - if (minutes >= TM_G_MINUTES_FOR_G_HOUR) - { - hours++; - if (hours >= TM_G_HOURS_FOR_G_DAY) - { - days++; - if ((months == (uint8_t)eMonths::January || months == (uint8_t)eMonths::March || - months == (uint8_t)eMonths::May || months == (uint8_t)eMonths::July || - months == (uint8_t)eMonths::August || months == (uint8_t)eMonths::October || - months == (uint8_t)eMonths::December) && days >= TM_G_DAYS_FOR_G_LONG_MONTH) - { - months++; - if (months > (uint8_t)eMonths::December) - { - years++; - months = (uint8_t)eMonths::January; - } - days = 0; - } - else if ((months == (uint8_t)eMonths::April || months == (uint8_t)eMonths::June || - months == (uint8_t)eMonths::September || months == (uint8_t)eMonths::November) && days >= TM_G_DAYS_FOR_G_MEDIUM_MONTH) - { - months++; - days = 0; - } - else if (months == (uint8_t)eMonths::February) - { - if ((years % 4 == 0 && days >= TM_G_DAYS_FOR_G_SHORT_MONTH + 1) || - (years % 4 != 0 && days >= TM_G_DAYS_FOR_G_SHORT_MONTH)) - { - months++; - days = 0; - } - } - hours = 0; - } - minutes = 0; - } - m_totalSeconds += elapsed; - m_rtClock.start(false, "", eTimeUnits::Seconds); - m_timeOfDay = CAP((1.0f / ((float)(TM_G_MINUTES_FOR_G_HOUR * TM_G_HOURS_FOR_G_DAY))) * ((hours * TM_G_MINUTES_FOR_G_HOUR) + (minutes)), 1.0f); - } - } - - String GameClock::getFormattedTime(void) - { - bool zh = (int32_t)(hours / 10) < 1; - bool zm = (int32_t)(minutes / 10) < 1; - std::ostringstream ss; - ss << (zh ? "0" : "") << (int32_t)hours << ":" << (zm ? "0" : "") << (int32_t)minutes; - return String(ss.str()); - } - - String GameClock::convertMonth(void) - { - switch (months) - { - case (uint8_t)eMonths::January: - return "January"; - case (uint8_t)eMonths::February: - return "February"; - case (uint8_t)eMonths::March: - return "March"; - case (uint8_t)eMonths::April: - return "April"; - case (uint8_t)eMonths::May: - return "May"; - case (uint8_t)eMonths::June: - return "June"; - case (uint8_t)eMonths::July: - return "July"; - case (uint8_t)eMonths::August: - return "August"; - case (uint8_t)eMonths::September: - return "September"; - case (uint8_t)eMonths::October: - return "October"; - case (uint8_t)eMonths::November: - return "November"; - case (uint8_t)eMonths::December: - return "December"; - default: - break; - } - return "_MONTH_"; - } - - - - String LocalTime::getFullString(bool include_date, bool include_time, bool day_name, bool month_as_name, bool include_seconds) const - { - std::ostringstream ss; - if (include_date) - { - if (day_name) ss << sWeekDay(true) << " "; - ss << sday(true); - if (month_as_name) ss << " " << smonth(false, true) << " "; - else ss << "." << smonth(true, false) << "."; - ss << syear(); - } - if (include_time) - { - if (include_date) ss << " - "; - ss << shours(true) << ":" << sminutes(true); - if (include_seconds) ss << ":" << sseconds(true); - } - return ss.str(); - } - - int32_t LocalTime::hours(void) const - { - __get_local_time(); - return __now_t->tm_hour; - } - - int32_t LocalTime::minutes(void) const - { - __get_local_time(); - return __now_t->tm_min; - } - - int32_t LocalTime::seconds(void) const - { - __get_local_time(); - return __now_t->tm_sec; - } - - int32_t LocalTime::day(void) const - { - __get_local_time(); - return __now_t->tm_mday; - } - - int32_t LocalTime::month(void) const - { - __get_local_time(); - return __now_t->tm_mon + 1; - } - - int32_t LocalTime::year(void) const - { - __get_local_time(); - return __now_t->tm_year + 1900; - } - - int32_t LocalTime::weekDay(void) const - { - __get_local_time(); - return __now_t->tm_wday; - } - - String LocalTime::shours(bool leading_zero) const - { - std::ostringstream ss; - int32_t h = hours(); - if (leading_zero && h < 10) - ss << "0" << (int32_t)h; - else - ss << (int32_t)h; - return ss.str(); - } - - String LocalTime::sminutes(bool leading_zero) const - { - std::ostringstream ss; - int32_t h = minutes(); - if (leading_zero && h < 10) - ss << "0" << (int32_t)h; - else - ss << (int32_t)h; - return ss.str(); - } - - String LocalTime::sseconds(bool leading_zero) const - { - std::ostringstream ss; - int32_t h = seconds(); - if (leading_zero && h < 10) - ss << "0" << (int32_t)h; - else - ss << (int32_t)h; - return ss.str(); - } - - String LocalTime::sday(bool leading_zero) const - { - std::ostringstream ss; - int32_t h = day(); - if (leading_zero && h < 10) - ss << "0" << (int32_t)h; - else - ss << (int32_t)h; - return ss.str(); - } - - String LocalTime::smonth(bool leading_zero, bool month_name) const - { - int32_t h = month(); - if (month_name) return monthToText(h); - std::ostringstream ss; - if (leading_zero && h < 10) - ss << "0" << (int32_t)h; - else - ss << (int32_t)h; - return ss.str(); - } - - String LocalTime::syear(void) const - { - std::ostringstream ss; - int32_t h = year(); - ss << (int32_t)h; - return ss.str(); - } - - String LocalTime::sWeekDay(bool day_name) const - { - int32_t h = weekDay(); - if (day_name) - return weekDayToText(h); - std::ostringstream ss; - ss << (int32_t)h; - return ss.str(); - } - - String LocalTime::monthToText(int32_t month) const - { - switch (month) - { - case 1: return "January"; - case 2: return "February"; - case 3: return "March"; - case 4: return "April"; - case 5: return "May"; - case 6: return "June"; - case 7: return "July"; - case 8: return "August"; - case 9: return "September"; - case 10: return "October"; - case 11: return "November"; - case 12: return "December"; - default: return "Unknown Month"; - } - } - - String LocalTime::weekDayToText(int32_t day) const - { - switch (day) - { - case 0: return "Sun"; - case 1: return "Mon"; - case 2: return "Tue"; - case 3: return "Wed"; - case 4: return "Thu"; - case 5: return "Fri"; - case 6: return "Sat"; - default: return "Unknown Day"; - } - } - - String LocalTime_IT::monthToText(int32_t month) const - { - switch (month) - { - case 1: return "Gennaio"; - case 2: return "Febraio"; - case 3: return "Marzo"; - case 4: return "Aprile"; - case 5: return "Maggio"; - case 6: return "Giugno"; - case 7: return "Luglio"; - case 8: return "Agosto"; - case 9: return "Settembre"; - case 10: return "Ottobre"; - case 11: return "Novembre"; - case 12: return "Dicembre"; - default: return "Mese sconosciuto"; - } - } - - String LocalTime_IT::weekDayToText(int32_t day) const - { - switch (day) - { - case 0: return "Dom"; - case 1: return "Lun"; - case 2: return "Mar"; - case 3: return "Mer"; - case 4: return "Gio"; - case 5: return "Ven"; - case 6: return "Sab"; - default: return "Giorno Sconosciuto"; - } - } - - String LocalTime_ES::monthToText(int32_t month) const - { - switch (month) - { - case 1: return "Enero"; - case 2: return "Febrero"; - case 3: return "Marzo"; - case 4: return "Abril"; - case 5: return "Mayo"; - case 6: return "Junio"; - case 7: return "Julio"; - case 8: return "Agosto"; - case 9: return "Septiembre"; - case 10: return "Octubre"; - case 11: return "Noviembre"; - case 12: return "Diciembre"; - default: return "Mes desconocido"; - } - } - - String LocalTime_ES::weekDayToText(int32_t day) const - { - switch (day) - { - case 0: return "Domingo"; - case 1: return "Lunes"; - case 2: return "Martes"; - case 3: return "Miercoles"; - case 4: return "Jueves"; - case 5: return "Viernes"; - case 6: return "Sabado"; - default: return "Dia desconoscido"; - } - } - - String LocalTime_DE::monthToText(int32_t month) const - { - switch (month) - { - case 1: return "Januar"; - case 2: return "Februar"; - case 3: return "Marz"; - case 4: return "April"; - case 5: return "May"; - case 6: return "Juni"; - case 7: return "July"; - case 8: return "August"; - case 9: return "September"; - case 10: return "Oktuber"; - case 11: return "November"; - case 12: return "Dizember"; - default: return "Unknown day"; - } - } - - String LocalTime_DE::weekDayToText(int32_t day) const - { - switch (day) - { - case 0: return "So"; - case 1: return "Mo"; - case 2: return "Di"; - case 3: return "Mi"; - case 4: return "Do"; - case 5: return "Fr"; - case 6: return "Sa"; - default: return "Unknown day"; - } - } - - - - uint64_t Timer::start(bool print, String name, eTimeUnits timeUnit, OutputHandlerBase* __destination) - { - m_timeUnit = timeUnit; - m_started = true; - m_name = name; - if (print) - { - if (__destination == nullptr) - { - std::cout << "\n" << termcolor::magenta << "====> "; - std::cout << termcolor::cyan << "Starting test for ["; - std::cout << termcolor::green << m_name; - std::cout << termcolor::cyan << "]"; - std::cout << termcolor::magenta << " <===="; - std::cout << termcolor::reset << "\n"; - } - else - { - m_dest = __destination; - m_dest->nl().fg("magenta").p("====> "); - m_dest->fg("cyan").p("Starting test for ["); - m_dest->fg("green").p(m_name); - m_dest->fg("cyan").p("]"); - m_dest->fg("magenta").p(" <===="); - m_dest->reset().nl(); - } - } - switch (m_timeUnit) - { - case eTimeUnits::Nanoseconds: - m_current = std::chrono::duration_cast (std::chrono::system_clock::now().time_since_epoch()).count(); - return m_current; - case eTimeUnits::Microseconds: - m_current = std::chrono::duration_cast (std::chrono::system_clock::now().time_since_epoch()).count(); - return m_current; - case eTimeUnits::Milliseconds: - m_current = std::chrono::duration_cast (std::chrono::system_clock::now().time_since_epoch()).count(); - return m_current; - case eTimeUnits::Seconds: - m_current = std::chrono::duration_cast (std::chrono::system_clock::now().time_since_epoch()).count(); - return m_current; - default: m_started = false; return 0; - } - m_started = false; - return 0; - } - - uint64_t Timer::startCount(eTimeUnits timeUnit) - { - m_timeUnit = timeUnit; - m_started = true; - switch (m_timeUnit) - { - case eTimeUnits::Nanoseconds: - m_current = std::chrono::duration_cast (std::chrono::system_clock::now().time_since_epoch()).count(); - return m_current; - case eTimeUnits::Microseconds: - m_current = std::chrono::duration_cast (std::chrono::system_clock::now().time_since_epoch()).count(); - return m_current; - case eTimeUnits::Milliseconds: - m_current = std::chrono::duration_cast (std::chrono::system_clock::now().time_since_epoch()).count(); - return m_current; - case eTimeUnits::Seconds: - m_current = std::chrono::duration_cast (std::chrono::system_clock::now().time_since_epoch()).count(); - return m_current; - default: m_started = false; return 0; - } - m_started = false; - return 0; - } - - uint64_t Timer::end(bool print) - { - if (!m_started) return 0; - m_started = false; - m_dest = nullptr; - int64_t diff; - String unit; - switch (m_timeUnit) - { - case eTimeUnits::Nanoseconds: - diff = std::chrono::duration_cast (std::chrono::system_clock::now().time_since_epoch()).count(); - unit = " ns"; - break; - case eTimeUnits::Microseconds: - diff = std::chrono::duration_cast (std::chrono::system_clock::now().time_since_epoch()).count(); - unit = " us"; - break; - case eTimeUnits::Milliseconds: - diff = std::chrono::duration_cast (std::chrono::system_clock::now().time_since_epoch()).count(); - unit = " ms"; - break; - case eTimeUnits::Seconds: - diff = std::chrono::duration_cast (std::chrono::system_clock::now().time_since_epoch()).count(); - unit = " s"; - break; - default: return 0; - } - diff -= m_current; - if (print) - { - if (m_dest == nullptr) - { - std::cout << termcolor::magenta << "====> "; - std::cout << termcolor::cyan << "Test for ["; - std::cout << termcolor::green << m_name; - std::cout << termcolor::cyan << "] took "; - std::cout << termcolor::bright_blue << diff << unit; - std::cout << termcolor::magenta << " <===="; - std::cout << termcolor::reset << "\n"; - } - else - { - m_dest->fg("magenta").p("====> "); - m_dest->fg("cyan").p("Test for ["); - m_dest->fg("green").p(m_name); - m_dest->fg("cyan").p("] took "); - m_dest->fg("b-blue").p(diff).p(unit); - m_dest->nl().nl().fg("magenta").p(" <===="); - m_dest->reset().nl(); - } - } - return diff; - } - - uint64_t Timer::endCount(bool stop) - { - if (!m_started) return 0; - m_started = !stop; - int64_t diff; - switch (m_timeUnit) - { - case eTimeUnits::Nanoseconds: - diff = std::chrono::duration_cast (std::chrono::system_clock::now().time_since_epoch()).count(); - break; - case eTimeUnits::Microseconds: - diff = std::chrono::duration_cast (std::chrono::system_clock::now().time_since_epoch()).count(); - break; - case eTimeUnits::Milliseconds: - diff = std::chrono::duration_cast (std::chrono::system_clock::now().time_since_epoch()).count(); - break; - case eTimeUnits::Seconds: - diff = std::chrono::duration_cast (std::chrono::system_clock::now().time_since_epoch()).count(); - break; - default: return 0; - } - diff -= m_current; - return diff; - } - - uint64_t Timer::restart(eTimeUnits timeUnit) - { - if (!m_started) - { - startCount(timeUnit); - return 0; - } - uint64_t elapsed = endCount(); - startCount(timeUnit); - return elapsed; - } - - uint64_t Timer::getEpoch(eTimeUnits timeUnit) - { - switch (timeUnit) - { - case eTimeUnits::Nanoseconds: - return std::chrono::duration_cast (std::chrono::system_clock::now().time_since_epoch()).count(); - break; - case eTimeUnits::Microseconds: - return std::chrono::duration_cast (std::chrono::system_clock::now().time_since_epoch()).count(); - break; - case eTimeUnits::Milliseconds: - return std::chrono::duration_cast (std::chrono::system_clock::now().time_since_epoch()).count(); - break; - case eTimeUnits::Seconds: - return std::chrono::duration_cast (std::chrono::system_clock::now().time_since_epoch()).count(); - break; - default: return 0; - } - return 0; - } - - - - void Utils::init(void) - { - Utils::s_startTime_ms = std::chrono::duration_cast - (std::chrono::system_clock::now().time_since_epoch()).count(); - } - bool Utils::isHex(String hex) - { - hex = String(hex).trim().toLower(); - return hex.cpp_str().compare(0, 2, "0x") == 0 && - hex.cpp_str().size() > 2 && - hex.cpp_str().find_first_not_of("0123456789abcdef", 2) == std::string::npos; - } - bool Utils::isBin(String bin) - { - bin = String(bin).trim().toLower(); - return bin.cpp_str().compare(0, 2, "0b") == 0 && - bin.cpp_str().size() > 2 && - bin.cpp_str().find_first_not_of("01", 2) == std::string::npos; - } - bool Utils::isInt(String str) - { - str = String(str).trim().toLower(); - bool isNumber = std::ranges::all_of(str.begin(), str.end(), - [](char c){ return isdigit(c) != 0; }); - return Utils::isHex(str) || Utils::isBin(str) || isNumber; - } - int64_t Utils::strToInt(String str) - { - str = String(str).trim().toLower(); - if (!Utils::isInt(str)) return 0; - int32_t base = 10; - if (str.cpp_str().rfind("0x", 0) == 0) - { - str = str.substr(2); - base = 16; - } - else if (str.cpp_str().rfind("0b", 0) == 0) - { - str = str.substr(2); - base = 2; - } - return strtol(str.c_str(), NULL, base); - } - bool Utils::readFile(String fileName, std::vector& outLines) - { - String line; - std::ifstream file(fileName.cpp_str()); - if (file.fail()) return false; - outLines.clear(); - while (std::getline(file, line.cpp_str_ref())) - outLines.push_back(line); - return true; - } - String Utils::getHexStr(uint64_t value, bool prefix, uint8_t nbytes) - { - union { - uint64_t val; - uint8_t bytes[8]; - } __tmp_editor; - __tmp_editor.val = value; - if (nbytes < 1 || nbytes > 8) nbytes = 1; - std::ostringstream oss; - if (prefix) oss << "0x"; - for (int8_t b = nbytes - 1; b >= 0; b--) - oss << std::setw(2) << std::setfill('0') << std::uppercase << std::hex << (int)__tmp_editor.bytes[b]; - return oss.str(); - } - String Utils::getBinStr(uint64_t value, bool prefix, uint8_t nbytes) - { - union { - uint64_t val; - uint8_t bytes[8]; - } __tmp_editor; - __tmp_editor.val = value; - if (nbytes < 1 || nbytes > 8) nbytes = 1; - std::ostringstream oss; - if (prefix) oss << "0b "; - for (int8_t b = nbytes - 1; b >= 0; b--) - oss << std::bitset<8>((char)__tmp_editor.bytes[b]) << " "; - return oss.str(); - } - String Utils::duplicateChar(unsigned char c, uint16_t count) - { - String str = ""; - for (uint16_t i = 0; i < count; i++) - str = str += c; - return str; - } - float Utils::map_value(float input, float input_start, float input_end, float output_start, float output_end) - { - float slope = 1.0 * (output_end - output_start) / (input_end - input_start); - return output_start + round(slope * (input - input_start)); - } - bool Utils::loadFileFromHppResource(String output_file_path, const char* resource_buffer, unsigned int size) - { - unsigned char ext_len = resource_buffer[0]; - String ext = ""; - for (unsigned char i = 0; i < ext_len; i++) - ext += (char)(resource_buffer[i + 1]); - if (String(output_file_path).trim().toLower().endsWith(ext)) - ext = ""; - std::fstream bin (output_file_path.cpp_str() + ext.cpp_str(), std::ios::out | std::ios::binary); - if (!bin.is_open()) return false; - bin.write(resource_buffer + ext_len + 1, size - ext_len - 1); - bin.close(); - return true; - } - void Utils::printByteStream(const ByteStream& data, StreamIndex start, uint8_t line_len, uint16_t n_rows, OutputHandlerBase& out, int32_t addrHighlight, uint32_t highlightRange, const String& title) - { - StreamIndex end = start + (n_rows * line_len); - if (end > data.size()) end = data.size(); - String titleEdit(title); - if (titleEdit.len() > 12) - titleEdit = titleEdit.substr(0, 12); - else if (titleEdit.len() < 12) - { - int32_t diff = 12 - titleEdit.len(); - for (int32_t i = 0; i < diff; i++) - titleEdit.addChar(' '); - } - bool highlight = addrHighlight >= 0; - uint8_t i = 1; - ByteStream tmp; - uint16_t linew = 1 + 1 + 6 + 1 + 1 + 2 + ((2 + 2) * line_len) + 1 + 4; - out.fg(ConsoleColors::BrightBlue).p(Utils::duplicateChar('=', linew)).nl(); - if (line_len <= 0xFF) - { - out.fg(ConsoleColors::BrightBlue).p("|"); - out.fg(ConsoleColors::BrightMagenta).p(titleEdit); - out.fg(ConsoleColors::BrightBlue).p("| "); - for (int32_t i = 0; i < line_len; i++) - out.fg(ConsoleColors::Green).p(getHexStr(i, false, 1)).p(" "); - out.fg(ConsoleColors::BrightBlue).p("|").nl(); - out.fg(ConsoleColors::BrightBlue).p(Utils::duplicateChar('=', linew)).nl(); - } - out.fg(ConsoleColors::BrightBlue).p("| "); - out.fg(ConsoleColors::BrightGray).p("0x"); - out.fg(ConsoleColors::BrightCyan).p(Utils::getHexStr(start, false, 4)).fg(ConsoleColors::BrightBlue).p(" | "); - for (StreamIndex addr = start; addr < end; addr++) - { - tmp.push_back(data[addr]); - if (highlight && (addr >= (uint32_t)addrHighlight && addr < (uint32_t)(addrHighlight + highlightRange))) - out.fg(ConsoleColors::Red); - else if (data[addr] == 0) - out.fg(ConsoleColors::BrightGray); - else - out.fg(ConsoleColors::White); - out.p(Utils::getHexStr(data[addr], false)).p(" "); - if (i++ % line_len == 0 || addr == end - 1) - { - i = 1; - out.fg(ConsoleColors::BrightBlue).p("|"); - out.nl(); - out.fg(ConsoleColors::BrightBlue).p("|"); - out.fg(ConsoleColors::BrightGray).p(" -------- ").fg(ConsoleColors::BrightBlue).p("|").fg(ConsoleColors::BrightGray).p(" "); - for (const auto& c : tmp) - { - if (isprint(c)) out.fg(ConsoleColors::BrightYellow).pChar((char)c).fg(ConsoleColors::BrightGray).p(" "); - else out.fg(ConsoleColors::BrightGray).p(". "); - } - out.fg(ConsoleColors::BrightBlue).p("| "); - tmp.clear(); - out.reset(); - if (addr == end - 1) break; - out.nl(); - out.fg(ConsoleColors::BrightBlue).p("| "); - out.fg(ConsoleColors::BrightGray).p("0x"); - out.fg(ConsoleColors::BrightCyan).p(Utils::getHexStr(addr + 1, false, 4)).fg(ConsoleColors::BrightBlue).p(" | "); - } - } - out.nl().fg(ConsoleColors::BrightBlue).p(Utils::duplicateChar('=', linew)).nl().reset(); - } - bool Utils::saveByteStreamToFile(const ByteStream& stream, const String& filePath) - { - std::ofstream writeFile; - writeFile.open(filePath.cpp_str(), std::ios::out | std::ios::binary); - writeFile.write((char*)(&stream[0]), stream.size()); - writeFile.close(); - return true; - } - bool Utils::loadByteStreamFromFile(const String& filePath, ByteStream& outStream) - { - std::ifstream rf(filePath.cpp_str(), std::ios::out | std::ios::binary); - if(!rf) return false; //TODO: Error - uint8_t cell = 0; - while(rf.read((char*)&cell, sizeof(cell))) - outStream.push_back(cell); - if (outStream.size() == 0) return false; //TODO: Error - return true; - } - ByteStream Utils::stringToByteStream(const String& data) - { - ByteStream bstream; - for (auto& c : data) - bstream.push_back((int8_t)c); - return bstream; - } - String Utils::byteStreamToString(const ByteStream& data) - { - String out_string = ""; - for (int64_t i = 0; i < data.size(); i++) - { - if (data[i] == 0) break; - out_string.addChar((char)data[i]); - } - return out_string; - } -} diff --git a/src/ostd/utils/Utils.hpp b/src/ostd/utils/Utils.hpp deleted file mode 100755 index e43959d..0000000 --- a/src/ostd/utils/Utils.hpp +++ /dev/null @@ -1,99 +0,0 @@ -/* - OmniaFramework - A collection of useful functionality - Copyright (C) 2025 OmniaX-Dev - - This file is part of OmniaFramework. - - OmniaFramework is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - OmniaFramework is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with OmniaFramework. If not, see . -*/ - -#pragma once - -#include -#include -#include -#include - -#define STR_BOOL(b) (b ? "true" : "false") -#define STDVEC_CONTAINS(vec, elem) (std::find(vec.begin(), vec.end(), elem) != vec.end()) - -namespace ostd -{ - class Utils - { - public: - //Implemented in - static inline const uint64_t getStartTime(void) { return Utils::s_startTime_ms; } - static void init(void); - static bool isHex(String hex); - static bool isBin(String bin); - static bool isInt(String str); - static int64_t strToInt(String str); - static bool readFile(String fileName, std::vector& outLines); - static String getHexStr(uint64_t value, bool prefix = true, uint8_t nbytes = 1); - static String getBinStr(uint64_t value, bool prefix = true, uint8_t nbytes = 1); - static String duplicateChar(unsigned char c, uint16_t count); - static float map_value(float input, float input_start, float input_end, float output_start, float output_end); - static bool loadFileFromHppResource(String output_file_path, const char* resource_buffer, unsigned int size); - static void printByteStream(const ByteStream& data, StreamIndex start, uint8_t line_len, uint16_t n_rows, OutputHandlerBase& out, int32_t addrHighlight = -1, uint32_t highlightRange = 1, const String& title = ""); - static bool saveByteStreamToFile(const ByteStream& stream, const String& filePath); - static bool loadByteStreamFromFile(const String& filePath, ByteStream& outStream); - static ByteStream stringToByteStream(const String& data); - static String byteStreamToString(const ByteStream& data); - - //Implemented in - static void sleep(uint32_t __time, eTimeUnits __unit = eTimeUnits::Milliseconds); - static uint64_t getRunningTime_ms(void); - static String secondsToFormattedString(int32_t totalSeconds); - - //Implemented in - static String md5(const String& str); - - //Implemented in - static int32_t solveIntegerExpression(const String& expr); - - //Implemented in - static void clearConsole(void); - static void getConsoleSize(int32_t& outColumns, int32_t& outRows); - static void setConsoleCursorPosition(int32_t x, int32_t y); - static int32_t getConsoleWidth(void); - static int32_t getConsoleHeight(void); - - //Array helpers - template - static inline T* createArray(size_t size) - { - T* array = (T*)malloc(size * sizeof(T)); - return array; - } - template - static inline T* resizeArray(T* array, size_t new_size) - { - T* new_array = (T*)realloc(array, new_size * sizeof(T)); - return new_array; - } - static inline void destroyArray(void* array) - { - free(array); - } - - private: - static void transform(const uint8_t block[64], uint32_t state[4]); - static void encode(uint8_t* output, const uint32_t* input, size_t len); - static void decode(uint32_t* output, const uint8_t* input, size_t len); - - private: - inline static uint64_t s_startTime_ms; - }; -} diff --git a/src/test.cpp b/src/test.cpp index bb33ee9..6d0c520 100644 --- a/src/test.cpp +++ b/src/test.cpp @@ -24,7 +24,7 @@ // #include #include "Image.hpp" -#include "utils/Utils.hpp" +#include "utils/Hash.hpp" #include #include #include @@ -113,9 +113,9 @@ class Window : public ogfx::WindowBase int main(int argc, char** argv) { - out.p(STR_BOOL(ostd::Utils::md5("") == "d41d8cd98f00b204e9800998ecf8427e")).nl(); - out.p(STR_BOOL(ostd::Utils::md5("abc") == "900150983cd24fb0d6963f7d28e17f72")).nl(); - out.p(STR_BOOL(ostd::Utils::md5("message digest") == "f96b697d7cb7938d525a2f31aaf161d0")).nl(); + out.p(STR_BOOL(ostd::Hash::md5("") == "d41d8cd98f00b204e9800998ecf8427e")).nl(); + out.p(STR_BOOL(ostd::Hash::md5("abc") == "900150983cd24fb0d6963f7d28e17f72")).nl(); + out.p(STR_BOOL(ostd::Hash::md5("message digest") == "f96b697d7cb7938d525a2f31aaf161d0")).nl(); Window window; window.initialize(1280, 720, "OmniaFramework - Test Window");