From 11d75e401e7e756342ff56ef24590975fba98533 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ya=C4=9F=C4=B1z=20Zengin?= Date: Mon, 24 Nov 2025 18:50:57 +0300 Subject: [PATCH] pmt: reformat code, etc. --- .clang-format | 94 +++-- include/PartitionManager/PartitionManager.hpp | 53 +-- manager.sh | 23 +- src/FunctionManager.cpp | 31 +- src/Main.cpp | 2 +- src/PartitionManager.cpp | 74 ++-- src/functions/BackupFunction.cpp | 21 +- src/functions/CleanLogFunction.cpp | 7 +- src/functions/EraseFunction.cpp | 24 +- src/functions/FlashFunction.cpp | 19 +- src/functions/InfoFunction.cpp | 24 +- src/functions/MemoryTestFunction.cpp | 18 +- src/functions/PartitionSizeFunction.cpp | 22 +- src/functions/RealPathFunction.cpp | 10 +- src/functions/RebootFunction.cpp | 11 +- src/functions/TypeFunction.cpp | 12 +- src/functions/functions.hpp | 70 ++-- srclib/libhelper/include/libhelper/lib.hpp | 347 +++++++++--------- srclib/libhelper/src/Checkers.cpp | 9 +- srclib/libhelper/src/Classes.cpp | 54 +-- srclib/libhelper/src/FileUtil.cpp | 24 +- srclib/libhelper/src/Sha256.cpp | 7 +- srclib/libhelper/src/Utilities.cpp | 87 ++--- srclib/libhelper/tests/test.cpp | 19 +- .../include/libpartition_map/lib.hpp | 133 ++++--- srclib/libpartition_map/src/Getters.cpp | 17 +- srclib/libpartition_map/src/Magic.cpp | 9 +- srclib/libpartition_map/src/PartitionMap.cpp | 98 ++--- srclib/libpartition_map/src/Type.cpp | 68 ++-- srclib/libpartition_map/tests/test.cpp | 15 +- 30 files changed, 755 insertions(+), 647 deletions(-) diff --git a/.clang-format b/.clang-format index ba7174e..2d373d0 100644 --- a/.clang-format +++ b/.clang-format @@ -1,6 +1,6 @@ --- Language: Cpp -AccessModifierOffset: -2 +AccessModifierOffset: -1 AlignAfterOpenBracket: Align AlignArrayOfStructures: None AlignConsecutiveAssignments: @@ -65,7 +65,7 @@ AlignConsecutiveTableGenDefinitionColons: AlignFunctionDeclarations: false AlignFunctionPointers: false PadOperators: false -AlignEscapedNewlines: Right +AlignEscapedNewlines: Left AlignOperands: Align AlignTrailingComments: Kind: Always @@ -79,17 +79,22 @@ AllowShortCaseLabelsOnASingleLine: false AllowShortCompoundRequirementOnASingleLine: true AllowShortEnumsOnASingleLine: true AllowShortFunctionsOnASingleLine: All -AllowShortIfStatementsOnASingleLine: AllIfsAndElse +AllowShortIfStatementsOnASingleLine: WithoutElse AllowShortLambdasOnASingleLine: All -AllowShortLoopsOnASingleLine: false +AllowShortLoopsOnASingleLine: true AllowShortNamespacesOnASingleLine: false AlwaysBreakAfterDefinitionReturnType: None -AlwaysBreakBeforeMultilineStrings: false +AlwaysBreakBeforeMultilineStrings: true AttributeMacros: - __capability + - absl_nonnull + - absl_nullable + - absl_nullability_unknown BinPackArguments: true +BinPackLongBracedList: true BinPackParameters: BinPack BitFieldColonSpacing: Both +BracedInitializerIndentWidth: -1 BraceWrapping: AfterCaseLabel: false AfterClass: false @@ -118,13 +123,14 @@ BreakBeforeBinaryOperators: None BreakBeforeConceptDeclarations: Always BreakBeforeBraces: Attach BreakBeforeInlineASMColon: OnlyMultiline +BreakBeforeTemplateCloser: false BreakBeforeTernaryOperators: true BreakBinaryOperations: Never BreakConstructorInitializers: BeforeColon BreakFunctionDefinitionParameters: false BreakInheritanceList: BeforeColon BreakStringLiterals: true -BreakTemplateDeclarations: MultiLine +BreakTemplateDeclarations: Yes ColumnLimit: 80 CommentPragmas: '^ IWYU pragma:' CompactNamespaces: false @@ -135,6 +141,7 @@ DerivePointerAlignment: false DisableFormat: false EmptyLineAfterAccessModifier: Never EmptyLineBeforeAccessModifier: LogicalBlock +EnumTrailingComma: Leave ExperimentalAutoDetectBinPacking: false FixNamespaceComments: true ForEachMacros: @@ -143,25 +150,29 @@ ForEachMacros: - BOOST_FOREACH IfMacros: - KJ_IF_MAYBE -IncludeBlocks: Preserve +IncludeBlocks: Regroup IncludeCategories: - - Regex: '^"(llvm|llvm-c|clang|clang-c)/' + - Regex: '^' Priority: 2 SortPriority: 0 CaseSensitive: false - - Regex: '^(<|"(gtest|gmock|isl|json)/)' - Priority: 3 - SortPriority: 0 - CaseSensitive: false - - Regex: '.*' + - Regex: '^<.*\.h>' Priority: 1 SortPriority: 0 CaseSensitive: false -IncludeIsMainRegex: '(Test)?$' + - Regex: '^<.*' + Priority: 2 + SortPriority: 0 + CaseSensitive: false + - Regex: '.*' + Priority: 3 + SortPriority: 0 + CaseSensitive: false +IncludeIsMainRegex: '([-_](test|unittest))?$' IncludeIsMainSourceRegex: '' IndentAccessModifiers: false IndentCaseBlocks: false -IndentCaseLabels: false +IndentCaseLabels: true IndentExportBlock: true IndentExternBlock: AfterExternBlock IndentGotoLabels: true @@ -183,7 +194,7 @@ JavaScriptQuotes: Leave JavaScriptWrapImports: true KeepEmptyLines: AtEndOfFile: false - AtStartOfBlock: true + AtStartOfBlock: false AtStartOfFile: true KeepFormFeed: false LambdaBodyIndentation: Signature @@ -193,14 +204,15 @@ MacroBlockEnd: '' MainIncludeChar: Quote MaxEmptyLinesToKeep: 1 NamespaceIndentation: None -ObjCBinPackProtocolList: Auto +ObjCBinPackProtocolList: Never ObjCBlockIndentWidth: 2 ObjCBreakBeforeNestedBlockParam: true ObjCSpaceAfterProperty: false ObjCSpaceBeforeProtocolList: true -PackConstructorInitializers: BinPack +OneLineFormatOffRegex: '' +PackConstructorInitializers: NextLine PenaltyBreakAssignment: 2 -PenaltyBreakBeforeFirstCallParameter: 19 +PenaltyBreakBeforeFirstCallParameter: 1 PenaltyBreakBeforeMemberAccess: 150 PenaltyBreakComment: 300 PenaltyBreakFirstLessLess: 120 @@ -210,10 +222,40 @@ PenaltyBreakString: 1000 PenaltyBreakTemplateDeclaration: 10 PenaltyExcessCharacter: 1000000 PenaltyIndentedWhitespace: 0 -PenaltyReturnTypeOnItsOwnLine: 60 -PointerAlignment: Right +PenaltyReturnTypeOnItsOwnLine: 200 +PointerAlignment: Left PPIndentWidth: -1 QualifierAlignment: Leave +RawStringFormats: + - Language: Cpp + Delimiters: + - cc + - CC + - cpp + - Cpp + - CPP + - 'c++' + - 'C++' + CanonicalDelimiter: '' + BasedOnStyle: google + - Language: TextProto + Delimiters: + - pb + - PB + - proto + - PROTO + EnclosingFunctions: + - EqualsProto + - EquivToProto + - PARSE_PARTIAL_TEXT_PROTO + - PARSE_TEST_PROTO + - PARSE_TEXT_PROTO + - ParseTextOrDie + - ParseTextProtoOrDie + - ParseTestProto + - ParsePartialTestProto + CanonicalDelimiter: pb + BasedOnStyle: google ReferenceAlignment: Pointer ReflowComments: Always RemoveBracesLLVM: false @@ -225,11 +267,14 @@ RequiresExpressionIndentation: OuterScope SeparateDefinitionBlocks: Leave ShortNamespaceLines: 1 SkipMacroDefinitionBody: false -SortIncludes: CaseSensitive +SortIncludes: + Enabled: true + IgnoreCase: false SortJavaStaticImport: Before SortUsingDeclarations: LexicographicNumeric SpaceAfterCStyleCast: false SpaceAfterLogicalNot: false +SpaceAfterOperatorKeyword: false SpaceAfterTemplateKeyword: true SpaceAroundPointerQualifiers: Default SpaceBeforeAssignmentOperators: true @@ -245,6 +290,7 @@ SpaceBeforeParensOptions: AfterFunctionDefinitionName: false AfterFunctionDeclarationName: false AfterIfMacros: true + AfterNot: false AfterOverloadedOperator: false AfterPlacementOperator: true AfterRequiresInClause: false @@ -253,7 +299,7 @@ SpaceBeforeParensOptions: SpaceBeforeRangeBasedForLoopColon: true SpaceBeforeSquareBrackets: false SpaceInEmptyBlock: false -SpacesBeforeTrailingComments: 1 +SpacesBeforeTrailingComments: 2 SpacesInAngles: Never SpacesInContainerLiterals: true SpacesInLineCommentPrefix: @@ -267,7 +313,7 @@ SpacesInParensOptions: InEmptyParentheses: false Other: false SpacesInSquareBrackets: false -Standard: Latest +Standard: Auto StatementAttributeLikeMacros: - Q_EMIT StatementMacros: diff --git a/include/PartitionManager/PartitionManager.hpp b/include/PartitionManager/PartitionManager.hpp index 96571b1..c9af76d 100644 --- a/include/PartitionManager/PartitionManager.hpp +++ b/include/PartitionManager/PartitionManager.hpp @@ -34,31 +34,31 @@ #define PART_MAP (*VARS.PartMap) namespace PartitionManager { -int Main(int argc, char **argv); +int Main(int argc, char** argv); // Print messages if not using quiet mode -__attribute__((format(printf, 1, 2))) void print(const char *format, ...); -__attribute__((format(printf, 1, 2))) void println(const char *format, ...); +__attribute__((format(printf, 1, 2))) void print(const char* format, ...); +__attribute__((format(printf, 1, 2))) void println(const char* format, ...); // If there is a delimiter in the string, CLI::detail::split returns; if not, an // empty vector is returned. And checks duplicate arguments. -std::vector splitIfHasDelim(const std::string &s, char delim, +std::vector splitIfHasDelim(const std::string& s, char delim, bool checkForBadUsage = false); // Process vectors with input strings. Use for [flag(s)]-[other flag(s)] // situations -void processCommandLine(std::vector &vec1, - std::vector &vec2, const std::string &s1, - const std::string &s2, char delim, +void processCommandLine(std::vector& vec1, + std::vector& vec2, const std::string& s1, + const std::string& s2, char delim, bool checkForBadUsage = false); // Setting ups buffer size -void setupBufferSize(uint64_t &size, const std::string &entry); +void setupBufferSize(uint64_t& size, const std::string& entry); std::string getLibVersion(); -std::string getAppVersion(); // Not Android app version (an Android app is - // planned!), tells pmt version. +std::string getAppVersion(); // Not Android app version (an Android app is + // planned!), tells pmt version. enum basic_function_flags { NO_SU = 1, @@ -68,28 +68,29 @@ enum basic_function_flags { // All function classes must inherit from this class. class basic_function { -public: - CLI::App *cmd = nullptr; + public: + CLI::App* cmd = nullptr; std::vector flags = {}; - virtual bool init(CLI::App &_app) = 0; + virtual bool init(CLI::App& _app) = 0; virtual bool run() = 0; [[nodiscard]] virtual bool isUsed() const = 0; - [[nodiscard]] virtual const char *name() const = 0; + [[nodiscard]] virtual const char* name() const = 0; virtual ~basic_function() = default; }; // A class for function management. -template class basic_manager { -private: +template +class basic_manager { + private: std::vector> _functions; -public: - void registerFunction(std::unique_ptr<_Type> _func, CLI::App &_app) { + public: + void registerFunction(std::unique_ptr<_Type> _func, CLI::App& _app) { LOGN(PMTF, INFO) << "registering: " << _func->name() << std::endl; - for (const auto &f : _functions) { + for (const auto& f : _functions) { if (std::string(_func->name()) == std::string(f->name())) { LOGN(PMTF, INFO) << "Is already registered: " << _func->name() << ". Skipping." << std::endl; @@ -104,7 +105,7 @@ public: } [[nodiscard]] bool hasFlagOnUsedFunction(int flag) const { - for (const auto &func : _functions) { + for (const auto& func : _functions) { if (func->isUsed()) { std::for_each(func->flags.begin(), func->flags.end(), [&](const int x) { LOGN(PMTF, INFO) << "Used flag " << x << " on " << func->name() @@ -117,9 +118,9 @@ public: return false; } - [[nodiscard]] bool isUsed(const std::string &name) const { + [[nodiscard]] bool isUsed(const std::string& name) const { if (_functions.empty()) return false; - for (const auto &func : _functions) { + for (const auto& func : _functions) { if (func->name() == name) return func->isUsed(); } return false; @@ -127,7 +128,7 @@ public: [[nodiscard]] bool handleAll() const { LOGN(PMTF, INFO) << "running caught commands in command-line." << std::endl; - for (const auto &func : _functions) { + for (const auto& func : _functions) { if (func->isUsed()) { LOGN(PMTF, INFO) << func->name() << " is calling because used in command-line." @@ -144,7 +145,7 @@ public: }; class basic_variables final { -public: + public: basic_variables(); std::unique_ptr PartMap; @@ -165,6 +166,6 @@ using Error = Helper::Error; extern std::unique_ptr Variables; extern FILE *pstdout, *pstderr; -} // namespace PartitionManager +} // namespace PartitionManager -#endif // #ifndef LIBPMT_LIB_HPP +#endif // #ifndef LIBPMT_LIB_HPP diff --git a/manager.sh b/manager.sh index ae69447..7a46e7a 100644 --- a/manager.sh +++ b/manager.sh @@ -19,8 +19,7 @@ RELEASE="20250821" echo() { command echo "[$THIS]: $@"; } -checks() -{ +checks() { if ! curl "https://github.com" &>/dev/null; then echo "No internet connection!" exit 1 @@ -32,8 +31,7 @@ checks() [ ! -f $PREFIX/bin/wget ] && pkg install -y wget } -select_variant() -{ +select_variant() { LINK=""; ARCH=""; VARIANT="" if getprop ro.product.cpu.abi | grep "arm64-v8a" &>/dev/null; then ARCH="arm64-v8a" @@ -44,8 +42,7 @@ select_variant() LINK="https://github.com/ShawkTeam/pmt-renovated/releases/download/${RELEASE}/pmt-${VARIANT}${ARCH}.zip" } -download() -{ +download() { echo "Downloading pmt-${VARIANT}${ARCH}.zip (${RELEASE})" if ! wget -O $PREFIX/tmp/pmt.zip "${LINK}" &>/dev/null; then echo "Download failed! LINK=${LINK}" @@ -60,8 +57,7 @@ download() fi } -setup() -{ +setup() { [ -f $PREFIX/tmp/pmt_static ] && mv $PREFIX/tmp/pmt_static $PREFIX/tmp/pmt set -e install -t $PREFIX/bin $PREFIX/tmp/pmt @@ -72,21 +68,18 @@ setup() echo "Installed successfully. Try running 'pmt' command." } -uninstall() -{ +uninstall() { rm -f $PREFIX/bin/pmt $PREFIX/lib/libhelper* $PREFIX/lib/libpartition_map* &>/dev/null } -is_installed() -{ +is_installed() { if /system/bin/which pmt &>/dev/null; then echo "PMT is already installed." exit 1 fi } -cleanup() -{ +cleanup() { rm -f $PREFIX/tmp/pmt* $PREFIX/tmp/lib* $PREFIX/tmp/*.zip &>/dev/null } @@ -95,7 +88,7 @@ if [ $# -eq 0 ]; then exit 1 fi -if ! basename -a ${PREFIX}/bin/* | grep "termux" &>/dev/null; then +if ! echo ${HOME} | grep "com.termux" &>/dev/null; then echo "This script only for termux!" exit 1 fi diff --git a/src/FunctionManager.cpp b/src/FunctionManager.cpp index 64d70d7..7716c16 100644 --- a/src/FunctionManager.cpp +++ b/src/FunctionManager.cpp @@ -14,23 +14,24 @@ limitations under the License. */ +#include + #include #include -#include #include #include #include #include namespace PartitionManager { -std::vector splitIfHasDelim(const std::string &s, const char delim, +std::vector splitIfHasDelim(const std::string& s, const char delim, const bool checkForBadUsage) { if (s.find(delim) == std::string::npos) return {}; auto vec = CLI::detail::split(s, delim); if (checkForBadUsage) { std::unordered_set set; - for (const auto &str : vec) { + for (const auto& str : vec) { if (set.find(str) != set.end()) throw CLI::ValidationError("Duplicate element in your inputs!"); set.insert(str); @@ -40,25 +41,27 @@ std::vector splitIfHasDelim(const std::string &s, const char delim, return vec; } -void setupBufferSize(uint64_t &size, const std::string &entry) { +void setupBufferSize(uint64_t& size, const std::string& entry) { if (PART_MAP.hasPartition(entry) && PART_MAP.sizeOf(entry) % size != 0) { - println("%sWARNING%s: Specified buffer size is invalid for %s! Using " - "different buffer size for %s.", - YELLOW, STYLE_RESET, entry.data(), entry.data()); + println( + "%sWARNING%s: Specified buffer size is invalid for %s! Using " + "different buffer size for %s.", + YELLOW, STYLE_RESET, entry.data(), entry.data()); size = PART_MAP.sizeOf(entry) % 4096 == 0 ? 4096 : 1; } else if (Helper::fileIsExists(entry)) { if (Helper::fileSize(entry) % size != 0) { - println("%sWARNING%s: Specified buffer size is invalid for %s! using " - "different buffer size for %s.", - YELLOW, STYLE_RESET, entry.data(), entry.data()); + println( + "%sWARNING%s: Specified buffer size is invalid for %s! using " + "different buffer size for %s.", + YELLOW, STYLE_RESET, entry.data(), entry.data()); size = Helper::fileSize(entry) % 4096 == 0 ? 4096 : 1; } } } -void processCommandLine(std::vector &vec1, - std::vector &vec2, const std::string &s1, - const std::string &s2, const char delim, +void processCommandLine(std::vector& vec1, + std::vector& vec2, const std::string& s1, + const std::string& s2, const char delim, const bool checkForBadUsage) { vec1 = splitIfHasDelim(s1, delim, checkForBadUsage); vec2 = splitIfHasDelim(s2, delim, checkForBadUsage); @@ -66,4 +69,4 @@ void processCommandLine(std::vector &vec1, if (vec1.empty() && !s1.empty()) vec1.push_back(s1); if (vec2.empty() && !s2.empty()) vec2.push_back(s2); } -} // namespace PartitionManager +} // namespace PartitionManager diff --git a/src/Main.cpp b/src/Main.cpp index 03e297e..8c2147a 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -16,7 +16,7 @@ #include -int main(int argc, char **argv) { +int main(int argc, char** argv) { // Call integrated main function in library return PartitionManager::Main(argc, argv); } diff --git a/src/PartitionManager.cpp b/src/PartitionManager.cpp index 2ff569e..9e6eefa 100644 --- a/src/PartitionManager.cpp +++ b/src/PartitionManager.cpp @@ -14,18 +14,20 @@ limitations under the License. */ -#include "functions/functions.hpp" #include #include #include #include #include + +#include "functions/functions.hpp" #ifndef ANDROID_BUILD #include #endif -#include #include +#include + namespace PartitionManager { /** @@ -33,16 +35,19 @@ namespace PartitionManager { * * Usage: REGISTER_FUNCTION(FUNCTION_CLASS); */ -#define REGISTER_FUNCTION(cls) \ +#define REGISTER_FUNCTION(cls) \ FuncManager.registerFunction(std::make_unique(), AppMain) basic_variables::basic_variables() - : logFile(Helper::LoggingProperties::FILE), onLogical(false), - quietProcess(false), verboseMode(false), viewVersion(false), + : logFile(Helper::LoggingProperties::FILE), + onLogical(false), + quietProcess(false), + verboseMode(false), + viewVersion(false), forceProcess(false) { try { PartMap = std::make_unique(); - } catch (std::exception &) { + } catch (std::exception&) { } } @@ -57,26 +62,27 @@ static void sigHandler(const int sig) { exit(sig); } -static int write(void *cookie, const char *buf, const int size) { - auto *real = static_cast(cookie); +static int write(void* cookie, const char* buf, const int size) { + auto* real = static_cast(cookie); if (!VARS.quietProcess) { const int ret = fwrite(buf, 1, static_cast(size), real); fflush(real); return ret; - } else return size; + } else + return size; } -static FILE *make_fp(FILE *real) { +static FILE* make_fp(FILE* real) { return funopen(real, nullptr, write, nullptr, nullptr); } auto Variables = std::make_unique(); -FILE *pstdout = make_fp(stdout); -FILE *pstderr = make_fp(stderr); +FILE* pstdout = make_fp(stdout); +FILE* pstderr = make_fp(stderr); static Helper::garbageCollector collector; -int Main(int argc, char **argv) { +int Main(int argc, char** argv) { try { // try-catch start Helper::LoggingProperties::setProgramName(argv[0]); @@ -90,7 +96,7 @@ int Main(int argc, char **argv) { char buf[128]; while (fgets(buf, sizeof(buf), stdin) != nullptr) { buf[strcspn(buf, "\n")] = 0; - const char *token = strtok(buf, " \t"); + const char* token = strtok(buf, " \t"); while (token != nullptr) { argv[argc] = strdup(token); argc++; @@ -111,14 +117,15 @@ int Main(int argc, char **argv) { AppMain.fallthrough(true); AppMain.set_help_all_flag("--help-all", "Print full help message and exit"); - AppMain.footer("Partition Manager Tool is written by YZBruh\n" - "This project licensed under " - "Apache 2.0 license\nReport " - "bugs to https://github.com/ShawkTeam/pmt-renovated/issues"); + AppMain.footer( + "Partition Manager Tool is written by YZBruh\n" + "This project licensed under " + "Apache 2.0 license\nReport " + "bugs to https://github.com/ShawkTeam/pmt-renovated/issues"); AppMain .add_option("-S,--search-path", VARS.searchPath, "Set partition search path") - ->check([&](const std::string &val) { + ->check([&](const std::string& val) { if (val.find("/block") == std::string::npos) return std::string( "Partition search path is unexpected! Couldn't find " @@ -159,17 +166,20 @@ int Main(int argc, char **argv) { if (FuncManager.hasFlagOnUsedFunction(NO_MAP_CHECK)) { if (!VARS.searchPath.empty()) - WARNING("-S (--search-path) flag is ignored. Because, don't needed " - "partition map by your used function.\n"); + WARNING( + "-S (--search-path) flag is ignored. Because, don't needed " + "partition map by your used function.\n"); if (VARS.onLogical) - WARNING("-l (--logical) flag ignored. Because, partition type don't " - "needed by your used function.\n"); + WARNING( + "-l (--logical) flag ignored. Because, partition type don't " + "needed by your used function.\n"); } else { if (!VARS.searchPath.empty()) (PART_MAP)(VARS.searchPath); if (!VARS.PartMap && VARS.searchPath.empty()) - throw Error("No default search entries were found. Specify a search " - "directory with -S " - "(--search-path)"); + throw Error( + "No default search entries were found. Specify a search " + "directory with -S " + "(--search-path)"); if (VARS.onLogical) { if (!PART_MAP.hasLogicalPartitions()) @@ -187,29 +197,29 @@ int Main(int argc, char **argv) { } return FuncManager.handleAll() == true ? EXIT_SUCCESS : EXIT_FAILURE; - } catch (Helper::Error &error) { + } catch (Helper::Error& error) { // catch Helper::Error fprintf(pstderr, "%s%sERROR(S) OCCURRED:%s\n%s\n", RED, BOLD, STYLE_RESET, error.what()); return EXIT_FAILURE; - } catch (CLI::Error &error) { + } catch (CLI::Error& error) { // catch CLI::Error fprintf(stderr, "%s: %s%sFLAG PARSE ERROR:%s %s\n", argv[0], RED, BOLD, STYLE_RESET, error.what()); return EXIT_FAILURE; - } // try-catch block end + } // try-catch block end } -void print(const char *format, ...) { +void print(const char* format, ...) { va_list args; va_start(args, format); vfprintf(pstdout, format, args); va_end(args); } -void println(const char *format, ...) { +void println(const char* format, ...) { va_list args; va_start(args, format); vfprintf(pstdout, format, args); @@ -220,4 +230,4 @@ void println(const char *format, ...) { std::string getLibVersion() { MKVERSION(PMT); } std::string getAppVersion() { MKVERSION(PMTE); } -} // namespace PartitionManager +} // namespace PartitionManager diff --git a/src/functions/BackupFunction.cpp b/src/functions/BackupFunction.cpp index 5b53d05..26089c9 100644 --- a/src/functions/BackupFunction.cpp +++ b/src/functions/BackupFunction.cpp @@ -14,21 +14,23 @@ limitations under the License. */ -#include "functions.hpp" +#include +#include +#include + #include #include #include #include -#include #include -#include -#include + +#include "functions.hpp" #define BFUN "backupFunction" #define FUNCTION_CLASS backupFunction namespace PartitionManager { -RUN_ASYNC(const std::string &partitionName, const std::string &outputName, +RUN_ASYNC(const std::string& partitionName, const std::string& outputName, const uint64_t bufferSize) { if (!PART_MAP.hasPartition(partitionName)) return {Helper::format("Couldn't find partition: %s", partitionName.data()), @@ -77,7 +79,7 @@ RUN_ASYNC(const std::string &partitionName, const std::string &outputName, LOGN(BFUN, INFO) << "Writing partition " << partitionName << " to file: " << outputName << std::endl; - auto *buffer = new (std::nothrow) char[bufferSize]; + auto* buffer = new (std::nothrow) char[bufferSize]; collector.delAfterProgress(buffer); memset(buffer, 0x00, bufferSize); @@ -148,12 +150,13 @@ RUN { std::string end; bool endResult = true; - for (auto &future : futures) { + for (auto& future : futures) { auto [fst, snd] = future.get(); if (!snd) { end += fst + '\n'; endResult = false; - } else println("%s", fst.c_str()); + } else + println("%s", fst.c_str()); } if (!endResult) throw Error("%s", end.c_str()); @@ -165,4 +168,4 @@ RUN { IS_USED_COMMON_BODY NAME { return BFUN; } -} // namespace PartitionManager +} // namespace PartitionManager diff --git a/src/functions/CleanLogFunction.cpp b/src/functions/CleanLogFunction.cpp index 7ccd957..66cd4da 100644 --- a/src/functions/CleanLogFunction.cpp +++ b/src/functions/CleanLogFunction.cpp @@ -14,9 +14,10 @@ Copyright 2025 Yağız Zengin limitations under the License. */ -#include "functions.hpp" #include +#include "functions.hpp" + #define CFUN "cleanLogFunction" #define FUNCTION_CLASS cleanLogFunction @@ -31,7 +32,7 @@ INIT { RUN { LOGN(CFUN, INFO) << "Removing log file: " << VARS.logFile << std::endl; - Helper::LoggingProperties::setLoggingState(); // eraseEntry writes log! + Helper::LoggingProperties::setLoggingState(); // eraseEntry writes log! return Helper::eraseEntry(VARS.logFile); } @@ -39,4 +40,4 @@ IS_USED_COMMON_BODY NAME { return CFUN; } -} // namespace PartitionManager +} // namespace PartitionManager diff --git a/src/functions/EraseFunction.cpp b/src/functions/EraseFunction.cpp index 6dd56ea..a69aa24 100644 --- a/src/functions/EraseFunction.cpp +++ b/src/functions/EraseFunction.cpp @@ -14,18 +14,20 @@ Copyright 2025 Yağız Zengin limitations under the License. */ -#include "functions.hpp" +#include +#include + #include #include -#include #include -#include + +#include "functions.hpp" #define EFUN "eraseFunction" #define FUNCTION_CLASS eraseFunction namespace PartitionManager { -RUN_ASYNC(const std::string &partitionName, const uint64_t bufferSize) { +RUN_ASYNC(const std::string& partitionName, const uint64_t bufferSize) { if (!PART_MAP.hasPartition(partitionName)) return {Helper::format("Couldn't find partition: %s", partitionName.data()), false}; @@ -65,7 +67,7 @@ RUN_ASYNC(const std::string &partitionName, const uint64_t bufferSize) { LOGN(EFUN, INFO) << "Writing zero bytes to partition: " << partitionName << std::endl; - auto *buffer = new (std::nothrow) char[bufferSize]; + auto* buffer = new (std::nothrow) char[bufferSize]; collector.delAfterProgress(buffer); memset(buffer, 0x00, bufferSize); @@ -81,7 +83,8 @@ RUN_ASYNC(const std::string &partitionName, const uint64_t bufferSize) { return {Helper::format("Can't write zero bytes to partition: %s: %s", partitionName.data(), strerror(errno)), false}; - else bytesWritten += result; + else + bytesWritten += result; } return {Helper::format("Successfully wrote zero bytes to the %s partition", @@ -104,7 +107,7 @@ INIT { RUN { std::vector> futures; - for (const auto &partitionName : partitions) { + for (const auto& partitionName : partitions) { uint64_t buf = bufferSize; setupBufferSize(buf, partitionName); futures.push_back( @@ -115,12 +118,13 @@ RUN { std::string end; bool endResult = true; - for (auto &future : futures) { + for (auto& future : futures) { auto [fst, snd] = future.get(); if (!snd) { end += fst + '\n'; endResult = false; - } else println("%s", fst.c_str()); + } else + println("%s", fst.c_str()); } if (!endResult) throw Error("%s", end.c_str()); @@ -132,4 +136,4 @@ RUN { IS_USED_COMMON_BODY NAME { return EFUN; } -} // namespace PartitionManager +} // namespace PartitionManager diff --git a/src/functions/FlashFunction.cpp b/src/functions/FlashFunction.cpp index b514d7c..e33d670 100644 --- a/src/functions/FlashFunction.cpp +++ b/src/functions/FlashFunction.cpp @@ -14,19 +14,21 @@ Copyright 2025 Yağız Zengin limitations under the License. */ -#include "functions.hpp" +#include +#include + #include #include #include -#include #include -#include + +#include "functions.hpp" #define FFUN "flashFunction" #define FUNCTION_CLASS flashFunction namespace PartitionManager { -RUN_ASYNC(const std::string &partitionName, const std::string &imageName, +RUN_ASYNC(const std::string& partitionName, const std::string& imageName, const uint64_t bufferSize, const bool deleteAfterProgress) { if (!Helper::fileIsExists(imageName)) return {Helper::format("Couldn't find image file: %s", imageName.data()), @@ -75,7 +77,7 @@ RUN_ASYNC(const std::string &partitionName, const std::string &imageName, LOGN(FFUN, INFO) << "Writing image " << imageName << " to partition: " << partitionName << std::endl; - auto *buffer = new (std::nothrow) char[bufferSize]; + auto* buffer = new (std::nothrow) char[bufferSize]; collector.delAfterProgress(buffer); memset(buffer, 0x00, bufferSize); @@ -146,12 +148,13 @@ RUN { std::string end; bool endResult = true; - for (auto &future : futures) { + for (auto& future : futures) { auto [fst, snd] = future.get(); if (!snd) { end += fst + '\n'; endResult = false; - } else println("%s", fst.c_str()); + } else + println("%s", fst.c_str()); } if (!endResult) throw Error("%s", end.c_str()); @@ -163,4 +166,4 @@ RUN { IS_USED_COMMON_BODY NAME { return FFUN; } -} // namespace PartitionManager +} // namespace PartitionManager diff --git a/src/functions/InfoFunction.cpp b/src/functions/InfoFunction.cpp index 38939fe..45725f9 100644 --- a/src/functions/InfoFunction.cpp +++ b/src/functions/InfoFunction.cpp @@ -14,13 +14,15 @@ Copyright 2025 Yağız Zengin limitations under the License. */ -#include "functions.hpp" +#include + #include #include #include -#include #include +#include "functions.hpp" + #define IFUN "infoFunction" #define FUNCTION_CLASS infoFunction @@ -30,11 +32,12 @@ INIT { LOGN(IFUN, INFO) << "Initializing variables of info printer function." << std::endl; cmd = _app.add_subcommand("info", "Tell info(s) of input partition list") - ->footer("Use get-all or getvar-all as partition name for getting " - "info's of all partitions.\nUse get-logicals as partition " - "name for getting info's of logical partitions.\n" - "Use get-physical as partition name for getting info's of " - "physical partitions."); + ->footer( + "Use get-all or getvar-all as partition name for getting " + "info's of all partitions.\nUse get-logicals as partition " + "name for getting info's of logical partitions.\n" + "Use get-physical as partition name for getting info's of " + "physical partitions."); cmd->add_option("partition(s)", partitions, "Partition name(s).") ->required() ->delimiter(','); @@ -103,13 +106,14 @@ RUN { PART_MAP.doForLogicalPartitions(func); else if (partitions.back() == "get-physicals") PART_MAP.doForPhysicalPartitions(func); - else PART_MAP.doForPartitionList(partitions, func); + else + PART_MAP.doForPartitionList(partitions, func); if (jsonFormat) { nlohmann::json j; j["multipleType"] = Helper::multipleToString(multiple); j["partitions"] = nlohmann::json::array(); - for (const auto &[name, props] : jParts) { + for (const auto& [name, props] : jParts) { j["partitions"].push_back({{jNamePartition, name}, {jNameSize, props.size}, {jNameLogical, props.isLogical}}); @@ -124,4 +128,4 @@ RUN { IS_USED_COMMON_BODY NAME { return IFUN; }; -} // namespace PartitionManager +} // namespace PartitionManager diff --git a/src/functions/MemoryTestFunction.cpp b/src/functions/MemoryTestFunction.cpp index 3448295..3fba2d3 100644 --- a/src/functions/MemoryTestFunction.cpp +++ b/src/functions/MemoryTestFunction.cpp @@ -14,14 +14,16 @@ Copyright 2025 Yağız Zengin limitations under the License. */ -#include "functions.hpp" +#include +#include + #include #include #include #include -#include #include -#include + +#include "functions.hpp" #define MTFUN "memoryTestFunction" #define FUNCTION_CLASS memoryTestFunction @@ -35,7 +37,7 @@ INIT { cmd = _app.add_subcommand("memtest", "Test your write/read speed of device."); cmd->add_option("testDirectory", testPath, "Path to test directory") ->default_val("/data/local/tmp") - ->check([&](const std::string &val) { + ->check([&](const std::string& val) { if (val.find("/sdcard") != std::string::npos || val.find("/storage") != std::string::npos) return std::string( @@ -69,7 +71,7 @@ RUN { const std::string test = Helper::pathJoin(testPath, "test.bin"); LOGN(MTFUN, INFO) << "Generating random data for testing" << std::endl; - auto *buffer = new (std::nothrow) char[bufferSize]; + auto* buffer = new (std::nothrow) char[bufferSize]; collector.delAfterProgress(buffer); for (size_t i = 0; i < bufferSize; i++) @@ -99,9 +101,9 @@ RUN { LOGN(MTFUN, INFO) << "Sequential write test done!" << std::endl; if (!doNotReadTest) { - auto *rawBuffer = new char[bufferSize + 4096]; + auto* rawBuffer = new char[bufferSize + 4096]; collector.delAfterProgress(rawBuffer); - auto *bufferRead = reinterpret_cast( + auto* bufferRead = reinterpret_cast( (reinterpret_cast(rawBuffer) + 4096 - 1) & ~(4096 - 1)); const int rfd = Helper::openAndAddToCloseList(test, collector, O_RDONLY | O_DIRECT); @@ -129,4 +131,4 @@ RUN { IS_USED_COMMON_BODY NAME { return MTFUN; } -} // namespace PartitionManager +} // namespace PartitionManager diff --git a/src/functions/PartitionSizeFunction.cpp b/src/functions/PartitionSizeFunction.cpp index ee6f6a0..fee476d 100644 --- a/src/functions/PartitionSizeFunction.cpp +++ b/src/functions/PartitionSizeFunction.cpp @@ -14,9 +14,10 @@ Copyright 2025 Yağız Zengin limitations under the License. */ -#include "functions.hpp" #include +#include "functions.hpp" + #define SFUN "partitionSizeFunction" #define FUNCTION_CLASS partitionSizeFunction @@ -26,11 +27,12 @@ INIT { << "Initializing variables of partition size getter function." << std::endl; cmd = _app.add_subcommand("sizeof", "Tell size(s) of input partition list") - ->footer("Use get-all or getvar-all as partition name for getting " - "sizes of all partitions.\nUse get-logicals as partition " - "name for getting sizes of logical partitions.\n" - "Use get-physical as partition name for getting sizes of " - "physical partitions."); + ->footer( + "Use get-all or getvar-all as partition name for getting " + "sizes of all partitions.\nUse get-logicals as partition " + "name for getting sizes of logical partitions.\n" + "Use get-physical as partition name for getting sizes of " + "physical partitions."); cmd->add_option("partition(s)", partitions, "Partition name(s).") ->required() ->delimiter(','); @@ -72,7 +74,8 @@ RUN { partition.data()); } - if (onlySize) println("%d", Helper::convertTo(props.size, multiple)); + if (onlySize) + println("%d", Helper::convertTo(props.size, multiple)); else println("%s: %d%s", partition.data(), Helper::convertTo(props.size, multiple), @@ -87,7 +90,8 @@ RUN { PART_MAP.doForLogicalPartitions(func); else if (partitions.back() == "get-physicals") PART_MAP.doForPhysicalPartitions(func); - else PART_MAP.doForPartitionList(partitions, func); + else + PART_MAP.doForPartitionList(partitions, func); return true; } @@ -95,4 +99,4 @@ RUN { IS_USED_COMMON_BODY NAME { return SFUN; } -} // namespace PartitionManager +} // namespace PartitionManager diff --git a/src/functions/RealPathFunction.cpp b/src/functions/RealPathFunction.cpp index b37b9a4..1fcde51 100644 --- a/src/functions/RealPathFunction.cpp +++ b/src/functions/RealPathFunction.cpp @@ -14,9 +14,10 @@ limitations under the License. */ -#include "functions.hpp" #include +#include "functions.hpp" + #define RPFUN "realPathFunction" #define FUNCTION_CLASS realPathFunction @@ -34,7 +35,7 @@ INIT { } RUN { - for (const auto &partition : partitions) { + for (const auto& partition : partitions) { if (!PART_MAP.hasPartition(partition)) throw Error("Couldn't find partition: %s", partition.data()); @@ -51,7 +52,8 @@ RUN { if (realLinkPath) println("%s", PART_MAP.getRealLinkPathOf(partition).data()); - else println("%s", PART_MAP.getRealPathOf(partition).data()); + else + println("%s", PART_MAP.getRealPathOf(partition).data()); } return true; @@ -60,4 +62,4 @@ RUN { IS_USED_COMMON_BODY NAME { return RPFUN; } -} // namespace PartitionManager +} // namespace PartitionManager diff --git a/src/functions/RebootFunction.cpp b/src/functions/RebootFunction.cpp index 06dd349..ed10420 100644 --- a/src/functions/RebootFunction.cpp +++ b/src/functions/RebootFunction.cpp @@ -14,9 +14,10 @@ Copyright 2025 Yağız Zengin limitations under the License. */ -#include "functions.hpp" #include +#include "functions.hpp" + #define RFUN "rebootFunction" #define FUNCTION_CLASS rebootFunction @@ -35,8 +36,10 @@ RUN { << (rebootTarget.empty() ? "none" : rebootTarget) << std::endl; - if (Helper::androidReboot(rebootTarget)) println("Reboot command was sent"); - else throw Error("Cannot reboot device"); + if (Helper::androidReboot(rebootTarget)) + println("Reboot command was sent"); + else + throw Error("Cannot reboot device"); return true; } @@ -44,4 +47,4 @@ RUN { IS_USED_COMMON_BODY NAME { return RFUN; } -} // namespace PartitionManager +} // namespace PartitionManager diff --git a/src/functions/TypeFunction.cpp b/src/functions/TypeFunction.cpp index 324c1d0..b2fa20f 100644 --- a/src/functions/TypeFunction.cpp +++ b/src/functions/TypeFunction.cpp @@ -14,10 +14,11 @@ limitations under the License. */ -#include "functions.hpp" #include #include +#include "functions.hpp" + #define TFUN "typeFunction" #define FUNCTION_CLASS typeFunction @@ -47,14 +48,15 @@ RUN { magics.merge(PartitionMap::Extras::AndroidMagicMap); else if (onlyCheckFileSystemMagics) magics.merge(PartitionMap::Extras::FileSystemMagicMap); - else magics.merge(PartitionMap::Extras::MagicMap); + else + magics.merge(PartitionMap::Extras::MagicMap); - for (const auto &content : contents) { + for (const auto& content : contents) { if (!PART_MAP.hasPartition(content) && !Helper::fileIsExists(content)) throw Error("Couldn't find partition or image file: %s", content.data()); bool found = false; - for (const auto &[magic, name] : magics) { + for (const auto& [magic, name] : magics) { if (PartitionMap::Extras::hasMagic( magic, static_cast(bufferSize), Helper::fileIsExists(content) @@ -79,4 +81,4 @@ IS_USED_COMMON_BODY NAME { return TFUN; } -} // namespace PartitionManager +} // namespace PartitionManager diff --git a/src/functions/functions.hpp b/src/functions/functions.hpp index bbdf065..25c0b84 100644 --- a/src/functions/functions.hpp +++ b/src/functions/functions.hpp @@ -21,133 +21,133 @@ #include #include -#define INIT bool FUNCTION_CLASS::init(CLI::App &_app) +#define INIT bool FUNCTION_CLASS::init(CLI::App& _app) #define RUN bool FUNCTION_CLASS::run() #define RUN_ASYNC pair FUNCTION_CLASS::runAsync #define IS_USED bool FUNCTION_CLASS::isUsed() const -#define IS_USED_COMMON_BODY \ +#define IS_USED_COMMON_BODY \ bool FUNCTION_CLASS::isUsed() const { return cmd->parsed(); } -#define NAME const char *FUNCTION_CLASS::name() const +#define NAME const char* FUNCTION_CLASS::name() const /** * Please define FUNCTION_CLASS before using these macros!!! (INIT etc.) */ -#define COMMON_FUNCTION_BODY() \ - CLI::App *cmd = nullptr; \ - bool init(CLI::App &_app) override; \ - bool run() override; \ - [[nodiscard]] bool isUsed() const override; \ - [[nodiscard]] const char *name() const override +#define COMMON_FUNCTION_BODY() \ + CLI::App* cmd = nullptr; \ + bool init(CLI::App& _app) override; \ + bool run() override; \ + [[nodiscard]] bool isUsed() const override; \ + [[nodiscard]] const char* name() const override namespace PartitionManager { using pair = std::pair; // Back-up function class backupFunction final : public FunctionBase { -private: + private: std::vector partitions, outputNames; std::string rawPartitions, rawOutputNames, outputDirectory; uint64_t bufferSize = 0; -public: + public: COMMON_FUNCTION_BODY(); - static pair runAsync(const std::string &partitionName, - const std::string &outputName, uint64_t bufferSize); + static pair runAsync(const std::string& partitionName, + const std::string& outputName, uint64_t bufferSize); }; // Image flasher function class flashFunction final : public FunctionBase { -private: + private: std::vector partitions, imageNames; std::string rawPartitions, rawImageNames, imageDirectory; uint64_t bufferSize = 0; bool deleteAfterProgress = false; -public: + public: COMMON_FUNCTION_BODY(); - static pair runAsync(const std::string &partitionName, - const std::string &imageName, uint64_t bufferSize, + static pair runAsync(const std::string& partitionName, + const std::string& imageName, uint64_t bufferSize, bool deleteAfterProgress); }; // Eraser function (writes zero bytes to partition) class eraseFunction final : public FunctionBase { -private: + private: std::vector partitions; uint64_t bufferSize = 0; -public: + public: COMMON_FUNCTION_BODY(); - static pair runAsync(const std::string &partitionName, uint64_t bufferSize); + static pair runAsync(const std::string& partitionName, uint64_t bufferSize); }; // Partition size getter function class partitionSizeFunction final : public FunctionBase { -private: + private: std::vector partitions; bool onlySize = false, asByte = false, asKiloBytes = false, asMega = false, asGiga = false; -public: + public: COMMON_FUNCTION_BODY(); }; // Partition info getter function class infoFunction final : public FunctionBase { -private: + private: std::vector partitions; std::string jNamePartition, jNameSize, jNameLogical; int jIndentSize = 2; bool jsonFormat = false, asByte = true, asKiloBytes = false, asMega = false, asGiga = false; -public: + public: COMMON_FUNCTION_BODY(); }; class realPathFunction final : public FunctionBase { -private: + private: std::vector partitions; bool realLinkPath = false; -public: + public: COMMON_FUNCTION_BODY(); }; class typeFunction final : public FunctionBase { -private: + private: std::vector contents; bool onlyCheckAndroidMagics = false, onlyCheckFileSystemMagics = false; uint64_t bufferSize = 0; -public: + public: COMMON_FUNCTION_BODY(); }; class rebootFunction final : public FunctionBase { -private: + private: std::string rebootTarget; -public: + public: COMMON_FUNCTION_BODY(); }; class memoryTestFunction final : public FunctionBase { -private: + private: uint64_t bufferSize = MB(4), /* bufferSizeRandom = KB(4),*/ testFileSize = 0; std::string testPath; bool doNotReadTest = false; -public: + public: COMMON_FUNCTION_BODY(); }; class cleanLogFunction final : public FunctionBase { -public: + public: COMMON_FUNCTION_BODY(); }; -} // namespace PartitionManager +} // namespace PartitionManager -#endif // #ifndef FUNCTIONS_HPP +#endif // #ifndef FUNCTIONS_HPP diff --git a/srclib/libhelper/include/libhelper/lib.hpp b/srclib/libhelper/include/libhelper/lib.hpp index a19bfcb..8c75722 100644 --- a/srclib/libhelper/include/libhelper/lib.hpp +++ b/srclib/libhelper/include/libhelper/lib.hpp @@ -17,8 +17,9 @@ #ifndef LIBHELPER_LIB_HPP #define LIBHELPER_LIB_HPP -#include #include + +#include #include #include #include @@ -29,13 +30,13 @@ #include #include -#define KB(x) (static_cast(x) * 1024) // KB(8) = 8192 (8 * 1024) -#define MB(x) (KB(x) * 1024) // MB(4) = 4194304 (KB(4) * 1024) -#define GB(x) (MB(x) * 1024) // GB(1) = 1073741824 (MB(1) * 1024) +#define KB(x) (static_cast(x) * 1024) // KB(8) = 8192 (8 * 1024) +#define MB(x) (KB(x) * 1024) // MB(4) = 4194304 (KB(4) * 1024) +#define GB(x) (MB(x) * 1024) // GB(1) = 1073741824 (MB(1) * 1024) -#define TO_KB(x) (x / 1024) // TO_KB(1024) = 1 -#define TO_MB(x) (TO_KB(x) / 1024) // TO_MB(2048) (2048 / 1024) -#define TO_GB(x) (TO_MB(x) / 1024) // TO_GB(1048576) (TO_MB(1048576) / 1024) +#define TO_KB(x) (x / 1024) // TO_KB(1024) = 1 +#define TO_MB(x) (TO_KB(x) / 1024) // TO_MB(2048) (2048 / 1024) +#define TO_GB(x) (TO_MB(x) / 1024) // TO_GB(1048576) (TO_MB(1048576) / 1024) #ifndef ONLY_HELPER_MACROS @@ -62,57 +63,59 @@ constexpr int NO = 0; namespace Helper { // Throwable error class class Error final : public std::exception { -private: + private: std::string _message; std::ostringstream _oss; -public: - __attribute__((format(printf, 2, 3))) explicit Error(const char *format, ...); + public: + __attribute__((format(printf, 2, 3))) explicit Error(const char* format, ...); - [[nodiscard]] const char *what() const noexcept override; + [[nodiscard]] const char* what() const noexcept override; }; // Logging class Logger final { -private: + private: LogLevels _level; std::ostringstream _oss; const char *_function_name, *_logFile, *_program_name, *_file; int _line; -public: - Logger(LogLevels level, const char *func, const char *file, const char *name, - const char *source_file, int line); + public: + Logger(LogLevels level, const char* func, const char* file, const char* name, + const char* source_file, int line); ~Logger(); - template Logger &operator<<(const T &msg) { + template + Logger& operator<<(const T& msg) { _oss << msg; return *this; } - Logger &operator<<(std::ostream &(*msg)(std::ostream &)); + Logger& operator<<(std::ostream& (*msg)(std::ostream&)); }; // Close file descriptors and delete allocated array memory class garbageCollector { -private: + private: std::vector> _cleaners; - std::vector _fps; - std::vector _dps; + std::vector _fps; + std::vector _dps; std::vector _fds; std::vector _files; -public: + public: ~garbageCollector(); - template void delAfterProgress(T *_ptr) { + template + void delAfterProgress(T* _ptr) { _cleaners.push_back([_ptr] { delete[] _ptr; }); } - void delFileAfterProgress(const std::string &_path); - void closeAfterProgress(FILE *_fp); - void closeAfterProgress(DIR *_dp); + void delFileAfterProgress(const std::string& _path); + void closeAfterProgress(FILE* _fp); + void closeAfterProgress(DIR* _dp); void closeAfterProgress(int _fd); }; @@ -122,7 +125,7 @@ class Random { static_assert(count > 1, "count is larger than 1"); static_assert(count <= max - start, "count is greater than max-start"); -public: + public: static std::set get() { std::set set; std::random_device rd; @@ -130,12 +133,10 @@ public: if constexpr (d > 0) { std::uniform_int_distribution<> dist(0, (max - start - 1) / d); - while (set.size() < count) - set.insert(start + dist(gen) * d); + while (set.size() < count) set.insert(start + dist(gen) * d); } else { std::uniform_int_distribution<> dist(start, max - 1); - while (set.size() < count) - set.insert(dist(gen)); + while (set.size() < count) set.insert(dist(gen)); } return set; @@ -150,7 +151,7 @@ public: std::uniform_int_distribution<> dist(0, (max - start - 1) / d); ret = start + dist(gen) * d; } else { - std::uniform_int_distribution<> dist(start, max - 1); // max exclusive + std::uniform_int_distribution<> dist(start, max - 1); // max exclusive ret = dist(gen); } @@ -158,39 +159,39 @@ public: } }; -template class PureTuple { -private: +template +class PureTuple { + private: void expand_if_needed() { if (count == capacity) { capacity *= 2; - Data *data = new Data[capacity]; + Data* data = new Data[capacity]; - for (size_t i = 0; i < count; i++) - data[i] = tuple_data[i]; + for (size_t i = 0; i < count; i++) data[i] = tuple_data[i]; delete[] tuple_data; tuple_data = data; } } -public: + public: struct Data { _Type1 first; _Type2 second; _Type3 third; - bool - operator==(const std::tuple<_Type1, _Type2, _Type3> &t) const noexcept { + bool operator==( + const std::tuple<_Type1, _Type2, _Type3>& t) const noexcept { return first == std::get<0>(t) && second == std::get<1>(t) && third == std::get<2>(t); } - bool operator==(const Data &other) const noexcept { + bool operator==(const Data& other) const noexcept { return first == other.first && second == other.second && third == other.third; } - bool operator!=(const Data &other) const noexcept { + bool operator!=(const Data& other) const noexcept { return !(*this == other); } @@ -200,13 +201,13 @@ public: bool operator!() const noexcept { return !bool{*this}; } - void operator()(const std::tuple<_Type1, _Type2, _Type3> &t) { + void operator()(const std::tuple<_Type1, _Type2, _Type3>& t) { first = std::get<0>(t); second = std::get<1>(t); third = std::get<2>(t); } - Data &operator=(const std::tuple<_Type1, _Type2, _Type3> &t) { + Data& operator=(const std::tuple<_Type1, _Type2, _Type3>& t) { first = std::get<0>(t); second = std::get<1>(t); third = std::get<2>(t); @@ -214,7 +215,7 @@ public: } }; - Data *tuple_data = nullptr; + Data* tuple_data = nullptr; Data tuple_data_type = {_Type1{}, _Type2{}, _Type3{}}; size_t capacity{}, count{}; @@ -223,38 +224,39 @@ public: PureTuple(std::initializer_list val) : tuple_data(new Data[20]), capacity(20), count(0) { - for (const auto &v : val) - insert(v); + for (const auto& v : val) insert(v); } - PureTuple(PureTuple &other) - : tuple_data(new Data[other.capacity]), capacity(other.capacity), + PureTuple(PureTuple& other) + : tuple_data(new Data[other.capacity]), + capacity(other.capacity), count(other.count) { std::copy(other.tuple_data, other.tuple_data + count, tuple_data); } - PureTuple(PureTuple &&other) noexcept - : tuple_data(new Data[other.capacity]), capacity(other.capacity), + PureTuple(PureTuple&& other) noexcept + : tuple_data(new Data[other.capacity]), + capacity(other.capacity), count(other.count) { std::copy(other.tuple_data, other.tuple_data + count, tuple_data); other.clear(); } class iterator { - private: - Data *it; + private: + Data* it; - public: + public: using iterator_category = std::random_access_iterator_tag; using value_type = Data; using difference_type = std::ptrdiff_t; - using pointer = Data *; - using reference = Data &; + using pointer = Data*; + using reference = Data&; - explicit iterator(Data *ptr) : it(ptr) {} + explicit iterator(Data* ptr) : it(ptr) {} pointer operator->() const { return it; } reference operator*() { return *it; } - iterator &operator++() { + iterator& operator++() { ++it; return *this; } @@ -263,7 +265,7 @@ public: ++(*this); return tmp; } - iterator &operator--() { + iterator& operator--() { --it; return *this; } @@ -273,32 +275,32 @@ public: return tmp; } - iterator &operator+=(difference_type n) { + iterator& operator+=(difference_type n) { it += n; return *this; } iterator operator+(difference_type n) const { return iterator(it + n); } - iterator &operator-=(difference_type n) { + iterator& operator-=(difference_type n) { it -= n; return *this; } iterator operator-(difference_type n) const { return iterator(it - n); } - difference_type operator-(const iterator &other) const { + difference_type operator-(const iterator& other) const { return it - other.it; } reference operator[](difference_type n) const { return it[n]; } - bool operator<(const iterator &other) const { return it < other.it; } - bool operator>(const iterator &other) const { return it > other.it; } - bool operator<=(const iterator &other) const { return it <= other.it; } - bool operator>=(const iterator &other) const { return it >= other.it; } + bool operator<(const iterator& other) const { return it < other.it; } + bool operator>(const iterator& other) const { return it > other.it; } + bool operator<=(const iterator& other) const { return it <= other.it; } + bool operator>=(const iterator& other) const { return it >= other.it; } - bool operator!=(const iterator &other) const { return it != other.it; } - bool operator==(const iterator &other) const { return it == other.it; } + bool operator!=(const iterator& other) const { return it != other.it; } + bool operator==(const iterator& other) const { return it == other.it; } }; - bool find(const Data &data) const noexcept { + bool find(const Data& data) const noexcept { for (size_t i = 0; i < count; i++) if (data == tuple_data[i]) return true; @@ -307,51 +309,50 @@ public: template > std::enable_if_t>, bool> - find(const std::tuple<_Type1, _Type2, _Type3> &t) const noexcept { + find(const std::tuple<_Type1, _Type2, _Type3>& t) const noexcept { for (size_t i = 0; i < count; i++) if (tuple_data[i] == t) return true; return false; } - bool find(const _Type1 &val, const _Type2 &val2, - const _Type3 &val3) const noexcept { + bool find(const _Type1& val, const _Type2& val2, + const _Type3& val3) const noexcept { for (size_t i = 0; i < count; i++) if (tuple_data[i] == std::make_tuple(val, val2, val3)) return true; return false; } - void insert(const Data &val) noexcept { + void insert(const Data& val) noexcept { expand_if_needed(); if (!find(val)) tuple_data[count++] = val; } template > std::enable_if_t>, void> - insert(const std::tuple<_Type1, _Type2, _Type3> &t) noexcept { + insert(const std::tuple<_Type1, _Type2, _Type3>& t) noexcept { expand_if_needed(); if (!find(t)) tuple_data[count++] = Data{std::get<0>(t), std::get<1>(t), std::get<2>(t)}; } - void insert(const _Type1 &val, const _Type2 &val2, - const _Type3 &val3) noexcept { + void insert(const _Type1& val, const _Type2& val2, + const _Type3& val3) noexcept { expand_if_needed(); if (!find(val, val2, val3)) tuple_data[count++] = Data{val, val2, val3}; } - void merge(const PureTuple &other) noexcept { - for (const auto &v : other) - insert(v); + void merge(const PureTuple& other) noexcept { + for (const auto& v : other) insert(v); } void pop_back() noexcept { if (count > 0) --count; } - void pop(const Data &data) noexcept { + void pop(const Data& data) noexcept { for (size_t i = 0; i < count; i++) { if (tuple_data[i] == data) { for (size_t j = i; j < count - 1; j++) @@ -374,7 +375,7 @@ public: } } - void pop(const _Type1 &val, const _Type2 &val2, const _Type3 &val3) noexcept { + void pop(const _Type1& val, const _Type2& val2, const _Type3& val3) noexcept { for (size_t i = 0; i < count; i++) { if (tuple_data[i] == std::make_tuple(val, val2, val3)) { for (size_t j = i; j < count - 1; j++) @@ -387,7 +388,7 @@ public: template > std::enable_if_t>, void> - pop(const std::tuple<_Type1, _Type2, _Type3> &t) noexcept { + pop(const std::tuple<_Type1, _Type2, _Type3>& t) noexcept { for (size_t i = 0; i < count; i++) { if (tuple_data[i] == t) { for (size_t j = i; j < count - 1; j++) @@ -435,7 +436,7 @@ public: explicit operator bool() const noexcept { return count > 0; } bool operator!() const noexcept { return count == 0; } - bool operator==(const PureTuple &other) const noexcept { + bool operator==(const PureTuple& other) const noexcept { if (this->count != other.count || this->capacity != other.capacity) return false; @@ -444,7 +445,7 @@ public: return true; } - bool operator!=(const PureTuple &other) const noexcept { + bool operator!=(const PureTuple& other) const noexcept { return !(*this == other); } @@ -454,7 +455,7 @@ public: } explicit operator int() const noexcept { return count; } - PureTuple &operator=(const PureTuple &other) { + PureTuple& operator=(const PureTuple& other) { if (this != &other) { delete[] tuple_data; @@ -468,70 +469,71 @@ public: return *this; } - PureTuple &operator<<(const std::tuple<_Type1, _Type2, _Type3> &t) noexcept { + PureTuple& operator<<(const std::tuple<_Type1, _Type2, _Type3>& t) noexcept { insert(t); return *this; } - friend PureTuple &operator>>(const std::tuple<_Type1, _Type2, _Type3> &t, - PureTuple &tuple) noexcept { + friend PureTuple& operator>>(const std::tuple<_Type1, _Type2, _Type3>& t, + PureTuple& tuple) noexcept { tuple.insert(t); return tuple; } }; // Provides a capsule structure to store variable references and values. -template class Capsule : public garbageCollector { -public: - _Type &value; +template +class Capsule : public garbageCollector { + public: + _Type& value; // The value to be stored is taken as a reference as an argument - explicit Capsule(_Type &value) noexcept : value(value) {} + explicit Capsule(_Type& value) noexcept : value(value) {} // Set the value. - void set(const _Type &_value) noexcept { this->value = _value; } - void set(_Type &_value) noexcept { this->value = _value; } + void set(const _Type& _value) noexcept { this->value = _value; } + void set(_Type& _value) noexcept { this->value = _value; } // Get reference of the value. - _Type &get() noexcept { return this->value; } - const _Type &get() const noexcept { return this->value; } + _Type& get() noexcept { return this->value; } + const _Type& get() const noexcept { return this->value; } // You can get the reference of the stored value in the input type (casting is // required). - operator _Type &() noexcept { return this->value; } - operator const _Type &() const noexcept { return this->value; } - explicit operator _Type *() noexcept { return &this->value; } + operator _Type&() noexcept { return this->value; } + operator const _Type&() const noexcept { return this->value; } + explicit operator _Type*() noexcept { return &this->value; } // The value of another capsule is taken. - Capsule &operator=(const Capsule &other) noexcept { + Capsule& operator=(const Capsule& other) noexcept { this->value = other.value; return *this; } // Assign another value. - Capsule &operator=(const _Type &_value) noexcept { + Capsule& operator=(const _Type& _value) noexcept { this->value = _value; return *this; } // Check if this capsule and another capsule hold the same data. - bool operator==(const Capsule &other) const noexcept { + bool operator==(const Capsule& other) const noexcept { return this->value == other.value; } // Check if this capsule value and another capsule value hold the same data. - bool operator==(const _Type &_value) const noexcept { + bool operator==(const _Type& _value) const noexcept { return this->value == _value; } // Check that this capsule and another capsule do not hold the same data. - bool operator!=(const Capsule &other) const noexcept { + bool operator!=(const Capsule& other) const noexcept { return !(*this == other); } // Check that this capsule value and another capsule value do not hold the // same data. - bool operator!=(const _Type &_value) const noexcept { + bool operator!=(const _Type& _value) const noexcept { return !(*this == _value); } @@ -542,17 +544,17 @@ public: bool operator!() const noexcept { return this->value == _Type{}; } // Change the value with the input operator. - friend Capsule &operator>>(const _Type &_value, Capsule &_capsule) noexcept { + friend Capsule& operator>>(const _Type& _value, Capsule& _capsule) noexcept { _capsule.value = _value; return _capsule; } // Get the reference of the value held. - _Type &operator()() noexcept { return value; } - const _Type &operator()() const noexcept { return value; } + _Type& operator()() noexcept { return value; } + const _Type& operator()() const noexcept { return value; } // Set the value. - void operator()(const _Type &_value) noexcept { this->value = _value; } + void operator()(const _Type& _value) noexcept { this->value = _value; } }; namespace LoggingProperties { @@ -563,17 +565,23 @@ void set(std::string_view name, std::string_view file); void setProgramName(std::string_view name); void setLogFile(std::string_view file); -template void setPrinting() { - if (state == 1 || state == 0) PRINT = state; - else PRINT = NO; +template +void setPrinting() { + if (state == 1 || state == 0) + PRINT = state; + else + PRINT = NO; } -template void setLoggingState() { - if (state == 1 || state == 0) DISABLE = state; - else DISABLE = NO; +template +void setLoggingState() { + if (state == 1 || state == 0) + DISABLE = state; + else + DISABLE = NO; } void reset(); -} // namespace LoggingProperties +} // namespace LoggingProperties // ------------------------------- // Checkers - not throws Helper::Error @@ -803,13 +811,14 @@ std::string multipleToString(sizeCastTypes type); /** * Format it input and return as std::string. */ -__attribute__((format(printf, 1, 2))) std::string format(const char *format, +__attribute__((format(printf, 1, 2))) std::string format(const char* format, ...); /** * Convert input size to input multiple */ -template int convertTo(const sizeCastTypes type) { +template +int convertTo(const sizeCastTypes type) { if (type == KB) return TO_KB(size); if (type == MB) return TO_MB(size); if (type == GB) return TO_GB(size); @@ -840,26 +849,26 @@ std::string getLibVersion(); * Open input path with flags and add to integrity list. * And returns file descriptor. */ -[[nodiscard]] int openAndAddToCloseList(const std::string_view &path, - garbageCollector &collector, int flags, +[[nodiscard]] int openAndAddToCloseList(const std::string_view& path, + garbageCollector& collector, int flags, mode_t mode = 0000); /** * Open input path with flags and add to integrity list. * And returns file pointer. */ -[[nodiscard]] FILE *openAndAddToCloseList(const std::string_view &path, - garbageCollector &collector, - const char *mode); +[[nodiscard]] FILE* openAndAddToCloseList(const std::string_view& path, + garbageCollector& collector, + const char* mode); /** * Open input directory and add to integrity list. * And returns directory pointer. */ -[[nodiscard]] DIR *openAndAddToCloseList(const std::string_view &path, - garbageCollector &collector); +[[nodiscard]] DIR* openAndAddToCloseList(const std::string_view& path, + garbageCollector& collector); -} // namespace Helper +} // namespace Helper -#endif // #ifndef ONLY_HELPER_MACROS +#endif // #ifndef ONLY_HELPER_MACROS #define HELPER "libhelper" @@ -879,73 +888,73 @@ std::string getLibVersion(); #ifndef NO_C_TYPE_HANDLERS // ABORT(message), ex: ABORT("memory error!\n") -#define ABORT(msg) \ - do { \ - fprintf(stderr, "%s%sCRITICAL ERROR%s: %s\nAborting...\n", BOLD, RED, \ - STYLE_RESET, msg); \ - abort(); \ +#define ABORT(msg) \ + do { \ + fprintf(stderr, "%s%sCRITICAL ERROR%s: %s\nAborting...\n", BOLD, RED, \ + STYLE_RESET, msg); \ + abort(); \ } while (0) // ERROR(message, exit), ex: ERROR("an error occured.\n", 1) -#define ERROR(msg, code) \ - do { \ - fprintf(stderr, "%s%sERROR%s: %s", BOLD, RED, STYLE_RESET, msg); \ - exit(code); \ +#define ERROR(msg, code) \ + do { \ + fprintf(stderr, "%s%sERROR%s: %s", BOLD, RED, STYLE_RESET, msg); \ + exit(code); \ } while (0) // WARNING(message), ex: WARNING("using default setting.\n") -#define WARNING(msg) \ +#define WARNING(msg) \ fprintf(stderr, "%s%sWARNING%s: %s", BOLD, YELLOW, STYLE_RESET, msg); // INFO(message), ex: INFO("operation ended.\n") -#define INFO(msg) \ +#define INFO(msg) \ fprintf(stdout, "%s%sINFO%s: %s", BOLD, GREEN, STYLE_RESET, msg); -#endif // #ifndef NO_C_TYPE_HANDLERS +#endif // #ifndef NO_C_TYPE_HANDLERS -#define LOG(level) \ - Helper::Logger(level, __func__, Helper::LoggingProperties::FILE.data(), \ +#define LOG(level) \ + Helper::Logger(level, __func__, Helper::LoggingProperties::FILE.data(), \ Helper::LoggingProperties::NAME.data(), __FILE__, __LINE__) -#define LOGF(file, level) \ - Helper::Logger(level, __func__, file, \ +#define LOGF(file, level) \ + Helper::Logger(level, __func__, file, \ Helper::LoggingProperties::NAME.data(), __FILE__, __LINE__) -#define LOGN(name, level) \ - Helper::Logger(level, __func__, Helper::LoggingProperties::FILE.data(), \ +#define LOGN(name, level) \ + Helper::Logger(level, __func__, Helper::LoggingProperties::FILE.data(), \ name, __FILE__, __LINE__) -#define LOGNF(name, file, level) \ +#define LOGNF(name, file, level) \ Helper::Logger(level, file, name, __FILE__, __LINE__) -#define LOG_IF(level, condition) \ - if (condition) \ - Helper::Logger(level, __func__, Helper::LoggingProperties::FILE.data(), \ +#define LOG_IF(level, condition) \ + if (condition) \ + Helper::Logger(level, __func__, Helper::LoggingProperties::FILE.data(), \ Helper::LoggingProperties::NAME.data(), __FILE__, __LINE__) -#define LOGF_IF(file, level, condition) \ - if (condition) \ - Helper::Logger(level, __func__, file, \ +#define LOGF_IF(file, level, condition) \ + if (condition) \ + Helper::Logger(level, __func__, file, \ Helper::LoggingProperties::NAME.data(), __FILE__, __LINE__) -#define LOGN_IF(name, level, condition) \ - if (condition) \ - Helper::Logger(level, __func__, Helper::LoggingProperties::FILE.data(), \ +#define LOGN_IF(name, level, condition) \ + if (condition) \ + Helper::Logger(level, __func__, Helper::LoggingProperties::FILE.data(), \ name, __FILE__, __LINE__) -#define LOGNF_IF(name, file, level, condition) \ +#define LOGNF_IF(name, file, level, condition) \ if (condition) Helper::Logger(level, __func__, file, name, __FILE__, __LINE__) #ifdef ANDROID_BUILD -#define MKVERSION(name) \ - char vinfo[512]; \ - sprintf(vinfo, \ - "%s 1.3.0\nCompiler: clang\n" \ - "BuildFlags: -Wall;-Werror;-Wno-deprecated-declarations;-Os", \ - name); \ +#define MKVERSION(name) \ + char vinfo[512]; \ + sprintf(vinfo, \ + "%s 1.3.0\nCompiler: clang\n" \ + "BuildFlags: -Wall;-Werror;-Wno-deprecated-declarations;-Os", \ + name); \ return std::string(vinfo) #else -#define MKVERSION(name) \ - char vinfo[512]; \ - sprintf(vinfo, \ - "%s %s [%s %s]\nBuildType: %s\nCMakeVersion: %s\nCompilerVersion: " \ - "%s\nBuildFlags: %s", \ - name, BUILD_VERSION, BUILD_DATE, BUILD_TIME, BUILD_TYPE, \ - BUILD_CMAKE_VERSION, BUILD_COMPILER_VERSION, BUILD_FLAGS); \ +#define MKVERSION(name) \ + char vinfo[512]; \ + sprintf(vinfo, \ + "%s %s [%s %s]\nBuildType: %s\nCMakeVersion: %s\nCompilerVersion: " \ + "%s\nBuildFlags: %s", \ + name, BUILD_VERSION, BUILD_DATE, BUILD_TIME, BUILD_TYPE, \ + BUILD_CMAKE_VERSION, BUILD_COMPILER_VERSION, BUILD_FLAGS); \ return std::string(vinfo) #endif -#endif // #ifndef LIBHELPER_LIB_HPP +#endif // #ifndef LIBHELPER_LIB_HPP diff --git a/srclib/libhelper/src/Checkers.cpp b/srclib/libhelper/src/Checkers.cpp index 24a0c34..3bf8a1b 100644 --- a/srclib/libhelper/src/Checkers.cpp +++ b/srclib/libhelper/src/Checkers.cpp @@ -14,13 +14,14 @@ limitations under the License. */ -#include -#include -#include #include #include #include +#include +#include +#include + namespace Helper { bool hasSuperUser() { return (getuid() == AID_ROOT); } bool hasAdbPermissions() { return (getuid() == AID_SHELL); } @@ -68,4 +69,4 @@ bool areLinked(const std::string_view entry1, const std::string_view entry2) { return (st1 == st2); } -} // namespace Helper +} // namespace Helper diff --git a/srclib/libhelper/src/Classes.cpp b/srclib/libhelper/src/Classes.cpp index 4bca943..b4d89e0 100644 --- a/srclib/libhelper/src/Classes.cpp +++ b/srclib/libhelper/src/Classes.cpp @@ -14,22 +14,23 @@ limitations under the License. */ +#include +#include +#include +#include + #include #include #include #include #include -#include #include -#include #include -#include #include #include -#include namespace Helper { -Error::Error(const char *format, ...) { +Error::Error(const char* format, ...) { char buf[1024]; va_list args; va_start(args, format); @@ -39,19 +40,23 @@ Error::Error(const char *format, ...) { LOGN(HELPER, ERROR) << _message << std::endl; } -const char *Error::what() const noexcept { return _message.data(); } +const char* Error::what() const noexcept { return _message.data(); } -Logger::Logger(const LogLevels level, const char *func, const char *file, - const char *name, const char *source_file, const int line) - : _level(level), _function_name(func), _logFile(file), _program_name(name), - _file(source_file), _line(line) {} +Logger::Logger(const LogLevels level, const char* func, const char* file, + const char* name, const char* source_file, const int line) + : _level(level), + _function_name(func), + _logFile(file), + _program_name(name), + _file(source_file), + _line(line) {} Logger::~Logger() { if (LoggingProperties::DISABLE) return; char str[1024]; snprintf(str, sizeof(str), "<%c> [ %s %s] %s(): %s", static_cast(_level), _program_name, - basename(const_cast(_file)), _line, currentDate().data(), + basename(const_cast(_file)), _line, currentDate().data(), currentTime().data(), _function_name, _oss.str().data()); if (!isExists(_logFile)) { @@ -76,7 +81,7 @@ Logger::~Logger() { } } - if (FILE *fp = fopen(_logFile, "a"); fp != nullptr) { + if (FILE* fp = fopen(_logFile, "a"); fp != nullptr) { fprintf(fp, "%s", str); fclose(fp); } else { @@ -91,30 +96,25 @@ Logger::~Logger() { if (LoggingProperties::PRINT) printf("%s", str); } -Logger &Logger::operator<<(std::ostream &(*msg)(std::ostream &)) { +Logger& Logger::operator<<(std::ostream& (*msg)(std::ostream&)) { _oss << msg; return *this; } garbageCollector::~garbageCollector() { - for (auto &ptr_func : _cleaners) - ptr_func(); - for (const auto &fd : _fds) - close(fd); - for (const auto &fp : _fps) - fclose(fp); - for (const auto &dp : _dps) - closedir(dp); - for (const auto &file : _files) - eraseEntry(file); + for (auto& ptr_func : _cleaners) ptr_func(); + for (const auto& fd : _fds) close(fd); + for (const auto& fp : _fps) fclose(fp); + for (const auto& dp : _dps) closedir(dp); + for (const auto& file : _files) eraseEntry(file); } -void garbageCollector::delFileAfterProgress(const std::string &_path) { +void garbageCollector::delFileAfterProgress(const std::string& _path) { _files.push_back(_path); } void garbageCollector::closeAfterProgress(const int _fd) { _fds.push_back(_fd); } -void garbageCollector::closeAfterProgress(FILE *_fp) { _fps.push_back(_fp); } -void garbageCollector::closeAfterProgress(DIR *_dp) { _dps.push_back(_dp); } -} // namespace Helper +void garbageCollector::closeAfterProgress(FILE* _fp) { _fps.push_back(_fp); } +void garbageCollector::closeAfterProgress(DIR* _dp) { _dps.push_back(_dp); } +} // namespace Helper diff --git a/srclib/libhelper/src/FileUtil.cpp b/srclib/libhelper/src/FileUtil.cpp index 294ccc9..978cfaf 100644 --- a/srclib/libhelper/src/FileUtil.cpp +++ b/srclib/libhelper/src/FileUtil.cpp @@ -14,16 +14,17 @@ limitations under the License. */ +#include +#include +#include +#include + #include #include #include #include -#include -#include #include #include -#include -#include namespace Helper { bool writeFile(const std::string_view file, const std::string_view text) { @@ -31,7 +32,7 @@ bool writeFile(const std::string_view file, const std::string_view text) { << std::endl; garbageCollector collector; - FILE *fp = openAndAddToCloseList(file, collector, "a"); + FILE* fp = openAndAddToCloseList(file, collector, "a"); if (fp == nullptr) return false; fprintf(fp, "%s", text.data()); @@ -43,13 +44,12 @@ std::optional readFile(const std::string_view file) { LOGN(HELPER, INFO) << "read " << file << " requested." << std::endl; garbageCollector collector; - FILE *fp = openAndAddToCloseList(file, collector, "r"); + FILE* fp = openAndAddToCloseList(file, collector, "r"); if (fp == nullptr) return std::nullopt; char buffer[1024]; std::string str; - while (fgets(buffer, sizeof(buffer), fp)) - str += buffer; + while (fgets(buffer, sizeof(buffer), fp)) str += buffer; LOGN(HELPER, INFO) << "read " << file << " successfully, read text: \"" << str << "\"" << std::endl; @@ -95,7 +95,7 @@ bool makeRecursiveDirectory(const std::string_view paths) { snprintf(tmp, sizeof(tmp), "%s", paths.data()); if (const size_t len = strlen(tmp); tmp[len - 1] == '/') tmp[len - 1] = '\0'; - for (char *p = tmp + 1; *p; p++) { + for (char* p = tmp + 1; *p; p++) { if (*p == '/') { *p = '\0'; if (access(tmp, F_OK) != 0) { @@ -150,10 +150,10 @@ bool eraseEntry(const std::string_view entry) { bool eraseDirectoryRecursive(const std::string_view directory) { LOGN(HELPER, INFO) << "erase recursive requested: " << directory << std::endl; struct stat buf{}; - dirent *entry; + dirent* entry; garbageCollector collector; - DIR *dir = openAndAddToCloseList(directory.data(), collector); + DIR* dir = openAndAddToCloseList(directory.data(), collector); if (dir == nullptr) return false; while ((entry = readdir(dir)) != nullptr) { @@ -202,4 +202,4 @@ int64_t fileSize(const std::string_view file) { if (stat(file.data(), &st) != 0) return -1; return st.st_size; } -} // namespace Helper +} // namespace Helper diff --git a/srclib/libhelper/src/Sha256.cpp b/srclib/libhelper/src/Sha256.cpp index 48eec21..eac9eda 100644 --- a/srclib/libhelper/src/Sha256.cpp +++ b/srclib/libhelper/src/Sha256.cpp @@ -14,13 +14,14 @@ limitations under the License. */ +#include +#include + #include #include #include #include -#include #include -#include #include namespace Helper { @@ -54,4 +55,4 @@ bool sha256Compare(const std::string_view file1, const std::string_view file2) { << "(): input files is contains same sha256 signature." << std::endl; return (*f1 == *f2); } -} // namespace Helper +} // namespace Helper diff --git a/srclib/libhelper/src/Utilities.cpp b/srclib/libhelper/src/Utilities.cpp index ee84d5f..383e9bf 100644 --- a/srclib/libhelper/src/Utilities.cpp +++ b/srclib/libhelper/src/Utilities.cpp @@ -14,52 +14,57 @@ limitations under the License. */ +#include +#include + #include #include #include -#include -#include #ifndef ANDROID_BUILD -#include #include + +#include #else #include #endif -#include #include -#include #include -#include -#include -#include -#include #include #include #include +#include +#include +#include +#include +#include +#include + #ifdef __ANDROID__ // From system/core/libcutils/android_reboot.cpp android16-s2-release -int android_reboot(const unsigned cmd, int /*flags*/, const char *arg) { +int android_reboot(const unsigned cmd, int /*flags*/, const char* arg) { int ret; - const char *restart_cmd = nullptr; - char *prop_value; + const char* restart_cmd = nullptr; + char* prop_value; switch (cmd) { - case ANDROID_RB_RESTART: // deprecated - case ANDROID_RB_RESTART2: - restart_cmd = "reboot"; - break; - case ANDROID_RB_POWEROFF: - restart_cmd = "shutdown"; - break; - case ANDROID_RB_THERMOFF: - restart_cmd = "shutdown,thermal"; - break; + case ANDROID_RB_RESTART: // deprecated + case ANDROID_RB_RESTART2: + restart_cmd = "reboot"; + break; + case ANDROID_RB_POWEROFF: + restart_cmd = "shutdown"; + break; + case ANDROID_RB_THERMOFF: + restart_cmd = "shutdown,thermal"; + break; } if (!restart_cmd) return -1; - if (arg && arg[0]) ret = asprintf(&prop_value, "%s,%s", restart_cmd, arg); - else ret = asprintf(&prop_value, "%s", restart_cmd); + if (arg && arg[0]) + ret = asprintf(&prop_value, "%s,%s", restart_cmd, arg); + else + ret = asprintf(&prop_value, "%s", restart_cmd); if (ret < 0) return -1; ret = __system_property_set(ANDROID_RB_PROPERTY, prop_value); @@ -86,7 +91,7 @@ void set(std::string_view file, std::string_view name) { void setProgramName(const std::string_view name) { NAME = name; } void setLogFile(const std::string_view file) { FILE = file; } -} // namespace LoggingProperties +} // namespace LoggingProperties bool runCommand(const std::string_view cmd) { LOGN(HELPER, INFO) << "run command request: " << cmd << std::endl; @@ -116,7 +121,7 @@ std::string currentWorkingDirectory() { std::string currentDate() { const time_t t = time(nullptr); - if (const tm *date = localtime(&t)) + if (const tm* date = localtime(&t)) return std::string(std::to_string(date->tm_mday) + "/" + std::to_string(date->tm_mon + 1) + "/" + std::to_string(date->tm_year + 1900)); @@ -126,7 +131,7 @@ std::string currentDate() { std::string currentTime() { const time_t t = time(nullptr); - if (const tm *date = localtime(&t)) + if (const tm* date = localtime(&t)) return std::string(std::to_string(date->tm_hour) + ":" + std::to_string(date->tm_min) + ":" + std::to_string(date->tm_sec)); @@ -137,7 +142,7 @@ std::pair runCommandWithOutput(const std::string_view cmd) { LOGN(HELPER, INFO) << "run command and catch out request: " << cmd << std::endl; - FILE *pipe = popen(cmd.data(), "r"); + FILE* pipe = popen(cmd.data(), "r"); if (!pipe) return {}; std::unique_ptr pipe_holder(pipe, pclose); @@ -148,7 +153,7 @@ std::pair runCommandWithOutput(const std::string_view cmd) { while (fgets(buffer, sizeof(buffer), pipe_holder.get()) != nullptr) output += buffer; - FILE *raw = pipe_holder.release(); + FILE* raw = pipe_holder.release(); const int status = pclose(raw); return {output, (WIFEXITED(status) ? WEXITSTATUS(status) : -1)}; } @@ -161,12 +166,12 @@ std::string pathJoin(std::string base, std::string relative) { } std::string pathBasename(const std::string_view entry) { - char *base = basename(const_cast(entry.data())); + char* base = basename(const_cast(entry.data())); return (base == nullptr) ? std::string() : std::string(base); } std::string pathDirname(const std::string_view entry) { - char *base = dirname(const_cast(entry.data())); + char* base = dirname(const_cast(entry.data())); return (base == nullptr) ? std::string() : std::string(base); } @@ -183,8 +188,8 @@ bool changeOwner(const std::string_view file, const uid_t uid, return chown(file.data(), uid, gid) == 0; } -int openAndAddToCloseList(const std::string_view &path, - garbageCollector &collector, const int flags, +int openAndAddToCloseList(const std::string_view& path, + garbageCollector& collector, const int flags, const mode_t mode) { const int fd = mode == 0 ? open(path.data(), flags) : open(path.data(), flags, mode); @@ -192,16 +197,16 @@ int openAndAddToCloseList(const std::string_view &path, return fd; } -FILE *openAndAddToCloseList(const std::string_view &path, - garbageCollector &collector, const char *mode) { - FILE *fp = fopen(path.data(), mode); +FILE* openAndAddToCloseList(const std::string_view& path, + garbageCollector& collector, const char* mode) { + FILE* fp = fopen(path.data(), mode); collector.closeAfterProgress(fp); return fp; } -DIR *openAndAddToCloseList(const std::string_view &path, - garbageCollector &collector) { - DIR *dp = opendir(path.data()); +DIR* openAndAddToCloseList(const std::string_view& path, + garbageCollector& collector) { + DIR* dp = opendir(path.data()); collector.closeAfterProgress(dp); return dp; } @@ -247,7 +252,7 @@ std::string multipleToString(const sizeCastTypes type) { return "B"; } -std::string format(const char *format, ...) { +std::string format(const char* format, ...) { va_list args; va_start(args, format); char str[1024]; @@ -257,4 +262,4 @@ std::string format(const char *format, ...) { } std::string getLibVersion() { MKVERSION("libhelper"); } -} // namespace Helper +} // namespace Helper diff --git a/srclib/libhelper/tests/test.cpp b/srclib/libhelper/tests/test.cpp index 8c58d91..2112fdf 100644 --- a/srclib/libhelper/tests/test.cpp +++ b/srclib/libhelper/tests/test.cpp @@ -19,14 +19,14 @@ #include #include -char *TEST_DIR = nullptr; +char* TEST_DIR = nullptr; -std::string test_path(const char *file) { +std::string test_path(const char* file) { std::string end = std::string(TEST_DIR) + "/" + file; return end; } -int main(int argc, char **argv) { +int main(int argc, char** argv) { if (argc < 2) return 2; TEST_DIR = argv[1]; @@ -51,11 +51,13 @@ int main(int argc, char **argv) { if (!Helper::writeFile("file.txt", "hello world")) throw Helper::Error("Cannot write \"hello world\" in 'file.txt'"); - else std::cout << "file.txt writed." << std::endl; + else + std::cout << "file.txt writed." << std::endl; if (const auto content = Helper::readFile("file.txt"); !content) throw Helper::Error("Cannot read 'file.txt'"); - else std::cout << "'file.txt': " << *content << std::endl; + else + std::cout << "'file.txt': " << *content << std::endl; std::cout << "Making directory 'dir2': " << std::boolalpha << Helper::makeDirectory(test_path("dir2")) << std::endl; @@ -80,7 +82,8 @@ int main(int argc, char **argv) { if (const auto sha256 = Helper::sha256Of(test_path("file2.txt")); !sha256) throw Helper::Error("Cannot get sha256 of 'file2.txt'"); - else std::cout << "SHA256 of 'file2.txt': " << *sha256 << std::endl; + else + std::cout << "SHA256 of 'file2.txt': " << *sha256 << std::endl; std::cout << "'file2.txt' and 'file2lnk.txt' same? (SHA256): " << std::boolalpha @@ -130,7 +133,7 @@ int main(int argc, char **argv) { std::cout << "pure tuple test: " << std::boolalpha << static_cast(values.at(0)) << std::endl; - for (const auto &[x, y, z] : values) { + for (const auto& [x, y, z] : values) { std::cout << std::boolalpha << "(" << x << ", " << y << ", " << z << ")" << std::endl; } @@ -141,7 +144,7 @@ int main(int argc, char **argv) { LOG(WARNING) << "Warning message" << std::endl; LOG(ERROR) << "Error message" << std::endl; LOG(ABORT) << "Abort message" << std::endl; - } catch (std::exception &err) { + } catch (std::exception& err) { std::cout << err.what() << std::endl; return 1; } diff --git a/srclib/libpartition_map/include/libpartition_map/lib.hpp b/srclib/libpartition_map/include/libpartition_map/lib.hpp index 2113f78..a60958d 100644 --- a/srclib/libpartition_map/include/libpartition_map/lib.hpp +++ b/srclib/libpartition_map/include/libpartition_map/lib.hpp @@ -17,7 +17,7 @@ #ifndef LIBPARTITION_MAP_LIB_HPP #define LIBPARTITION_MAP_LIB_HPP -#include // for uint64_t +#include // for uint64_t #include #include #include @@ -27,7 +27,7 @@ #include #include #include -#include // for std::pair +#include // for std::pair namespace PartitionMap { struct _entry { @@ -52,74 +52,73 @@ using Info = _entry; * to be easily manipulated and modified only on this class. */ class basic_partition_map { -private: + private: void _resize_map(); [[nodiscard]] int _index_of(std::string_view name) const; -public: - _entry *_data; + public: + _entry* _data; size_t _count{}, _capacity{}; - basic_partition_map(const std::string &name, uint64_t size, bool logical); - basic_partition_map(const basic_partition_map &other); - basic_partition_map(basic_partition_map &&other) noexcept; + basic_partition_map(const std::string& name, uint64_t size, bool logical); + basic_partition_map(const basic_partition_map& other); + basic_partition_map(basic_partition_map&& other) noexcept; basic_partition_map(); ~basic_partition_map(); - bool insert(const std::string &name, uint64_t size, bool logical); - void merge(const basic_partition_map &map); + bool insert(const std::string& name, uint64_t size, bool logical); + void merge(const basic_partition_map& map); void clear(); [[nodiscard]] uint64_t get_size(std::string_view name) const; [[nodiscard]] bool is_logical(std::string_view name) const; [[nodiscard]] _returnable_entry get_all(std::string_view name) const; [[nodiscard]] bool find(std::string_view name) const; - [[nodiscard]] std::string find_(const std::string &name) const; + [[nodiscard]] std::string find_(const std::string& name) const; [[nodiscard]] size_t size() const; [[nodiscard]] bool empty() const; - basic_partition_map &operator=(const basic_partition_map &map); + basic_partition_map& operator=(const basic_partition_map& map); - bool operator==(const basic_partition_map &other) const; - bool operator!=(const basic_partition_map &other) const; + bool operator==(const basic_partition_map& other) const; + bool operator!=(const basic_partition_map& other) const; bool operator!() const; explicit operator bool() const; Info operator[](int index) const; - BasicInf operator[](const std::string_view &name) const; + BasicInf operator[](const std::string_view& name) const; explicit operator std::vector() const; explicit operator int() const; class iterator { - public: - _entry *ptr; + public: + _entry* ptr; - explicit iterator(_entry *p); + explicit iterator(_entry* p); - auto operator*() const - -> std::pair; - _entry *operator->() const; - iterator &operator++(); + auto operator*() const -> std::pair; + _entry* operator->() const; + iterator& operator++(); iterator operator++(int); - bool operator!=(const iterator &other) const; - bool operator==(const iterator &other) const; + bool operator!=(const iterator& other) const; + bool operator==(const iterator& other) const; }; class constant_iterator { - public: - const _entry *ptr; + public: + const _entry* ptr; - explicit constant_iterator(const _entry *p); + explicit constant_iterator(const _entry* p); auto operator*() const - -> std::pair; - const _entry *operator->() const; - constant_iterator &operator++(); + -> std::pair; + const _entry* operator->() const; + constant_iterator& operator++(); constant_iterator operator++(int); - bool operator!=(const constant_iterator &other) const; - bool operator==(const constant_iterator &other) const; + bool operator!=(const constant_iterator& other) const; + bool operator==(const constant_iterator& other) const; }; /* for-each support */ @@ -133,20 +132,20 @@ using Partition_t = _entry; using Map_t = basic_partition_map; class basic_partition_map_builder final { -private: + private: Map_t _current_map; std::string _workdir; bool _any_generating_error, _map_builded; Map_t _build_map(std::string_view path, bool logical = false); - void _insert_logicals(Map_t &&logicals); + void _insert_logicals(Map_t&& logicals); void _map_build_check() const; [[nodiscard]] static bool _is_real_block_dir(std::string_view path); - [[nodiscard]] uint64_t _get_size(const std::string &path); + [[nodiscard]] uint64_t _get_size(const std::string& path); -public: + public: /** * By default, it searches the directories in the * defaultEntryList in PartitionMap.cpp in order and @@ -162,7 +161,7 @@ public: /** * Move constructor */ - basic_partition_map_builder(basic_partition_map_builder &&other) noexcept; + basic_partition_map_builder(basic_partition_map_builder&& other) noexcept; /** * Returns the current list content in Map_t type. @@ -174,8 +173,8 @@ public: * Map_temp_t type. If the partition is not in the * currently created list, returns std::nullopt. */ - [[nodiscard]] std::optional> - get(std::string_view name) const; + [[nodiscard]] std::optional> get( + std::string_view name) const; /** * If there is a logical partition(s) in the created @@ -183,16 +182,16 @@ public: * data of type std::string). If there is no logical * partition in the created list, it returns std::nullopt. */ - [[nodiscard]] std::optional> - getLogicalPartitionList() const; + [[nodiscard]] std::optional> getLogicalPartitionList() + const; /** * The physical partitions in the created list are * returned as std::list type. If there is no content * due to any problem, returns std::nullopt. */ - [[nodiscard]] std::optional> - getPhysicalPartitionList() const; + [[nodiscard]] std::optional> getPhysicalPartitionList() + const; /** * The partitions in the created list are returned as std::list @@ -244,17 +243,17 @@ public: /** * Copy partition list to vec, current vec contents are cleaned */ - bool copyPartitionsToVector(std::vector &vec) const; + bool copyPartitionsToVector(std::vector& vec) const; /** * Copy logical partition list to vec, current vec contents are cleaned */ - bool copyLogicalPartitionsToVector(std::vector &vec) const; + bool copyLogicalPartitionsToVector(std::vector& vec) const; /** * Copy physical partition list to vec, current vec contents are cleaned */ - bool copyPhysicalPartitionsToVector(std::vector &vec) const; + bool copyPhysicalPartitionsToVector(std::vector& vec) const; /** * The created list and the current search index name are cleared. @@ -265,26 +264,26 @@ public: * Do input function (lambda) for all partitions. */ bool doForAllPartitions( - const std::function &func) const; + const std::function& func) const; /** * Do input function (lambda) for physical partitions. */ bool doForPhysicalPartitions( - const std::function &func) const; + const std::function& func) const; /** * Do input function (lambda) for logical partitions. */ bool doForLogicalPartitions( - const std::function &func) const; + const std::function& func) const; /** * Do input function (lambda) for input partition list. */ bool doForPartitionList( - const std::vector &partitions, - const std::function &func) const; + const std::vector& partitions, + const std::function& func) const; /** * The entered path is defined as the new search @@ -317,14 +316,14 @@ public: * the same (checked only according to the partition * names), true is returned, otherwise false is returned */ - friend bool operator==(const basic_partition_map_builder &lhs, - const basic_partition_map_builder &rhs); + friend bool operator==(const basic_partition_map_builder& lhs, + const basic_partition_map_builder& rhs); /** * The opposite logic of the == operator. */ - friend bool operator!=(const basic_partition_map_builder &lhs, - const basic_partition_map_builder &rhs); + friend bool operator!=(const basic_partition_map_builder& lhs, + const basic_partition_map_builder& rhs); /** * You can check whether the object was created @@ -347,12 +346,12 @@ public: /** * Get Map_t object reference */ - Map_t &operator*(); + Map_t& operator*(); /** * Get constant Map_t object reference */ - const Map_t &operator*() const; + const Map_t& operator*() const; /** * Get Info structure with given index @@ -362,7 +361,7 @@ public: /** * Get BasicInfo structure with given index */ - BasicInf operator[](const std::string_view &name) const; + BasicInf operator[](const std::string_view& name) const; /** * Get map contents as vector (PartitionManager::Info type). @@ -402,7 +401,7 @@ constexpr uint64_t FAT16_FS = 0x3631544146; constexpr uint64_t FAT32_FS = 0x3233544146; constexpr uint64_t NTFS_FS = 0x5346544E; constexpr uint64_t MSDOS_FS = 0x4d44; -} // namespace FileSystemMagic +} // namespace FileSystemMagic namespace AndroidMagic { constexpr uint64_t BOOT_IMAGE = 0x2144494F52444E41; @@ -413,23 +412,23 @@ constexpr uint64_t VBMETA_IMAGE = 0x425641; constexpr uint64_t SUPER_IMAGE = 0x7265797573; constexpr uint64_t SPARSE_IMAGE = 0x3AFF26ED; constexpr uint64_t ELF = - 0x464C457F; // It makes more sense than between file systems + 0x464C457F; // It makes more sense than between file systems constexpr uint64_t RAW = 0x00000000; -} // namespace AndroidMagic +} // namespace AndroidMagic extern std::map FileSystemMagicMap; extern std::map AndroidMagicMap; extern std::map MagicMap; size_t getMagicLength(uint64_t magic); -bool hasMagic(uint64_t magic, ssize_t buf, const std::string &path); +bool hasMagic(uint64_t magic, ssize_t buf, const std::string& path); std::string formatMagic(uint64_t magic); -} // namespace Extras -} // namespace PartitionMap +} // namespace Extras +} // namespace PartitionMap #define MAP "libpartition_map" -#define COMMON_LAMBDA_PARAMS \ - (const std::string &partition, const PartitionMap::BasicInf props) +#define COMMON_LAMBDA_PARAMS \ + (const std::string& partition, const PartitionMap::BasicInf props) -#endif // #ifndef LIBPARTITION_MAP_LIB_HPP +#endif // #ifndef LIBPARTITION_MAP_LIB_HPP diff --git a/srclib/libpartition_map/src/Getters.cpp b/srclib/libpartition_map/src/Getters.cpp index 8a9cfd9..0e87ca7 100644 --- a/srclib/libpartition_map/src/Getters.cpp +++ b/srclib/libpartition_map/src/Getters.cpp @@ -25,8 +25,8 @@ Map_t basic_partition_map_builder::getAll() const { return _current_map; } -std::optional> -basic_partition_map_builder::get(const std::string_view name) const { +std::optional> basic_partition_map_builder::get( + const std::string_view name) const { _map_build_check(); if (!_current_map.find(name)) return std::nullopt; @@ -39,7 +39,7 @@ basic_partition_map_builder::getLogicalPartitionList() const { _map_build_check(); std::list logicals; - for (const auto &[name, props] : _current_map) + for (const auto& [name, props] : _current_map) if (props.isLogical) logicals.push_back(name); if (logicals.empty()) return std::nullopt; @@ -51,7 +51,7 @@ basic_partition_map_builder::getPhysicalPartitionList() const { _map_build_check(); std::list physicals; - for (const auto &[name, props] : _current_map) + for (const auto& [name, props] : _current_map) if (!props.isLogical) physicals.push_back(name); if (physicals.empty()) return std::nullopt; @@ -63,8 +63,7 @@ basic_partition_map_builder::getPartitionList() const { _map_build_check(); std::list partitions; - for (const auto &[name, props] : _current_map) - partitions.push_back(name); + for (const auto& [name, props] : _current_map) partitions.push_back(name); if (partitions.empty()) return std::nullopt; return partitions; @@ -78,8 +77,8 @@ std::string basic_partition_map_builder::getRealLinkPathOf( return std::string(_workdir + "/" + name.data()); } -std::string -basic_partition_map_builder::getRealPathOf(const std::string_view name) const { +std::string basic_partition_map_builder::getRealPathOf( + const std::string_view name) const { _map_build_check(); const std::string full = (isLogical(name)) @@ -93,4 +92,4 @@ basic_partition_map_builder::getRealPathOf(const std::string_view name) const { std::string basic_partition_map_builder::getCurrentWorkDir() const { return _workdir; } -} // namespace PartitionMap +} // namespace PartitionMap diff --git a/srclib/libpartition_map/src/Magic.cpp b/srclib/libpartition_map/src/Magic.cpp index d0e5a68..164e2c3 100644 --- a/srclib/libpartition_map/src/Magic.cpp +++ b/srclib/libpartition_map/src/Magic.cpp @@ -15,12 +15,13 @@ */ #include +#include + #include #include #include #include #include -#include #include "PartitionManager/PartitionManager.hpp" @@ -76,7 +77,7 @@ size_t getMagicLength(const uint64_t magic) { } bool hasMagic(const uint64_t magic, const ssize_t buf, - const std::string &path) { + const std::string& path) { LOGN(MAP, INFO) << "Checking magic of " << path << " with using " << buf << " byte buffer size (has magic 0x" << std::hex << magic << "?)" << std::endl; @@ -89,7 +90,7 @@ bool hasMagic(const uint64_t magic, const ssize_t buf, return false; } - auto *buffer = new (std::nothrow) uint8_t[buf]; + auto* buffer = new (std::nothrow) uint8_t[buf]; collector.delAfterProgress(buffer); const ssize_t bytesRead = read(fd, buffer, buf); @@ -120,4 +121,4 @@ std::string formatMagic(const uint64_t magic) { << magic; return ss.str(); } -} // namespace PartitionMap::Extras +} // namespace PartitionMap::Extras diff --git a/srclib/libpartition_map/src/PartitionMap.cpp b/srclib/libpartition_map/src/PartitionMap.cpp index 1d5e68b..0454937 100644 --- a/srclib/libpartition_map/src/PartitionMap.cpp +++ b/srclib/libpartition_map/src/PartitionMap.cpp @@ -14,24 +14,26 @@ limitations under the License. */ +#include + #include #include #include #include -#include #include #ifndef ANDROID_BUILD #include #endif -#include -#include #include -#include -#include -#include #include #include #include + +#include +#include +#include +#include +#include #include static constexpr std::array defaultEntryList = { @@ -60,7 +62,7 @@ Map_t basic_partition_map_builder::_build_map(std::string_view path, std::vector entries{ std::filesystem::directory_iterator(path), std::filesystem::directory_iterator()}; - std::sort(entries.begin(), entries.end(), [](const auto &a, const auto &b) { + std::sort(entries.begin(), entries.end(), [](const auto& a, const auto& b) { return a.path().filename() < b.path().filename(); }); @@ -69,7 +71,7 @@ Map_t basic_partition_map_builder::_build_map(std::string_view path, << " is exists but generated vector is empty " "(std::vector)." << std::endl; - for (const auto &entry : entries) { + for (const auto& entry : entries) { if (entry.path().filename() != "by-uuid" && std::string(entry.path()).find("com.") == std::string::npos) map.insert(entry.path().filename().string(), _get_size(entry.path()), @@ -82,7 +84,7 @@ Map_t basic_partition_map_builder::_build_map(std::string_view path, return map; } -void basic_partition_map_builder::_insert_logicals(Map_t &&logicals) { +void basic_partition_map_builder::_insert_logicals(Map_t&& logicals) { LOGN(MAP, INFO) << "merging created logical partition list to this object's variable." << std::endl; @@ -96,7 +98,7 @@ void basic_partition_map_builder::_map_build_check() const { if (!_map_builded) throw Error("Please build partition map before!"); } -uint64_t basic_partition_map_builder::_get_size(const std::string &path) { +uint64_t basic_partition_map_builder::_get_size(const std::string& path) { const std::string real = std::filesystem::read_symlink(path); Helper::garbageCollector collector; @@ -120,7 +122,7 @@ uint64_t basic_partition_map_builder::_get_size(const std::string &path) { basic_partition_map_builder::basic_partition_map_builder() { LOGN(MAP, INFO) << "default constructor called. Starting build." << std::endl; - for (const auto &path : defaultEntryList) { + for (const auto& path : defaultEntryList) { if (std::filesystem::exists(path)) { _current_map = _build_map(path); if (_current_map.empty()) { @@ -149,8 +151,10 @@ basic_partition_map_builder::basic_partition_map_builder( if (std::filesystem::exists(path)) { if (!_is_real_block_dir(path)) return; _current_map = _build_map(path); - if (_current_map.empty()) _any_generating_error = true; - else _workdir = path; + if (_current_map.empty()) + _any_generating_error = true; + else + _workdir = path; } else throw Error("Cannot find directory: %s. Cannot build partition map!", path.data()); @@ -162,7 +166,7 @@ basic_partition_map_builder::basic_partition_map_builder( } basic_partition_map_builder::basic_partition_map_builder( - basic_partition_map_builder &&other) noexcept { + basic_partition_map_builder&& other) noexcept { _current_map = Map_t(std::move(other._current_map)); _workdir = std::move(other._workdir); _any_generating_error = other._any_generating_error; @@ -178,7 +182,7 @@ bool basic_partition_map_builder::hasPartition( bool basic_partition_map_builder::hasLogicalPartitions() const { _map_build_check(); - for (const auto &[name, props] : _current_map) + for (const auto& [name, props] : _current_map) if (props.isLogical) return true; return false; @@ -205,7 +209,8 @@ bool basic_partition_map_builder::readDirectory(const std::string_view path) { if (_current_map.empty()) { _any_generating_error = true; return false; - } else _workdir = path; + } else + _workdir = path; } else throw Error("Cannot find directory: %s. Cannot build partition map!", path.data()); @@ -220,7 +225,7 @@ bool basic_partition_map_builder::readDefaultDirectories() { _map_builded = false; LOGN(MAP, INFO) << "read default directories request." << std::endl; - for (const auto &path : defaultEntryList) { + for (const auto& path : defaultEntryList) { if (std::filesystem::exists(path)) { _current_map = _build_map(path); if (_current_map.empty()) { @@ -244,48 +249,49 @@ bool basic_partition_map_builder::readDefaultDirectories() { } bool basic_partition_map_builder::copyPartitionsToVector( - std::vector &vec) const { + std::vector& vec) const { if (_current_map.empty()) { LOGN(MAP, ERROR) << "Current map is empty."; return false; } vec.clear(); - for (const auto &[name, props] : _current_map) - vec.push_back(name); + for (const auto& [name, props] : _current_map) vec.push_back(name); return true; } bool basic_partition_map_builder::copyLogicalPartitionsToVector( - std::vector &vec) const { + std::vector& vec) const { if (_current_map.empty()) { LOGN(MAP, ERROR) << "Current map is empty."; return false; } std::vector vec2; - for (const auto &[name, props] : _current_map) + for (const auto& [name, props] : _current_map) if (props.isLogical) vec2.push_back(name); if (vec2.empty()) { LOGN(MAP, ERROR) << "Cannot find logical partitions in current map."; return false; - } else vec = vec2; + } else + vec = vec2; return true; } bool basic_partition_map_builder::copyPhysicalPartitionsToVector( - std::vector &vec) const { + std::vector& vec) const { if (_current_map.empty()) { LOGN(MAP, ERROR) << "Current map is empty."; return false; } std::vector vec2; - for (const auto &[name, props] : _current_map) + for (const auto& [name, props] : _current_map) if (!props.isLogical) vec2.push_back(name); if (vec2.empty()) { LOGN(MAP, ERROR) << "Cannot find physical partitions in current map."; return false; - } else vec = vec2; + } else + vec = vec2; return true; } @@ -295,12 +301,12 @@ bool basic_partition_map_builder::empty() const { } bool basic_partition_map_builder::doForAllPartitions( - const std::function &func) const { + const std::function& func) const { _map_build_check(); bool err = false; LOGN(MAP, INFO) << "Doing input function for all partitions." << std::endl; - for (const auto &[name, props] : _current_map) { + for (const auto& [name, props] : _current_map) { if (func(name, {props.size, props.isLogical})) LOGN(MAP, INFO) << "Done progress for " << name << " partition." << std::endl; @@ -315,13 +321,13 @@ bool basic_partition_map_builder::doForAllPartitions( } bool basic_partition_map_builder::doForPhysicalPartitions( - const std::function &func) const { + const std::function& func) const { _map_build_check(); bool err = false; LOGN(MAP, INFO) << "Doing input function for physical partitions." << std::endl; - for (const auto &[name, props] : _current_map) { + for (const auto& [name, props] : _current_map) { if (props.isLogical) continue; if (func(name, {props.size, props.isLogical})) LOGN(MAP, INFO) << "Done progress for " << name << " partition." @@ -337,13 +343,13 @@ bool basic_partition_map_builder::doForPhysicalPartitions( } bool basic_partition_map_builder::doForLogicalPartitions( - const std::function &func) const { + const std::function& func) const { _map_build_check(); bool err = false; LOGN(MAP, INFO) << "Doing input function for logical partitions." << std::endl; - for (const auto &[name, props] : _current_map) { + for (const auto& [name, props] : _current_map) { if (!props.isLogical) continue; if (func(name, {props.size, props.isLogical})) LOGN(MAP, INFO) << "Done progress for " << name << " partition." @@ -359,14 +365,14 @@ bool basic_partition_map_builder::doForLogicalPartitions( } bool basic_partition_map_builder::doForPartitionList( - const std::vector &partitions, - const std::function &func) const { + const std::vector& partitions, + const std::function& func) const { _map_build_check(); bool err = false; LOGN(MAP, INFO) << "Doing input function for input partition list." << std::endl; - for (const auto &partition : partitions) { + for (const auto& partition : partitions) { if (!hasPartition(partition)) throw Error("Couldn't find partition: %s", partition.data()); if (!func(partition, _current_map[partition])) { @@ -379,19 +385,19 @@ bool basic_partition_map_builder::doForPartitionList( return err; } -uint64_t -basic_partition_map_builder::sizeOf(const std::string_view name) const { +uint64_t basic_partition_map_builder::sizeOf( + const std::string_view name) const { _map_build_check(); return _current_map.get_size(name); } -bool operator==(const basic_partition_map_builder &lhs, - const basic_partition_map_builder &rhs) { +bool operator==(const basic_partition_map_builder& lhs, + const basic_partition_map_builder& rhs) { return lhs._current_map == rhs._current_map; } -bool operator!=(const basic_partition_map_builder &lhs, - const basic_partition_map_builder &rhs) { +bool operator!=(const basic_partition_map_builder& lhs, + const basic_partition_map_builder& rhs) { return !(lhs == rhs); } @@ -409,9 +415,9 @@ bool basic_partition_map_builder::operator()(const std::string_view path) { return readDirectory(path); } -Map_t &basic_partition_map_builder::operator*() { return _current_map; } +Map_t& basic_partition_map_builder::operator*() { return _current_map; } -const Map_t &basic_partition_map_builder::operator*() const { +const Map_t& basic_partition_map_builder::operator*() const { return _current_map; } @@ -419,8 +425,8 @@ Info basic_partition_map_builder::operator[](const int index) const { return _current_map[index]; } -BasicInf -basic_partition_map_builder::operator[](const std::string_view &name) const { +BasicInf basic_partition_map_builder::operator[]( + const std::string_view& name) const { return _current_map[name]; } @@ -435,4 +441,4 @@ basic_partition_map_builder::operator int() const { basic_partition_map_builder::operator std::string() const { return _workdir; } std::string getLibVersion() { MKVERSION("libpartition_map"); } -} // namespace PartitionMap +} // namespace PartitionMap diff --git a/srclib/libpartition_map/src/Type.cpp b/srclib/libpartition_map/src/Type.cpp index d893846..67c2ba2 100644 --- a/srclib/libpartition_map/src/Type.cpp +++ b/srclib/libpartition_map/src/Type.cpp @@ -20,16 +20,16 @@ #include namespace PartitionMap { -basic_partition_map::iterator::iterator(_entry *p) : ptr(p) {} +basic_partition_map::iterator::iterator(_entry* p) : ptr(p) {} auto basic_partition_map::iterator::operator*() const - -> std::pair { + -> std::pair { return {ptr->name, ptr->props}; } -_entry *basic_partition_map::iterator::operator->() const { return ptr; } +_entry* basic_partition_map::iterator::operator->() const { return ptr; } -basic_partition_map::iterator &basic_partition_map::iterator::operator++() { +basic_partition_map::iterator& basic_partition_map::iterator::operator++() { ++ptr; return *this; } @@ -40,27 +40,27 @@ basic_partition_map::iterator basic_partition_map::iterator::operator++(int) { return tmp; } -bool basic_partition_map::iterator::operator==(const iterator &other) const { +bool basic_partition_map::iterator::operator==(const iterator& other) const { return ptr == other.ptr; } -bool basic_partition_map::iterator::operator!=(const iterator &other) const { +bool basic_partition_map::iterator::operator!=(const iterator& other) const { return ptr != other.ptr; } -basic_partition_map::constant_iterator::constant_iterator(const _entry *p) +basic_partition_map::constant_iterator::constant_iterator(const _entry* p) : ptr(p) {} auto basic_partition_map::constant_iterator::operator*() const - -> std::pair { + -> std::pair { return {ptr->name, ptr->props}; } -const _entry *basic_partition_map::constant_iterator::operator->() const { +const _entry* basic_partition_map::constant_iterator::operator->() const { return ptr; } -basic_partition_map::constant_iterator & +basic_partition_map::constant_iterator& basic_partition_map::constant_iterator::operator++() { ++ptr; return *this; @@ -74,21 +74,20 @@ basic_partition_map::constant_iterator::operator++(int) { } bool basic_partition_map::constant_iterator::operator==( - const constant_iterator &other) const { + const constant_iterator& other) const { return ptr == other.ptr; } bool basic_partition_map::constant_iterator::operator!=( - const constant_iterator &other) const { + const constant_iterator& other) const { return ptr != other.ptr; } void basic_partition_map::_resize_map() { const size_t new_capacity = _capacity * 2; - auto *new_data = new _entry[new_capacity]; + auto* new_data = new _entry[new_capacity]; - for (size_t i = 0; i < _count; i++) - new_data[i] = _data[i]; + for (size_t i = 0; i < _count; i++) new_data[i] = _data[i]; delete[] _data; _data = new_data; @@ -103,21 +102,23 @@ int basic_partition_map::_index_of(const std::string_view name) const { return 0; } -basic_partition_map::basic_partition_map(const std::string &name, +basic_partition_map::basic_partition_map(const std::string& name, const uint64_t size, const bool logical) { _data = new _entry[_capacity]; insert(name, size, logical); } -basic_partition_map::basic_partition_map(const basic_partition_map &other) - : _data(new _entry[other._capacity]), _count(other._count), +basic_partition_map::basic_partition_map(const basic_partition_map& other) + : _data(new _entry[other._capacity]), + _count(other._count), _capacity(other._capacity) { std::copy(other._data, other._data + _count, _data); } -basic_partition_map::basic_partition_map(basic_partition_map &&other) noexcept - : _data(new _entry[other._capacity]), _count(other._count), +basic_partition_map::basic_partition_map(basic_partition_map&& other) noexcept + : _data(new _entry[other._capacity]), + _count(other._count), _capacity(other._capacity) { std::copy(other._data, other._data + _count, _data); other.clear(); @@ -129,7 +130,7 @@ basic_partition_map::basic_partition_map() : _capacity(6) { basic_partition_map::~basic_partition_map() { delete[] _data; } -bool basic_partition_map::insert(const std::string &name, const uint64_t size, +bool basic_partition_map::insert(const std::string& name, const uint64_t size, const bool logical) { if (name == _data[_index_of(name)].name) return false; if (_count == _capacity) _resize_map(); @@ -141,9 +142,9 @@ bool basic_partition_map::insert(const std::string &name, const uint64_t size, return true; } -void basic_partition_map::merge(const basic_partition_map &map) { +void basic_partition_map::merge(const basic_partition_map& map) { LOGN(MAP, INFO) << "map merge request." << std::endl; - for (const auto &[name, props] : map) + for (const auto& [name, props] : map) insert(name, props.size, props.isLogical); LOGN(MAP, INFO) << "map merged successfully." << std::endl; } @@ -162,8 +163,8 @@ bool basic_partition_map::is_logical(const std::string_view name) const { return false; } -_returnable_entry -basic_partition_map::get_all(const std::string_view name) const { +_returnable_entry basic_partition_map::get_all( + const std::string_view name) const { if (const int pos = _index_of(name); name == _data[pos].name) return _returnable_entry{_data[pos].props.size, _data[pos].props.isLogical}; @@ -176,7 +177,7 @@ bool basic_partition_map::find(const std::string_view name) const { return false; } -std::string basic_partition_map::find_(const std::string &name) const { +std::string basic_partition_map::find_(const std::string& name) const { if (name == _data[_index_of(name)].name) return name; return {}; @@ -194,8 +195,8 @@ void basic_partition_map::clear() { _data = new _entry[_capacity]; } -basic_partition_map & -basic_partition_map::operator=(const basic_partition_map &map) { +basic_partition_map& basic_partition_map::operator=( + const basic_partition_map& map) { if (this != &map) { delete[] _data; @@ -208,7 +209,7 @@ basic_partition_map::operator=(const basic_partition_map &map) { return *this; } -bool basic_partition_map::operator==(const basic_partition_map &other) const { +bool basic_partition_map::operator==(const basic_partition_map& other) const { if (this->_capacity != other._capacity || this->_count != other._count) return false; @@ -217,12 +218,13 @@ bool basic_partition_map::operator==(const basic_partition_map &other) const { _data[i].props.size == other._data[i].props.size && _data[i].props.isLogical == other._data[i].props.isLogical) continue; - else return false; + else + return false; return true; } -bool basic_partition_map::operator!=(const basic_partition_map &other) const { +bool basic_partition_map::operator!=(const basic_partition_map& other) const { return !(*this == other); } @@ -235,7 +237,7 @@ Info basic_partition_map::operator[](const int index) const { return _data[index]; } -BasicInf basic_partition_map::operator[](const std::string_view &name) const { +BasicInf basic_partition_map::operator[](const std::string_view& name) const { if (_count == 0) return {}; if (const int i = _index_of(name); name == _data[i].name) @@ -270,4 +272,4 @@ basic_partition_map::constant_iterator basic_partition_map::cbegin() const { basic_partition_map::constant_iterator basic_partition_map::cend() const { return constant_iterator(_data + _count); } -} // namespace PartitionMap +} // namespace PartitionMap diff --git a/srclib/libpartition_map/tests/test.cpp b/srclib/libpartition_map/tests/test.cpp index d4e7326..ec558e7 100644 --- a/srclib/libpartition_map/tests/test.cpp +++ b/srclib/libpartition_map/tests/test.cpp @@ -14,10 +14,11 @@ limitations under the License. */ +#include + #include #include #include -#include int main() { if (getuid() != 0) return 2; @@ -31,7 +32,7 @@ int main() { const auto map = MyMap.getAll(); if (map.empty()) throw PartitionMap::Error("getAll() empty"); - for (const auto &[name, props] : map) { + for (const auto& [name, props] : map) { std::cout << "Partition: " << name << ", size: " << props.size << ", logical: " << props.isLogical << std::endl; } @@ -45,14 +46,14 @@ int main() { if (!logicals) throw PartitionMap::Error("getLogicalPartitionList() returned nullopt"); std::cout << "Logical partitions: " << std::endl; - for (const auto &name : *logicals) + for (const auto& name : *logicals) std::cout << " - " << name << std::endl; const auto physicals = MyMap.getPhysicalPartitionList(); if (!physicals) throw PartitionMap::Error("getPhysicalPartitionList() returned nullopt"); std::cout << "Physical partitions: " << std::endl; - for (const auto &name : *physicals) + for (const auto& name : *physicals) std::cout << " - " << name << std::endl; if (const std::vector parts = @@ -61,7 +62,7 @@ int main() { throw PartitionMap::Error( "operator std::vector() returned empty vector"); - auto func = [](const std::string &partition, + auto func = [](const std::string& partition, const PartitionMap::BasicInf props) -> bool { std::ofstream f("parts.txt"); f << "Partition: " << partition << ", size: " << props.size @@ -96,10 +97,10 @@ int main() { if (MyMap != MyMap2) std::cout << "map1 != map2" << std::endl; std::cout << PartitionMap::getLibVersion() << std::endl; - } catch (PartitionMap::Error &error) { + } catch (PartitionMap::Error& error) { std::cerr << error.what() << std::endl; return 1; - } catch (std::ios_base::failure &error) { + } catch (std::ios_base::failure& error) { std::cerr << "fstream error: " << error.what() << std::endl; return 1; }