2020-12-08 00:13:22 -08:00
|
|
|
|
using System.IO;
|
2020-12-07 22:32:37 -08:00
|
|
|
|
|
|
|
|
|
|
namespace SabreTools.IO
|
|
|
|
|
|
{
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
|
/// Extensions to Stream functionality
|
|
|
|
|
|
/// </summary>
|
|
|
|
|
|
public static class StreamExtensions
|
|
|
|
|
|
{
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
|
/// Seek to a specific point in the stream, if possible
|
|
|
|
|
|
/// </summary>
|
|
|
|
|
|
/// <param name="input">Input stream to try seeking on</param>
|
|
|
|
|
|
/// <param name="offset">Optional offset to seek to</param>
|
|
|
|
|
|
public static long SeekIfPossible(this Stream input, long offset = 0)
|
|
|
|
|
|
{
|
2021-01-29 10:49:27 -08:00
|
|
|
|
// If the stream is null, don't even try
|
|
|
|
|
|
if (input == null)
|
|
|
|
|
|
return -1;
|
2021-09-08 22:52:23 -07:00
|
|
|
|
|
2021-01-29 10:49:27 -08:00
|
|
|
|
// If the input is not seekable, just return the current position
|
|
|
|
|
|
if (!input.CanSeek)
|
2021-09-08 22:52:23 -07:00
|
|
|
|
{
|
|
|
|
|
|
try
|
|
|
|
|
|
{
|
|
|
|
|
|
return input.Position;
|
|
|
|
|
|
}
|
|
|
|
|
|
catch
|
|
|
|
|
|
{
|
|
|
|
|
|
return -1;
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
2021-01-29 10:49:27 -08:00
|
|
|
|
// Attempt to seek to the offset
|
2020-12-07 22:32:37 -08:00
|
|
|
|
try
|
|
|
|
|
|
{
|
2021-01-29 10:49:27 -08:00
|
|
|
|
if (offset < 0)
|
|
|
|
|
|
return input.Seek(offset, SeekOrigin.End);
|
|
|
|
|
|
else if (offset >= 0)
|
|
|
|
|
|
return input.Seek(offset, SeekOrigin.Begin);
|
2020-12-07 22:32:37 -08:00
|
|
|
|
|
|
|
|
|
|
return input.Position;
|
|
|
|
|
|
}
|
2020-12-08 00:13:22 -08:00
|
|
|
|
catch
|
2020-12-07 22:32:37 -08:00
|
|
|
|
{
|
2020-12-08 00:13:22 -08:00
|
|
|
|
return -1;
|
2020-12-07 22:32:37 -08:00
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|