Core/Stream: Add HashAppend overload

This commit is contained in:
SirLynix 2023-03-03 13:19:12 +01:00
parent 34abeeb7bd
commit 0494a72849
4 changed files with 50 additions and 6 deletions

View File

@ -23,8 +23,8 @@ namespace Nz
{
class ByteArray;
template<typename T> ByteArray ComputeHash(HashType hash, const T& v);
template<typename T> ByteArray ComputeHash(AbstractHash& hash, const T& v);
template<typename T> ByteArray ComputeHash(HashType hash, T&& v);
template<typename T> ByteArray ComputeHash(AbstractHash& hash, T&& v);
inline bool HashAppend(AbstractHash* hash, const std::string_view& v);

View File

@ -30,9 +30,9 @@ namespace Nz
* \see ComputeHash
*/
template<typename T>
ByteArray ComputeHash(HashType hash, const T& v)
ByteArray ComputeHash(HashType hash, T&& v)
{
return ComputeHash(*AbstractHash::Get(hash), v);
return ComputeHash(*AbstractHash::Get(hash), std::forward<T>(v));
}
/*!
@ -49,11 +49,11 @@ namespace Nz
* \see ComputeHash
*/
template<typename T>
ByteArray ComputeHash(AbstractHash& hash, const T& v)
ByteArray ComputeHash(AbstractHash& hash, T&& v)
{
hash.Begin();
HashAppend(hash, v);
HashAppend(hash, std::forward<T>(v));
return hash.End();
}

View File

@ -83,6 +83,8 @@ namespace Nz
StreamOptionFlags m_streamOptions;
UInt64 m_bufferCursor;
};
NAZARA_CORE_API bool HashAppend(AbstractHash& hash, Stream& stream);
}
#include <Nazara/Core/Stream.inl>

View File

@ -281,4 +281,46 @@ namespace Nz
NazaraError("Stream set the MemoryMapped option but did not implement GetMemoryMappedPointer");
return nullptr;
}
bool HashAppend(AbstractHash& hash, Stream& stream)
{
if (stream.IsMemoryMapped())
{
const void* ptr = stream.GetMappedPointer();
UInt64 size = stream.GetSize();
if (ptr && size > 0)
{
hash.Append(static_cast<const UInt8*>(ptr), size);
return true;
}
}
std::array<UInt8, NAZARA_CORE_FILE_BUFFERSIZE> content;
// Save and restore cursor position after the call
std::size_t cursorPos = stream.GetCursorPos();
CallOnExit restoreCursorPos([&] { stream.SetCursorPos(cursorPos); });
stream.SetCursorPos(0);
while (!stream.EndOfStream())
{
std::size_t readSize = stream.Read(&content[0], content.size());
if (readSize > 0)
hash.Append(&content[0], readSize);
if (readSize != content.size())
{
if (!stream.EndOfStream())
{
NazaraError("failed to read from stream");
return false;
}
break;
}
}
return true;
}
}