blob: 1a8406506cf1ecb639c5fe1ee7b938656d888f16 [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 {
36 m_buf = new unsigned char [length];
37 memcpy (m_buf, buf, length);
38 }
39
40 Hash (const std::string &hashInTextEncoding);
41
42 ~Hash ()
43 {
44 delete [] m_buf;
45 }
46
47 bool
48 IsZero () const
49 {
50 return m_length == 0 ||
51 (m_length == 1 && m_buf[0] == 0);
52 }
53
54 bool
55 operator == (const Hash &otherHash) const
56 {
57 if (m_length != otherHash.m_length)
58 return false;
59
60 return memcmp (m_buf, otherHash.m_buf, m_length) == 0;
61 }
62
63 const void *
64 GetHash () const
65 {
66 return m_buf;
67 }
68
69 size_t
70 GetHashBytes () const
71 {
72 return m_length;
73 }
74
75private:
76 unsigned char *m_buf;
77 size_t m_length;
78
79 friend std::ostream &
80 operator << (std::ostream &os, const Hash &digest);
81};
82
83namespace Error {
84struct HashConversion : virtual boost::exception, virtual std::exception { };
85}
86
87typedef boost::shared_ptr<Hash> HashPtr;
88
89
90std::ostream &
91operator << (std::ostream &os, const Hash &digest);
92
93#endif // HASH_STRING_CONVERTER_H