Move serialize functions to variable-serializer.cpp
[hiphop-php.git] / hphp / util / md5.h
blobf63a140dddd2d3afb63555151ddc66e7ebf765b0
1 /*
2 +----------------------------------------------------------------------+
3 | HipHop for PHP |
4 +----------------------------------------------------------------------+
5 | Copyright (c) 2010-2015 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/byte-order.h"
30 namespace HPHP {
32 //////////////////////////////////////////////////////////////////////
34 struct MD5 : private boost::totally_ordered<MD5> {
35 uint64_t q[2];
37 MD5() : q{} {}
39 // Input should be null-terminated output from PHP::md5().
40 explicit MD5(const char* str) {
41 assert(strlen(str) == 32);
42 const int kQWordAsciiLen = 16;
43 char buf[kQWordAsciiLen + 1];
44 buf[kQWordAsciiLen] = 0;
45 memcpy(buf, str, kQWordAsciiLen);
46 assert(strlen(buf) == 16);
47 q[0] = strtoull(buf, nullptr, 16);
49 memcpy(buf, str + kQWordAsciiLen, 16);
50 assert(strlen(buf) == 16);
51 q[1] = strtoull(buf, nullptr, 16);
54 // Blob is assumed to be in network byte order.
55 explicit MD5(const void* blob) {
56 q[0] = ntohq(((const uint64_t*)blob)[0]);
57 q[1] = ntohq(((const uint64_t*)blob)[1]);
60 // Copy out in network byte order.
61 void nbo(void* blob) const {
62 ((uint64_t*)blob)[0] = htonq(q[0]);
63 ((uint64_t*)blob)[1] = htonq(q[1]);
66 // Convert to a std::string with hex representation of the md5.
67 std::string toString() const {
68 std::string ret;
69 char md5nbo[16];
70 nbo(md5nbo);
71 folly::hexlify(folly::StringPiece(md5nbo, sizeof md5nbo), ret);
72 return ret;
75 bool operator==(const MD5& r) const {
76 return q[0] == r.q[0] && q[1] == r.q[1];
79 bool operator<(const MD5& r) const {
80 return q[0] < r.q[0] || (q[0] == r.q[0] && q[1] < r.q[1]);
83 uint64_t hash() const {
84 // hash_int64_pair does way more work than necessary; all the bits here
85 // are fantastically good.
86 return q[0];
90 //////////////////////////////////////////////////////////////////////
94 #endif