1 /* 2 * Copyright (C) 2001-2012 Jacek Sieka, arnetheduck on gmail point com 3 * 4 * This program is free software; you can redistribute it and/or modify 5 * it under the terms of the GNU General Public License as published by 6 * the Free Software Foundation; either version 2 of the License, or 7 * (at your option) any later version. 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 17 */ 18 19 #pragma once 20 21 #include "Encoder.h" 22 #include "Util.h" 23 #include <functional> 24 #include <algorithm> 25 26 namespace dcpp { 27 28 class CID { 29 public: 30 enum { SIZE = 192 / 8 }; 31 CID()32 CID() { memset(cid, 0, sizeof(cid)); } CID(const uint8_t * data)33 explicit CID(const uint8_t* data) { memcpy(cid, data, sizeof(cid)); } CID(const string & base32)34 explicit CID(const string& base32) { Encoder::fromBase32(base32.c_str(), cid, sizeof(cid)); } 35 36 bool operator==(const CID& rhs) const { return memcmp(cid, rhs.cid, sizeof(cid)) == 0; } 37 bool operator<(const CID& rhs) const { return memcmp(cid, rhs.cid, sizeof(cid)) < 0; } 38 toBase32()39 string toBase32() const { return Encoder::toBase32(cid, sizeof(cid)); } toBase32(string & tmp)40 string& toBase32(string& tmp) const { return Encoder::toBase32(cid, sizeof(cid), tmp); } 41 toHash()42 size_t toHash() const { 43 // RVO should handle this as efficiently as reinterpret_cast version 44 size_t cidHash; 45 memcpy(&cidHash, cid, sizeof(size_t)); 46 return cidHash; 47 } data()48 const uint8_t* data() const { return cid; } 49 isZero()50 bool isZero() const { return std::find_if(cid, cid+SIZE, bind2nd(std::not_equal_to<uint8_t>(), 0)) == (cid+SIZE); } 51 52 static CID generate(); 53 54 private: 55 uint8_t cid[SIZE]; 56 }; 57 58 } // namespace dcpp 59 60 namespace std { 61 template<> 62 struct hash<dcpp::CID> { 63 size_t operator()(const dcpp::CID& rhs) const { 64 size_t hvHash; 65 memcpy(&hvHash, rhs.data(), sizeof(size_t)); 66 return hvHash; 67 } 68 }; 69 70 } // namespace dcpp 71