Optional Two-phase heap tracing
[hiphop-php.git] / hphp / util / md5.h
blob0e10af531b4a8fc173016a436cc31e7fa6be7748
1 /*
2 +----------------------------------------------------------------------+
3 | HipHop for PHP |
4 +----------------------------------------------------------------------+
5 | Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) |
6 +----------------------------------------------------------------------+
7 | This source file is subject to version 3.01 of the PHP license, |
8 | that is bundled with this package in the file LICENSE, and is |
9 | available through the world-wide-web at the following url: |
10 | http://www.php.net/license/3_01.txt |
11 | If you did not receive a copy of the PHP license and are unable to |
12 | obtain it through the world-wide-web, please send a note to |
13 | license@php.net so we can mail you a copy immediately. |
14 +----------------------------------------------------------------------+
17 #ifndef incl_HPHP_BASE_MD5_H_
18 #define incl_HPHP_BASE_MD5_H_
20 #include <cstring>
21 #include <memory>
23 #include <boost/operators.hpp>
25 #include <folly/String.h>
26 #include <folly/Range.h>
28 #include "hphp/util/assertions.h"
29 #include "hphp/util/byte-order.h"
31 namespace HPHP {
33 //////////////////////////////////////////////////////////////////////
35 struct MD5 : private boost::totally_ordered<MD5> {
36 uint64_t q[2];
38 MD5() : q{} {}
40 // Input should be null-terminated output from PHP::md5().
41 explicit MD5(folly::StringPiece str) {
42 assertx(str.size() == 32);
43 auto constexpr kQWordAsciiLen = 16;
44 char buf[kQWordAsciiLen + 1];
45 buf[kQWordAsciiLen] = '\0';
46 memcpy(buf, str.begin(), kQWordAsciiLen);
47 assertx(strlen(buf) == 16);
48 q[0] = strtoull(buf, nullptr, 16);
50 memcpy(buf, str.begin() + kQWordAsciiLen, 16);
51 assertx(strlen(buf) == 16);
52 q[1] = strtoull(buf, nullptr, 16);
55 // Blob is assumed to be in network byte order.
56 explicit MD5(const void* blob, DEBUG_ONLY size_t len) {
57 assertx(len == 16);
58 q[0] = ntohq(((const uint64_t*)blob)[0]);
59 q[1] = ntohq(((const uint64_t*)blob)[1]);
62 explicit MD5(uint64_t x) {
63 q[0] = 0; q[1] = x;
66 // Copy out in network byte order.
67 void nbo(void* blob) const {
68 ((uint64_t*)blob)[0] = htonq(q[0]);
69 ((uint64_t*)blob)[1] = htonq(q[1]);
72 // Convert to a std::string with hex representation of the md5.
73 std::string toString() const {
74 std::string ret;
75 char md5nbo[16];
76 nbo(md5nbo);
77 folly::hexlify(folly::StringPiece(md5nbo, sizeof md5nbo), ret);
78 return ret;
81 bool operator==(const MD5& r) const {
82 return q[0] == r.q[0] && q[1] == r.q[1];
85 bool operator<(const MD5& r) const {
86 return q[0] < r.q[0] || (q[0] == r.q[0] && q[1] < r.q[1]);
89 uint64_t hash() const {
90 // All the bits here are fantastically good.
91 return q[0];
95 //////////////////////////////////////////////////////////////////////
99 #endif