diff --git a/src/Yarhl.UnitTests/IO/BinaryFormatTests.cs b/src/Yarhl.UnitTests/IO/BinaryFormatTests.cs index 7e32f581..ec64ea20 100644 --- a/src/Yarhl.UnitTests/IO/BinaryFormatTests.cs +++ b/src/Yarhl.UnitTests/IO/BinaryFormatTests.cs @@ -176,6 +176,29 @@ public void MemoryConstructor() format.Dispose(); } + [Test] + public void ConstructorFromFile() + { + string tempFile = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); + File.WriteAllBytes(tempFile, new byte[] { 0xCA, 0xFE }); + + try { + using var format = new BinaryFormat(tempFile, FileOpenMode.ReadWrite); + Assert.That(format.Stream.BaseStream, Is.InstanceOf()); + Assert.That(format.Stream.Position, Is.EqualTo(0)); + Assert.That(format.Stream.Length, Is.EqualTo(2)); + Assert.That(format.Stream.ReadByte(), Is.EqualTo(0xCA)); + } finally { + File.Delete(tempFile); + } + } + + [Test] + public void ConstructorFromFileInvalidParams() + { + Assert.That(() => new BinaryFormat(null, FileOpenMode.Read), Throws.ArgumentNullException); + } + [Test] public void Clone() { diff --git a/src/Yarhl/IO/BinaryFormat.cs b/src/Yarhl/IO/BinaryFormat.cs index b5ec5c49..0ec00791 100644 --- a/src/Yarhl/IO/BinaryFormat.cs +++ b/src/Yarhl/IO/BinaryFormat.cs @@ -46,8 +46,7 @@ public BinaryFormat() /// public BinaryFormat(Stream stream) { - if (stream == null) - throw new ArgumentNullException(nameof(stream)); + ArgumentNullException.ThrowIfNull(stream); Stream = stream as DataStream ?? DataStreamFactory.FromStream(stream); } @@ -67,16 +66,30 @@ public BinaryFormat(Stream stream) /// Length of the substream. public BinaryFormat(Stream stream, long offset, long length) { - if (stream == null) - throw new ArgumentNullException(nameof(stream)); - if (offset < 0 || offset > stream.Length) + ArgumentNullException.ThrowIfNull(stream); + if (offset < 0 || offset > stream.Length) { throw new ArgumentOutOfRangeException(nameof(offset)); - if (length < 0 || offset + length > stream.Length) + } + + if (length < 0 || offset + length > stream.Length) { throw new ArgumentOutOfRangeException(nameof(length)); + } Stream = DataStreamFactory.FromStream(stream, offset, length); } + /// + /// Initializes a new instance of the class. + /// + /// The path of the file. + /// The mode to open the file. + public BinaryFormat(string path, FileOpenMode mode) + { + ArgumentNullException.ThrowIfNull(path); + + Stream = DataStreamFactory.FromFile(path, mode); + } + /// /// Gets the stream. /// @@ -126,8 +139,9 @@ public void Dispose() /// protected virtual void Dispose(bool disposing) { - if (Disposed) + if (Disposed) { return; + } Disposed = true; if (disposing) {