blob: b6964264d4f90ca11465feca48454780efa8490d [file] [log] [blame]
Alexander Afanasyevde1cdd02012-12-29 14:41:46 -08001/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil -*- */
2/*
3 * Copyright (c) 2012 University of California, Los Angeles
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2 as
7 * published by the Free Software Foundation;
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 *
18 * Author: Alexander Afanasyev <alexander.afanasyev@ucla.edu>
19 * Zhenkai Zhu <zhenkai@cs.ucla.edu>
20 */
21
22#ifndef HASH_STRING_CONVERTER_H
23#define HASH_STRING_CONVERTER_H
24
25#include <string.h>
26#include <iostream>
27#include <boost/shared_ptr.hpp>
28#include <boost/exception/all.hpp>
29
30class Hash
31{
32public:
33 Hash (const void *buf, size_t length)
34 : m_length (length)
35 {
Alexander Afanasyevae43c502012-12-29 17:26:37 -080036 if (m_length != 0)
37 {
38 m_buf = new unsigned char [length];
39 memcpy (m_buf, buf, length);
40 }
Alexander Afanasyevde1cdd02012-12-29 14:41:46 -080041 }
42
43 Hash (const std::string &hashInTextEncoding);
44
45 ~Hash ()
46 {
Alexander Afanasyevae43c502012-12-29 17:26:37 -080047 if (m_length != 0)
48 delete [] m_buf;
Alexander Afanasyevde1cdd02012-12-29 14:41:46 -080049 }
50
51 bool
52 IsZero () const
53 {
54 return m_length == 0 ||
55 (m_length == 1 && m_buf[0] == 0);
56 }
57
58 bool
59 operator == (const Hash &otherHash) const
60 {
61 if (m_length != otherHash.m_length)
62 return false;
63
64 return memcmp (m_buf, otherHash.m_buf, m_length) == 0;
65 }
66
67 const void *
68 GetHash () const
69 {
70 return m_buf;
71 }
72
73 size_t
74 GetHashBytes () const
75 {
76 return m_length;
77 }
78
79private:
80 unsigned char *m_buf;
81 size_t m_length;
82
Alexander Afanasyevae43c502012-12-29 17:26:37 -080083 Hash (const Hash &) { }
84 Hash & operator = (const Hash &) { return *this; }
85
Alexander Afanasyevde1cdd02012-12-29 14:41:46 -080086 friend std::ostream &
87 operator << (std::ostream &os, const Hash &digest);
88};
89
90namespace Error {
91struct HashConversion : virtual boost::exception, virtual std::exception { };
92}
93
94typedef boost::shared_ptr<Hash> HashPtr;
95
96
97std::ostream &
98operator << (std::ostream &os, const Hash &digest);
99
100#endif // HASH_STRING_CONVERTER_H