Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. // Copyright (c) 2014 The Starwels developers
  2. // Distributed under the MIT software license, see the accompanying
  3. // file COPYING or http://www.opensource.org/licenses/mit-license.php.
  4. #ifndef STARWELS_CRYPTO_COMMON_H
  5. #define STARWELS_CRYPTO_COMMON_H
  6. #if defined(HAVE_CONFIG_H)
  7. #include "starwels-config.h"
  8. #endif
  9. #include <stdint.h>
  10. #include <string.h>
  11. #include "compat/endian.h"
  12. uint16_t static inline ReadLE16(const unsigned char* ptr)
  13. {
  14. uint16_t x;
  15. memcpy((char*)&x, ptr, 2);
  16. return le16toh(x);
  17. }
  18. uint32_t static inline ReadLE32(const unsigned char* ptr)
  19. {
  20. uint32_t x;
  21. memcpy((char*)&x, ptr, 4);
  22. return le32toh(x);
  23. }
  24. uint64_t static inline ReadLE64(const unsigned char* ptr)
  25. {
  26. uint64_t x;
  27. memcpy((char*)&x, ptr, 8);
  28. return le64toh(x);
  29. }
  30. void static inline WriteLE16(unsigned char* ptr, uint16_t x)
  31. {
  32. uint16_t v = htole16(x);
  33. memcpy(ptr, (char*)&v, 2);
  34. }
  35. void static inline WriteLE32(unsigned char* ptr, uint32_t x)
  36. {
  37. uint32_t v = htole32(x);
  38. memcpy(ptr, (char*)&v, 4);
  39. }
  40. void static inline WriteLE64(unsigned char* ptr, uint64_t x)
  41. {
  42. uint64_t v = htole64(x);
  43. memcpy(ptr, (char*)&v, 8);
  44. }
  45. uint32_t static inline ReadBE32(const unsigned char* ptr)
  46. {
  47. uint32_t x;
  48. memcpy((char*)&x, ptr, 4);
  49. return be32toh(x);
  50. }
  51. uint64_t static inline ReadBE64(const unsigned char* ptr)
  52. {
  53. uint64_t x;
  54. memcpy((char*)&x, ptr, 8);
  55. return be64toh(x);
  56. }
  57. void static inline WriteBE32(unsigned char* ptr, uint32_t x)
  58. {
  59. uint32_t v = htobe32(x);
  60. memcpy(ptr, (char*)&v, 4);
  61. }
  62. void static inline WriteBE64(unsigned char* ptr, uint64_t x)
  63. {
  64. uint64_t v = htobe64(x);
  65. memcpy(ptr, (char*)&v, 8);
  66. }
  67. /** Return the smallest number n such that (x >> n) == 0 (or 64 if the highest bit in x is set. */
  68. uint64_t static inline CountBits(uint64_t x)
  69. {
  70. #ifdef HAVE_DECL___BUILTIN_CLZL
  71. if (sizeof(unsigned long) >= sizeof(uint64_t)) {
  72. return x ? 8 * sizeof(unsigned long) - __builtin_clzl(x) : 0;
  73. }
  74. #endif
  75. #ifdef HAVE_DECL___BUILTIN_CLZLL
  76. if (sizeof(unsigned long long) >= sizeof(uint64_t)) {
  77. return x ? 8 * sizeof(unsigned long long) - __builtin_clzll(x) : 0;
  78. }
  79. #endif
  80. int ret = 0;
  81. while (x) {
  82. x >>= 1;
  83. ++ret;
  84. }
  85. return ret;
  86. }
  87. #endif // STARWELS_CRYPTO_COMMON_H