Skip to content

Digest calculated in batches of sizeof(size_t) #606

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 3 commits into
base: develop
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 70 additions & 6 deletions include/boost/json/detail/digest.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@
#ifndef BOOST_JSON_DETAIL_DIGEST_HPP
#define BOOST_JSON_DETAIL_DIGEST_HPP

#include <algorithm>
#include <array>
#include <cstring>

namespace boost {
namespace json {
namespace detail {
Expand All @@ -23,18 +27,78 @@ digest(
std::size_t salt) noexcept
{
#if BOOST_JSON_ARCH == 64
std::uint64_t const prime = 0x100000001B3ULL;
std::uint64_t hash = 0xcbf29ce484222325ULL;
using hash_t = std::uint64_t;
hash_t const prime = 0x100000001B3ULL;
hash_t hash = 0xcbf29ce484222325ULL;
#else
using hash_t = std::uint32_t;
hash_t const prime = 0x01000193UL;
hash_t hash = 0x811C9DC5UL;
#endif
hash += salt;

constexpr std::size_t step = sizeof(hash_t);
std::size_t n = std::distance(b, e);

std::array<unsigned char, step> temp;
hash_t batch;
while( n >= step )
{
std::copy_n(b, step, temp.data());

std::memcpy(&batch, temp.data(), step);
hash = (batch ^ hash) * prime;

std::advance(b, step);
n -= step;
}

temp.fill(0);
std::copy_n(b, n, temp.data());

std::memcpy(&batch, temp.data(), step);
hash = (batch ^ hash) * prime;

return hash;
}

// Calculate salted digest of string
template<>
inline
std::size_t
digest<char const*>(
char const* b,
char const* e,
std::size_t salt) noexcept
{
#if BOOST_JSON_ARCH == 64
using hash_t = std::uint64_t;
hash_t const prime = 0x100000001B3ULL;
hash_t hash = 0xcbf29ce484222325ULL;
#else
std::uint32_t const prime = 0x01000193UL;
std::uint32_t hash = 0x811C9DC5UL;
using hash_t = std::uint32_t;
hash_t const prime = 0x01000193UL;
hash_t hash = 0x811C9DC5UL;
#endif
hash += salt;
for(; b != e; ++b)
hash = (*b ^ hash) * prime;

constexpr std::size_t step = sizeof(hash_t);

hash_t batch;
for( ; (e - b) >= static_cast<int>(step); b += step )
{
std::memcpy(&batch, b, step);
hash = (batch ^ hash) * prime;
}

batch = 0;
std::memcpy(&batch, b, e - b);
hash = (batch ^ hash) * prime;

return hash;
}


} // detail
} // namespace json
} // namespace boost
Expand Down