CID.h
Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019 #ifndef ADCHPP_CID_H
00020 #define ADCHPP_CID_H
00021
00022 #include "Util.h"
00023 #include "Encoder.h"
00024
00025 namespace adchpp {
00026
00027 class CID {
00028 public:
00029 enum { SIZE = 192 / 8 };
00030 enum { BASE32_SIZE = 39 };
00031
00032 CID() { memset(cid, 0, sizeof(cid)); }
00033 explicit CID(const uint8_t* data) { memcpy(cid, data, sizeof(cid)); }
00034 explicit CID(const std::string& base32) { Encoder::fromBase32(base32.c_str(), cid, sizeof(cid)); }
00035
00036 CID(const CID& rhs) { memcpy(cid, rhs.cid, sizeof(cid)); }
00037 CID& operator=(const CID& rhs) { memcpy(cid, rhs.cid, sizeof(cid)); return *this; }
00038
00039 bool operator==(const CID& rhs) const { return memcmp(cid, rhs.cid, sizeof(cid)) == 0; }
00040 bool operator<(const CID& rhs) const { return memcmp(cid, rhs.cid, sizeof(cid)) < 0; }
00041
00042 std::string toBase32() const { return Encoder::toBase32(cid, sizeof(cid)); }
00043 std::string& toBase32(std::string& tmp) const { return Encoder::toBase32(cid, sizeof(cid), tmp); }
00044
00045 size_t toHash() const { static_assert(sizeof(cid) >= sizeof(cidHash), "cid too small, cidHash invalid"); return cidHash; }
00046 const uint8_t* data() const { return cid; }
00047
00048 bool isZero() const { return std::find_if(cid, cid+SIZE, std::bind2nd(std::not_equal_to<uint8_t>(), 0)) == (cid+SIZE); }
00049
00050 static CID generate() {
00051 uint8_t data[CID::SIZE];
00052 for(size_t i = 0; i < sizeof(data); ++i) {
00053 data[i] = (uint8_t)Util::rand();
00054 }
00055 return CID(data);
00056 }
00057
00058 private:
00059 union {
00060 uint8_t cid[SIZE];
00061 size_t cidHash;
00062 };
00063 };
00064
00065 }
00066
00067 namespace std {
00068 template<>
00069 struct hash<adchpp::CID> {
00070 size_t operator()(const adchpp::CID& cid) const {
00071 return cid.toHash();
00072 }
00073 };
00074 }
00075
00076 #endif