/* */ #include "GroupId.h" #include #include "util.h" namespace aria2 { std::set GroupId::set_; std::shared_ptr GroupId::create() { a2_gid_t n; for(;;) { util::generateRandomData(reinterpret_cast(&n), sizeof(n)); if(n != 0 && set_.count(n) == 0) { break; } } std::shared_ptr res(new GroupId(n)); return res; } std::shared_ptr GroupId::import(a2_gid_t n) { std::shared_ptr res; if(n == 0 || set_.count(n) != 0) { return res; } res.reset(new GroupId(n)); return res; } void GroupId::clear() { set_.clear(); } int GroupId::expandUnique(a2_gid_t& n, const char* hex) { a2_gid_t p = 0; size_t i; for(i = 0; hex[i]; ++i) { unsigned int c = util::hexCharToUInt(hex[i]); if(c == 255) { return ERR_INVALID; } p <<= 4; p |= c; } if(i == 0 || i > sizeof(a2_gid_t)*2) { return ERR_INVALID; } p <<= 64-i*4; a2_gid_t mask = UINT64_MAX-((1LL << (64-i*4))-1); std::set::const_iterator itr = set_.lower_bound(p); if(itr == set_.end()) { return ERR_NOT_FOUND; } if(p == ((*itr)&mask)) { n = *itr; ++itr; if(itr == set_.end() || p != ((*itr)&mask)) { return 0; } else { return ERR_NOT_UNIQUE; } } else { return ERR_NOT_FOUND; } } int GroupId::toNumericId(a2_gid_t& n, const char* hex) { a2_gid_t p = 0; size_t i; for(i = 0; hex[i]; ++i) { unsigned int c = util::hexCharToUInt(hex[i]); if(c == 255) { return ERR_INVALID; } p <<= 4; p |= c; } if(p == 0 || i != sizeof(a2_gid_t)*2) { return ERR_INVALID; } n = p; return 0; } std::string GroupId::toHex(a2_gid_t gid) { a2_gid_t n = hton64(gid); return util::toHex(reinterpret_cast(&n), sizeof(n)); } std::string GroupId::toAbbrevHex(a2_gid_t gid) { const size_t abbrevSize = 6; std::string h = toHex(gid); assert(h.size() >= abbrevSize); return toHex(gid).erase(abbrevSize); } std::string GroupId::toHex() const { return toHex(gid_); } std::string GroupId::toAbbrevHex() const { return toAbbrevHex(gid_); } GroupId::GroupId(a2_gid_t gid) : gid_(gid) { set_.insert(gid_); } GroupId::~GroupId() { set_.erase(gid_); } } // namespace aria2