A tool for adding anime to your anidb list.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

89 lines
2.1KB

  1. #define _XOPEN_SOURCE
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <time.h>
  5. #include "util.h"
  6. void util_byte2hex(const uint8_t* bytes, size_t bytes_len,
  7. bool uppercase, char* out)
  8. {
  9. const char* hex = (uppercase) ? "0123456789ABCDEF" : "0123456789abcdef";
  10. for (size_t i = 0; i < bytes_len; i++) {
  11. *out++ = hex[bytes[i] >> 4];
  12. *out++ = hex[bytes[i] & 0xF];
  13. }
  14. *out = '\0';
  15. }
  16. void util_hex2byte(const char *str, uint8_t* out_bytes)
  17. {
  18. while (*str) {
  19. if (*str >= '0' && *str <= '9')
  20. *out_bytes = (*str - '0') << 4;
  21. if (*str >= 'A' && *str <= 'F')
  22. *out_bytes = (*str - ('A' - 10)) << 4;
  23. else
  24. *out_bytes = (*str - ('a' - 10)) << 4;
  25. str++;
  26. if (*str >= '0' && *str <= '9')
  27. *out_bytes |= (*str - '0');
  28. if (*str >= 'A' && *str <= 'F')
  29. *out_bytes |= (*str - ('A' - 10));
  30. else
  31. *out_bytes |= (*str - ('a' - 10));
  32. out_bytes++;
  33. str++;
  34. }
  35. }
  36. const char *util_get_home()
  37. {
  38. const char *home_env = getenv("HOME");
  39. return home_env; /* TODO this can be null, use other methods as fallback */
  40. }
  41. char *util_basename(const char *fullpath)
  42. {
  43. char *name_part = strrchr(fullpath, '/');
  44. if (name_part)
  45. name_part++;
  46. else
  47. name_part = (char*)fullpath;
  48. return name_part;
  49. }
  50. uint64_t util_timespec_diff(const struct timespec *past,
  51. const struct timespec *future)
  52. {
  53. int64_t sdiff = future->tv_sec - past->tv_sec;
  54. int64_t nsdiff = future->tv_nsec - past->tv_nsec;
  55. return sdiff * 1000 + (nsdiff / 1000000);
  56. }
  57. uint64_t util_iso2unix(const char *isotime)
  58. {
  59. struct tm tm = {0};
  60. char *ms = strptime(isotime, "%Y-%m-%d", &tm);
  61. if (!ms || (*ms != '\0' && *ms != ' ' && *ms != 'T'))
  62. return 0;
  63. if (*ms == '\0')
  64. ms = "T00:00:00";
  65. ms = strptime(ms + 1, "%H:%M", &tm);
  66. if (!ms || (*ms != '\0' && *ms != ':'))
  67. return 0;
  68. if (*ms == '\0')
  69. ms = ":00";
  70. ms = strptime(ms + 1, "%S", &tm);
  71. if (!ms)
  72. return 0;
  73. return mktime(&tm);
  74. }