looper/util.hpp
2024-09-06 10:06:32 -07:00

89 lines
2.4 KiB
C++

#pragma once
#include <string>
#include <string.h>
#include <stddef.h>
#include <stdint.h>
#include <cmath>
#include <vector>
#include <stdarg.h>
std::string PadZeros(std::string input, size_t required_length);
uint8_t TimeToComponentCount(double time_code);
std::string TimeToString(double time_code, uint8_t min_components = 1);
std::string get_prefs_path();
inline const char *vcformat(const char *format, va_list args) {
va_list args_copy;
va_copy(args_copy, args);
char *buf;
size_t buflen = 0;
buflen = vsnprintf(NULL, 0, format, args_copy) + 1;
va_end(args_copy);
buf = (char*)malloc(buflen);
if (buf == NULL) {
return NULL;
}
memset(buf, 0, buflen);
buflen = vsnprintf(buf, buflen, format, args) + 1;
return buf;
}
inline const char *cformat(const char *format, ...) {
va_list args;
va_start(args, format);
const char *output = vcformat(format, args);
va_end(args);
return output;
}
inline std::string to_string_with_decimals(double value, unsigned decimals) {
std::string num_text;
if (value == 0) {
num_text = "0";
} else {
size_t buflen = snprintf(NULL, 0, "%f", value);
buflen++;
char *buf = (char*)malloc(buflen);
memset(buf, 0, buflen);
snprintf(buf, buflen - 1, "%f", value);
num_text = std::string(buf);
free(buf);
}
int found = num_text.find(".");
if (found == -1) {
found = num_text.size();
num_text.append(".0");
}
if (num_text[0] == '.') {
num_text = "0" + num_text;
found++;
}
if (decimals == 0) {
num_text = num_text.substr(0, found);
return num_text;
}
int chars_after_decimal = num_text.size() - found - 1;
if (chars_after_decimal > decimals) {
num_text = num_text.substr(0, found + decimals + 1);
} else {
for (int i = chars_after_decimal; i < decimals; i++) {
num_text.push_back('0');
}
}
return num_text;
}
inline size_t combine_hashes(std::initializer_list<size_t> hashes) {
std::string values = "^";
values += hashes.size();
values += "@";
for (auto value : values) {
values += value;
values += ";";
}
return std::hash<std::string>()(values);
}
int launch(std::vector<std::string> args);
#ifdef MIN
#undef MIN
#endif
#define MIN(x, y) ((x < y) ? x : y)
#ifdef MAX
#undef MAX
#endif
#define MAX(x, y) ((x > y) ? x : y)