Utils.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. #ifndef UTILS_H
  2. #define UTILS_H
  3. #include <vector>
  4. #ifdef _WIN32
  5. #include <winsock2.h>
  6. #include <ws2tcpip.h>
  7. #include "win32shim.h"
  8. #else
  9. #include <unistd.h>
  10. #include "sys/socket.h"
  11. #include <netdb.h>
  12. #endif
  13. #include <cstdint>
  14. #include <cstring>
  15. #include <memory>
  16. #include <chrono>
  17. #include <string>
  18. #include <sstream>
  19. #include <iostream>
  20. #include <iomanip>
  21. #define HMAC_SHA1_BLOCKSIZE 64
  22. /**
  23. * @brief Returns current timestamp
  24. *
  25. * @return unsigned long long resulting timestamp in milliseconds from unix time zero
  26. */
  27. unsigned long long getCurrentTimestamp();
  28. /**
  29. * @brief portable 64bit equivalent of htons / htonl. aka endianess swap
  30. *
  31. * @param value input value to swap
  32. * @return uint64_t swapped result
  33. */
  34. uint64_t hton64(uint64_t value);
  35. /**
  36. * @brief Performs big number multiplication on two numbers
  37. *
  38. * @param num big num in vector format
  39. * @param n secondary number
  40. * @return std::vector<uint8_t> resulting number
  41. */
  42. std::vector<uint8_t> bigNumMultiply(std::vector<uint8_t> num, int n);
  43. /**
  44. * @brief Performs big number addition on two numbers
  45. *
  46. * @param num big num in vector format
  47. * @param n secondary number
  48. * @return std::vector<uint8_t> resulting number
  49. */
  50. std::vector<uint8_t> bigNumAdd(std::vector<uint8_t> num, int n);
  51. unsigned char h2int(char c);
  52. std::string urlDecode(std::string str);
  53. /**
  54. * @brief Converts provided bytes into a human readable hex string
  55. *
  56. * @param bytes vector containing binary data
  57. * @return std::string string containing hex representation of inputted data
  58. */
  59. std::string bytesToHexString(std::vector<uint8_t> &bytes);
  60. /**
  61. * @brief Extracts given type from binary data
  62. *
  63. * @tparam T type to extract
  64. * @param v vector containing binary data to extract from
  65. * @param pos position offset
  66. * @return T extracted type
  67. */
  68. template <typename T>
  69. T extract(const std::vector<unsigned char> &v, int pos)
  70. {
  71. T value;
  72. memcpy(&value, &v[pos], sizeof(T));
  73. return value;
  74. }
  75. /**
  76. * @brief Packs given type into binary data
  77. *
  78. * @tparam T type of data to pack
  79. * @param data data to pack
  80. * @return std::vector<uint8_t> resulting vector containing binary data
  81. */
  82. template <typename T>
  83. std::vector<uint8_t> pack(T data)
  84. {
  85. std::vector<std::uint8_t> rawData( (std::uint8_t*)&data, (std::uint8_t*)&(data) + sizeof(T));
  86. return rawData;
  87. }
  88. #endif