Skip to content

Commit

Permalink
infohash: add to_c_str(), improve toString() performance
Browse files Browse the repository at this point in the history
  • Loading branch information
aberaud committed Apr 10, 2017
1 parent fcca618 commit 9d75ed1
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 7 deletions.
2 changes: 2 additions & 0 deletions include/opendht/infohash.h
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,8 @@ class OPENDHT_PUBLIC InfoHash final : public std::array<uint8_t, HASH_LEN> {
OPENDHT_PUBLIC friend std::ostream& operator<< (std::ostream& s, const InfoHash& h);
OPENDHT_PUBLIC friend std::istream& operator>> (std::istream& s, InfoHash& h);

const char* to_c_str() const;

std::string toString() const;

template <typename Packer>
Expand Down
34 changes: 27 additions & 7 deletions src/infohash.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -71,20 +71,40 @@ InfoHash::getRandom()
return h;
}

struct HexMap : public std::array<std::array<char, 2>, 256> {
HexMap() {
for (size_t i=0; i<size(); i++) {
auto& e = (*this)[i];
e[0] = hex_digits[(i >> 4) & 0x0F];
e[1] = hex_digits[i & 0x0F];
}
}
private:
static constexpr const char* hex_digits = "0123456789abcdef";
};

const char*
InfoHash::to_c_str() const
{
static const HexMap map;
thread_local std::array<char, HASH_LEN*2+1> buf;
for (size_t i=0; i<HASH_LEN; i++) {
auto b = buf.data()+i*2;
const auto& m = map[(*this)[i]];
*((uint16_t*)b) = *((uint16_t*)&m);
}
return buf.data();
}

std::string
InfoHash::toString() const
{
std::stringstream ss;
ss << *this;
return ss.str();
return std::string(to_c_str(), HASH_LEN*2);
}

std::ostream& operator<< (std::ostream& s, const InfoHash& h)
{
s << std::hex;
for (unsigned i=0; i<HASH_LEN; i++)
s << std::setfill('0') << std::setw(2) << (unsigned)h[i];
s << std::dec;
s.write(h.to_c_str(), HASH_LEN*2);
return s;
}

Expand Down

0 comments on commit 9d75ed1

Please sign in to comment.