pmt: reformat code, etc.

This commit is contained in:
2025-11-24 18:50:57 +03:00
parent 579b2623a4
commit 11d75e401e
30 changed files with 755 additions and 647 deletions

View File

@@ -17,8 +17,9 @@
#ifndef LIBHELPER_LIB_HPP
#define LIBHELPER_LIB_HPP
#include <cstdint>
#include <dirent.h>
#include <cstdint>
#include <exception>
#include <functional>
#include <optional>
@@ -29,13 +30,13 @@
#include <string_view>
#include <vector>
#define KB(x) (static_cast<uint64_t>(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<uint64_t>(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 <typename T> Logger &operator<<(const T &msg) {
template <typename T>
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<std::function<void()>> _cleaners;
std::vector<FILE *> _fps;
std::vector<DIR *> _dps;
std::vector<FILE*> _fps;
std::vector<DIR*> _dps;
std::vector<int> _fds;
std::vector<std::string> _files;
public:
public:
~garbageCollector();
template <typename T> void delAfterProgress(T *_ptr) {
template <typename T>
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<int> get() {
std::set<int> 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 <typename _Type1, typename _Type2, typename _Type3> class PureTuple {
private:
template <typename _Type1, typename _Type2, typename _Type3>
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<Data> 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 <typename T = std::tuple<_Type1, _Type2, _Type3>>
std::enable_if_t<std::is_same_v<T, std::tuple<_Type1, _Type2, _Type3>>, 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 <typename T = std::tuple<_Type1, _Type2, _Type3>>
std::enable_if_t<std::is_same_v<T, std::tuple<_Type1, _Type2, _Type3>>, 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 <typename T = std::tuple<_Type1, _Type2, _Type3>>
std::enable_if_t<std::is_same_v<T, std::tuple<_Type1, _Type2, _Type3>>, 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 <typename _Type> class Capsule : public garbageCollector {
public:
_Type &value;
template <typename _Type>
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 <int state> void setPrinting() {
if (state == 1 || state == 0) PRINT = state;
else PRINT = NO;
template <int state>
void setPrinting() {
if (state == 1 || state == 0)
PRINT = state;
else
PRINT = NO;
}
template <int state> void setLoggingState() {
if (state == 1 || state == 0) DISABLE = state;
else DISABLE = NO;
template <int state>
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 <uint64_t size> int convertTo(const sizeCastTypes type) {
template <uint64_t size>
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

View File

@@ -14,13 +14,14 @@
limitations under the License.
*/
#include <cstdio>
#include <cstdlib>
#include <libhelper/lib.hpp>
#include <private/android_filesystem_config.h>
#include <sys/stat.h>
#include <unistd.h>
#include <cstdio>
#include <cstdlib>
#include <libhelper/lib.hpp>
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

View File

@@ -14,22 +14,23 @@
limitations under the License.
*/
#include <dirent.h>
#include <fcntl.h>
#include <libgen.h>
#include <unistd.h>
#include <cerrno>
#include <cstdarg>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <dirent.h>
#include <exception>
#include <fcntl.h>
#include <functional>
#include <libgen.h>
#include <libhelper/lib.hpp>
#include <sstream>
#include <unistd.h>
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> [ <prog %s> <on %s:%d> %s %s] %s(): %s",
static_cast<char>(_level), _program_name,
basename(const_cast<char *>(_file)), _line, currentDate().data(),
basename(const_cast<char*>(_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

View File

@@ -14,16 +14,17 @@
limitations under the License.
*/
#include <dirent.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <cerrno>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <dirent.h>
#include <fcntl.h>
#include <libhelper/lib.hpp>
#include <string>
#include <sys/stat.h>
#include <unistd.h>
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<std::string> 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

View File

@@ -14,13 +14,14 @@
limitations under the License.
*/
#include <picosha2.h>
#include <sys/stat.h>
#include <fstream>
#include <iostream>
#include <libhelper/lib.hpp>
#include <optional>
#include <picosha2.h>
#include <string>
#include <sys/stat.h>
#include <vector>
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

View File

@@ -14,52 +14,57 @@
limitations under the License.
*/
#include <cutils/android_reboot.h>
#include <fcntl.h>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <cutils/android_reboot.h>
#include <fcntl.h>
#ifndef ANDROID_BUILD
#include <generated/buildInfo.hpp>
#include <sys/_system_properties.h>
#include <generated/buildInfo.hpp>
#else
#include <sys/system_properties.h>
#endif
#include <cstdarg>
#include <cutils/android_reboot.h>
#include <iostream>
#include <libgen.h>
#include <libhelper/lib.hpp>
#include <memory>
#include <string>
#include <string_view>
#include <sys/_system_properties.h>
#include <sys/stat.h>
#include <unistd.h>
#include <cstdarg>
#include <iostream>
#include <libhelper/lib.hpp>
#include <memory>
#include <string>
#include <string_view>
#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<std::string, int> 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<FILE, decltype(&pclose)> pipe_holder(pipe, pclose);
@@ -148,7 +153,7 @@ std::pair<std::string, int> 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<char *>(entry.data()));
char* base = basename(const_cast<char*>(entry.data()));
return (base == nullptr) ? std::string() : std::string(base);
}
std::string pathDirname(const std::string_view entry) {
char *base = dirname(const_cast<char *>(entry.data()));
char* base = dirname(const_cast<char*>(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

View File

@@ -19,14 +19,14 @@
#include <iostream>
#include <libhelper/lib.hpp>
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<bool>(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;
}