Utils.h 2.2 KB

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