86 lines
2.0 KiB
C++
86 lines
2.0 KiB
C++
#include <cstdlib>
|
|
#include <stdio.h>
|
|
#include <errno.h>
|
|
#include <cstring>
|
|
#include <limits.h>
|
|
#include <stdint.h>
|
|
|
|
/**
|
|
* @brief Convert a given string to an unsigned 64 bit integer
|
|
*
|
|
* @param str Input string to convert
|
|
* @param n Integer output
|
|
* @return EXIT_SUCCESS if succesful otherwise EXIT_FAILURE
|
|
*/
|
|
int32_t sstrtoull(const char* str, uint64_t& n) noexcept {
|
|
errno = 0;
|
|
char* endptr = nullptr;
|
|
const uint64_t a = strtoull(str, &endptr, 10);
|
|
|
|
switch(errno){
|
|
case 0:
|
|
n = a;
|
|
return EXIT_SUCCESS;
|
|
case ERANGE:
|
|
fprintf(stderr, "Error while converting to integer : numerical result out of range (");
|
|
if(a == 0)
|
|
fprintf(stderr, "underflow occurred");
|
|
else if(a == ULLONG_MAX)
|
|
fprintf(stderr, "overflow occurred");
|
|
else
|
|
fprintf(stderr, "unspecified");
|
|
fprintf(stderr, ")\n");
|
|
return EXIT_FAILURE;
|
|
default:
|
|
fprintf(stderr, "Unspecified error occurred while converting to integer: %s\n", strerror(errno));
|
|
return EXIT_FAILURE;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @brief Swap two given memory values
|
|
*
|
|
* @tparam T Type of memory placeholder
|
|
* @param a Firat memory pointer
|
|
* @param b Second memory pointer
|
|
*/
|
|
template<typename T>
|
|
inline void swap(T* const a, T* const b) noexcept {
|
|
const T temp = *a;
|
|
*a = *b;
|
|
*b = temp;
|
|
|
|
}
|
|
|
|
/**
|
|
* @brief Convert a given number to string
|
|
*
|
|
* @param num Number to convert
|
|
* @param offset of the string location to append
|
|
* @param str String to append the number to
|
|
* @return number of written bytes
|
|
*/
|
|
size_t ullstr(uint64_t num, const size_t offset, char* const str) noexcept {
|
|
size_t i = 0;
|
|
|
|
for (; num > 0; num /= 10)
|
|
str[offset + i++] = num % 10 + '0';
|
|
|
|
str[offset + i] = '\0';
|
|
|
|
for (size_t j = 0; j < i / 2; ++j)
|
|
swap(str + offset + j, str + offset + i - j - 1);
|
|
return i;
|
|
}
|
|
|
|
/**
|
|
* @brief Convert a given number to string
|
|
*
|
|
* @param num Number to convert
|
|
* @param str String to append the number to
|
|
* @return number of written bytes
|
|
*/
|
|
size_t ullstr(uint64_t num, char* const str) noexcept {
|
|
return ullstr(num, 0, str);
|
|
}
|