hash.h 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. #pragma once
  2. #include <functional>
  3. #include <iomanip>
  4. #include <sstream>
  5. #include <vector>
  6. #include <c10/util/ArrayRef.h>
  7. #include <c10/util/complex.h>
  8. namespace c10 {
  9. // NOTE: hash_combine and SHA1 hashing is based on implementation from Boost
  10. //
  11. // Boost Software License - Version 1.0 - August 17th, 2003
  12. //
  13. // Permission is hereby granted, free of charge, to any person or organization
  14. // obtaining a copy of the software and accompanying documentation covered by
  15. // this license (the "Software") to use, reproduce, display, distribute,
  16. // execute, and transmit the Software, and to prepare derivative works of the
  17. // Software, and to permit third-parties to whom the Software is furnished to
  18. // do so, all subject to the following:
  19. //
  20. // The copyright notices in the Software and this entire statement, including
  21. // the above license grant, this restriction and the following disclaimer,
  22. // must be included in all copies of the Software, in whole or in part, and
  23. // all derivative works of the Software, unless such copies or derivative
  24. // works are solely in the form of machine-executable object code generated by
  25. // a source language processor.
  26. //
  27. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  28. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  29. // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
  30. // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
  31. // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
  32. // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  33. // DEALINGS IN THE SOFTWARE.
  34. inline size_t hash_combine(size_t seed, size_t value) {
  35. return seed ^ (value + 0x9e3779b9 + (seed << 6u) + (seed >> 2u));
  36. }
  37. // Creates the SHA1 hash of a string. A 160-bit hash.
  38. // Based on the implementation in Boost (see notice above).
  39. // Note that SHA1 hashes are no longer considered cryptographically
  40. // secure, but are the standard hash for generating unique ids.
  41. // Usage:
  42. // // Let 'code' be a std::string
  43. // c10::sha1 sha1_hash{code};
  44. // const auto hash_code = sha1_hash.str();
  45. // TODO: Compare vs OpenSSL and/or CryptoPP implementations
  46. struct sha1 {
  47. typedef unsigned int(digest_type)[5];
  48. sha1(const std::string& s = "") {
  49. if (!s.empty()) {
  50. reset();
  51. process_bytes(s.c_str(), s.size());
  52. }
  53. }
  54. void reset() {
  55. h_[0] = 0x67452301;
  56. h_[1] = 0xEFCDAB89;
  57. h_[2] = 0x98BADCFE;
  58. h_[3] = 0x10325476;
  59. h_[4] = 0xC3D2E1F0;
  60. block_byte_index_ = 0;
  61. bit_count_low = 0;
  62. bit_count_high = 0;
  63. }
  64. std::string str() {
  65. unsigned int digest[5];
  66. get_digest(digest);
  67. std::ostringstream buf;
  68. for (unsigned int i : digest) {
  69. buf << std::hex << std::setfill('0') << std::setw(8) << i;
  70. }
  71. return buf.str();
  72. }
  73. private:
  74. unsigned int left_rotate(unsigned int x, std::size_t n) {
  75. return (x << n) ^ (x >> (32 - n));
  76. }
  77. void process_block_impl() {
  78. unsigned int w[80];
  79. for (std::size_t i = 0; i < 16; ++i) {
  80. w[i] = (block_[i * 4 + 0] << 24);
  81. w[i] |= (block_[i * 4 + 1] << 16);
  82. w[i] |= (block_[i * 4 + 2] << 8);
  83. w[i] |= (block_[i * 4 + 3]);
  84. }
  85. for (std::size_t i = 16; i < 80; ++i) {
  86. w[i] = left_rotate((w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]), 1);
  87. }
  88. unsigned int a = h_[0];
  89. unsigned int b = h_[1];
  90. unsigned int c = h_[2];
  91. unsigned int d = h_[3];
  92. unsigned int e = h_[4];
  93. for (std::size_t i = 0; i < 80; ++i) {
  94. unsigned int f;
  95. unsigned int k;
  96. if (i < 20) {
  97. f = (b & c) | (~b & d);
  98. k = 0x5A827999;
  99. } else if (i < 40) {
  100. f = b ^ c ^ d;
  101. k = 0x6ED9EBA1;
  102. } else if (i < 60) {
  103. f = (b & c) | (b & d) | (c & d);
  104. k = 0x8F1BBCDC;
  105. } else {
  106. f = b ^ c ^ d;
  107. k = 0xCA62C1D6;
  108. }
  109. unsigned temp = left_rotate(a, 5) + f + e + k + w[i];
  110. e = d;
  111. d = c;
  112. c = left_rotate(b, 30);
  113. b = a;
  114. a = temp;
  115. }
  116. h_[0] += a;
  117. h_[1] += b;
  118. h_[2] += c;
  119. h_[3] += d;
  120. h_[4] += e;
  121. }
  122. void process_byte_impl(unsigned char byte) {
  123. block_[block_byte_index_++] = byte;
  124. if (block_byte_index_ == 64) {
  125. block_byte_index_ = 0;
  126. process_block_impl();
  127. }
  128. }
  129. void process_byte(unsigned char byte) {
  130. process_byte_impl(byte);
  131. // size_t max value = 0xFFFFFFFF
  132. // if (bit_count_low + 8 >= 0x100000000) { // would overflow
  133. // if (bit_count_low >= 0x100000000-8) {
  134. if (bit_count_low < 0xFFFFFFF8) {
  135. bit_count_low += 8;
  136. } else {
  137. bit_count_low = 0;
  138. if (bit_count_high <= 0xFFFFFFFE) {
  139. ++bit_count_high;
  140. } else {
  141. TORCH_CHECK(false, "sha1 too many bytes");
  142. }
  143. }
  144. }
  145. void process_block(void const* bytes_begin, void const* bytes_end) {
  146. unsigned char const* begin = static_cast<unsigned char const*>(bytes_begin);
  147. unsigned char const* end = static_cast<unsigned char const*>(bytes_end);
  148. for (; begin != end; ++begin) {
  149. process_byte(*begin);
  150. }
  151. }
  152. void process_bytes(void const* buffer, std::size_t byte_count) {
  153. unsigned char const* b = static_cast<unsigned char const*>(buffer);
  154. process_block(b, b + byte_count);
  155. }
  156. void get_digest(digest_type& digest) {
  157. // append the bit '1' to the message
  158. process_byte_impl(0x80);
  159. // append k bits '0', where k is the minimum number >= 0
  160. // such that the resulting message length is congruent to 56 (mod 64)
  161. // check if there is enough space for padding and bit_count
  162. if (block_byte_index_ > 56) {
  163. // finish this block
  164. while (block_byte_index_ != 0) {
  165. process_byte_impl(0);
  166. }
  167. // one more block
  168. while (block_byte_index_ < 56) {
  169. process_byte_impl(0);
  170. }
  171. } else {
  172. while (block_byte_index_ < 56) {
  173. process_byte_impl(0);
  174. }
  175. }
  176. // append length of message (before pre-processing)
  177. // as a 64-bit big-endian integer
  178. process_byte_impl(
  179. static_cast<unsigned char>((bit_count_high >> 24) & 0xFF));
  180. process_byte_impl(
  181. static_cast<unsigned char>((bit_count_high >> 16) & 0xFF));
  182. process_byte_impl(static_cast<unsigned char>((bit_count_high >> 8) & 0xFF));
  183. process_byte_impl(static_cast<unsigned char>((bit_count_high)&0xFF));
  184. process_byte_impl(static_cast<unsigned char>((bit_count_low >> 24) & 0xFF));
  185. process_byte_impl(static_cast<unsigned char>((bit_count_low >> 16) & 0xFF));
  186. process_byte_impl(static_cast<unsigned char>((bit_count_low >> 8) & 0xFF));
  187. process_byte_impl(static_cast<unsigned char>((bit_count_low)&0xFF));
  188. // get final digest
  189. digest[0] = h_[0];
  190. digest[1] = h_[1];
  191. digest[2] = h_[2];
  192. digest[3] = h_[3];
  193. digest[4] = h_[4];
  194. }
  195. unsigned int h_[5];
  196. unsigned char block_[64];
  197. std::size_t block_byte_index_;
  198. std::size_t bit_count_low;
  199. std::size_t bit_count_high;
  200. };
  201. ////////////////////////////////////////////////////////////////////////////////
  202. // c10::hash implementation
  203. ////////////////////////////////////////////////////////////////////////////////
  204. namespace _hash_detail {
  205. // Use template argument deduction to shorten calls to c10::hash
  206. template <typename T>
  207. size_t simple_get_hash(const T& o);
  208. template <typename T, typename V>
  209. using type_if_not_enum =
  210. typename std::enable_if<!std::is_enum<T>::value, V>::type;
  211. // Use SFINAE to dispatch to std::hash if possible, cast enum types to int
  212. // automatically, and fall back to T::hash otherwise. NOTE: C++14 added support
  213. // for hashing enum types to the standard, and some compilers implement it even
  214. // when C++14 flags aren't specified. This is why we have to disable this
  215. // overload if T is an enum type (and use the one below in this case).
  216. template <typename T>
  217. auto dispatch_hash(const T& o)
  218. -> decltype(std::hash<T>()(o), type_if_not_enum<T, size_t>()) {
  219. return std::hash<T>()(o);
  220. }
  221. template <typename T>
  222. typename std::enable_if<std::is_enum<T>::value, size_t>::type dispatch_hash(
  223. const T& o) {
  224. using R = typename std::underlying_type<T>::type;
  225. return std::hash<R>()(static_cast<R>(o));
  226. }
  227. template <typename T>
  228. auto dispatch_hash(const T& o) -> decltype(T::hash(o), size_t()) {
  229. return T::hash(o);
  230. }
  231. } // namespace _hash_detail
  232. // Hasher struct
  233. template <typename T>
  234. struct hash {
  235. size_t operator()(const T& o) const {
  236. return _hash_detail::dispatch_hash(o);
  237. };
  238. };
  239. // Specialization for std::tuple
  240. template <typename... Types>
  241. struct hash<std::tuple<Types...>> {
  242. template <size_t idx, typename... Ts>
  243. struct tuple_hash {
  244. size_t operator()(const std::tuple<Ts...>& t) const {
  245. return hash_combine(
  246. _hash_detail::simple_get_hash(std::get<idx>(t)),
  247. tuple_hash<idx - 1, Ts...>()(t));
  248. }
  249. };
  250. template <typename... Ts>
  251. struct tuple_hash<0, Ts...> {
  252. size_t operator()(const std::tuple<Ts...>& t) const {
  253. return _hash_detail::simple_get_hash(std::get<0>(t));
  254. }
  255. };
  256. size_t operator()(const std::tuple<Types...>& t) const {
  257. return tuple_hash<sizeof...(Types) - 1, Types...>()(t);
  258. }
  259. };
  260. template <typename T1, typename T2>
  261. struct hash<std::pair<T1, T2>> {
  262. size_t operator()(const std::pair<T1, T2>& pair) const {
  263. std::tuple<T1, T2> tuple = std::make_tuple(pair.first, pair.second);
  264. return _hash_detail::simple_get_hash(tuple);
  265. }
  266. };
  267. template <typename T>
  268. struct hash<c10::ArrayRef<T>> {
  269. size_t operator()(c10::ArrayRef<T> v) const {
  270. size_t seed = 0;
  271. for (const auto& elem : v) {
  272. seed = hash_combine(seed, _hash_detail::simple_get_hash(elem));
  273. }
  274. return seed;
  275. }
  276. };
  277. // Specialization for std::vector
  278. template <typename T>
  279. struct hash<std::vector<T>> {
  280. size_t operator()(const std::vector<T>& v) const {
  281. return hash<c10::ArrayRef<T>>()(v);
  282. }
  283. };
  284. namespace _hash_detail {
  285. template <typename T>
  286. size_t simple_get_hash(const T& o) {
  287. return c10::hash<T>()(o);
  288. }
  289. } // namespace _hash_detail
  290. // Use this function to actually hash multiple things in one line.
  291. // Dispatches to c10::hash, so it can hash containers.
  292. // Example:
  293. //
  294. // static size_t hash(const MyStruct& s) {
  295. // return get_hash(s.member1, s.member2, s.member3);
  296. // }
  297. template <typename... Types>
  298. size_t get_hash(const Types&... args) {
  299. return c10::hash<decltype(std::tie(args...))>()(std::tie(args...));
  300. }
  301. // Specialization for c10::complex
  302. template <typename T>
  303. struct hash<c10::complex<T>> {
  304. size_t operator()(const c10::complex<T>& c) const {
  305. return get_hash(c.real(), c.imag());
  306. }
  307. };
  308. } // namespace c10