using System.Security.Cryptography;
namespace Titano.Core.Archiving;
/// SHA-256 of files, streamed (originals can be hundreds of megabytes).
public static class ContentHash
{
internal const int BufferSize = 1 << 20;
/// Lower-case hex SHA-256 of the file.
/// Receives the number of bytes read since the previous call.
public static async Task Sha256Async(string path, Action? progress = null, CancellationToken cancellationToken = default)
{
await using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete, BufferSize,
FileOptions.Asynchronous | FileOptions.SequentialScan);
return await Sha256Async(stream, progress, cancellationToken).ConfigureAwait(false);
}
public static async Task Sha256Async(Stream stream, Action? progress = null, CancellationToken cancellationToken = default)
{
using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
var buffer = new byte[BufferSize];
int read;
while ((read = await stream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false)) > 0)
{
hash.AppendData(buffer, 0, read);
progress?.Invoke(read);
}
return Convert.ToHexStringLower(hash.GetHashAndReset());
}
}
/// Size and modification time of a file, the cheap change detector of incremental scans (BRIEF ยง7).
public readonly record struct FileStamp(long Size, DateTime ModifiedUtc)
{
/// The stamp of a file or directory, or null when it does not exist.
public static FileStamp? Of(string path)
{
var file = new FileInfo(path);
if (file.Exists) return new FileStamp(file.Length, file.LastWriteTimeUtc);
var directory = new DirectoryInfo(path);
return directory.Exists ? new FileStamp(0, directory.LastWriteTimeUtc) : null;
}
}