Commit d78c994d authored by Ray Koopa's avatar Ray Koopa

Add MoveAsync

parent 9f9f5fd7
......@@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Syroot.BinaryData
......@@ -160,6 +161,16 @@ namespace Syroot.BinaryData
public void Move(long offset)
=> BaseStream.Move(offset);
/// <summary>
/// Sets the position within the underlying stream relative to the current position. If the stream is not
/// seekable, it tries to simulates advancing the position by reading or writing 0-bytes asynchronously.
/// </summary>
/// <param name="offset">A byte offset relative to the origin parameter.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
public async Task MoveAsync(long offset,
CancellationToken cancellationToken = default)
=> await BaseStream.MoveAsync(offset, cancellationToken);
/// <summary>
/// Sets the position within the underlying stream relative to the current position.
/// </summary>
......
......@@ -96,6 +96,41 @@ namespace Syroot.BinaryData
}
}
/// <summary>
/// Sets the position within the current <paramref name="stream"/> relative to the current position. If the
/// stream is not seekable, it tries to simulates advancing the position by reading or writing 0-bytes
/// asynchronously.
/// </summary>
/// <param name="stream">The extended <see cref="Stream"/> instance.</param>
/// <param name="offset">A byte offset relative to the origin parameter.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
public async static Task MoveAsync(this Stream stream, long offset,
CancellationToken cancellationToken = default)
{
if (stream.CanSeek)
{
// No need to run any simulation.
stream.Seek(offset);
}
else
{
// Impossible to simulate seeking backwards in non-seekable stream.
if (offset < 0)
throw new NotSupportedException("Cannot simulate moving backwards in a non-seekable stream.");
// Simulate move by reading or writing bytes.
if (stream.CanRead)
{
await stream.ReadBytesAsync((int)offset, cancellationToken);
}
else if (stream.CanWrite)
{
for (int i = 0; i < offset; i++)
await stream.WriteByteAsync(0, cancellationToken);
}
}
}
/// <summary>
/// Sets the position within the current <paramref name="stream"/> relative to the current position.
/// </summary>
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment