wabbajack/Wabbajack.Common/AbsolutePathExtensions.cs

45 lines
1.5 KiB
C#
Raw Normal View History

2021-09-27 12:42:46 +00:00
using System.IO;
using System.Threading;
using System.Threading.Tasks;
2021-12-27 05:13:28 +00:00
using Wabbajack.DTOs.JsonConverters;
2021-09-27 12:42:46 +00:00
using Wabbajack.Hashing.xxHash64;
using Wabbajack.Paths;
using Wabbajack.Paths.IO;
2021-10-23 16:51:17 +00:00
namespace Wabbajack.Common;
public static class AbsolutePathExtensions
2021-09-27 12:42:46 +00:00
{
2021-10-23 16:51:17 +00:00
public static async Task<Hash> Hash(this AbsolutePath path, CancellationToken? token = null)
2021-09-27 12:42:46 +00:00
{
2021-10-23 16:51:17 +00:00
await using var fs = path.Open(FileMode.Open);
return await fs.HashingCopy(Stream.Null, token ?? CancellationToken.None);
2021-09-27 12:42:46 +00:00
}
2021-12-27 05:13:28 +00:00
public static async Task<T> FromJson<T>(this AbsolutePath path, DTOSerializer? dtos = null)
{
await using var fs = path.Open(FileMode.Open, FileAccess.Read, FileShare.Read);
return await fs.FromJson<T>(dtos);
}
2022-10-23 21:28:44 +00:00
public static async Task<Hash> WriteAllHashedAsync(this AbsolutePath file, Stream srcStream, CancellationToken token,
bool closeWhenDone = true)
{
try
{
await using var dest = file.Open(FileMode.Create, FileAccess.Write, FileShare.None);
return await srcStream.HashingCopy(dest, token);
}
finally
{
if (closeWhenDone)
srcStream.Close();
}
}
public static async Task<Hash> WriteAllHashedAsync(this AbsolutePath file, byte[] data, CancellationToken token)
{
await using var dest = file.Open(FileMode.Create, FileAccess.Write, FileShare.None);
return await new MemoryStream(data).HashingCopy(dest, token);
}
2021-09-27 12:42:46 +00:00
}