Skip to content

Commit

Permalink
🐛 WriteTo truncates output file
Browse files Browse the repository at this point in the history
  • Loading branch information
pleonex committed Nov 28, 2023
1 parent 49038fe commit c93e32e
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 9 deletions.
43 changes: 35 additions & 8 deletions src/Yarhl.UnitTests/IO/DataStreamTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1368,17 +1368,44 @@ public void WriteToWhenLengthZeroCreatesEmptyFile()
{
string tempFile = Path.Combine(
Path.GetTempPath(),
Path.GetRandomFileName(),
Path.GetRandomFileName());

DataStream stream = new DataStream();
stream.WriteTo(tempFile);
try {
var stream = new DataStream();
stream.WriteTo(tempFile);

Assert.That(File.Exists(tempFile), Is.True);
FileStream fs = new FileStream(tempFile, FileMode.Open, FileAccess.Read);
Assert.AreEqual(0, fs.Length);
fs.Dispose();
File.Delete(tempFile);
Assert.That(File.Exists(tempFile), Is.True);

using var fs = new FileStream(tempFile, FileMode.Open, FileAccess.Read);
Assert.That(fs.Length, Is.EqualTo(0));
} finally {
File.Delete(tempFile);
}
}

[Test]
public void WriteToWhenTruncatesExistingFile()
{
string tempFile = Path.Combine(
Path.GetTempPath(),
Path.GetRandomFileName());

byte[] expected = new byte[] { 0xCA, 0xFE };
using var stream = new DataStream();
stream.Write(expected);

try {
// Pre-fill the output file with some long content
File.WriteAllText(tempFile, "hello world!");

// Overwrite with 2 bytes stream content
stream.WriteTo(tempFile);

byte[] actual = File.ReadAllBytes(tempFile);
Assert.That(actual, Is.EquivalentTo(expected));
} finally {
File.Delete(tempFile);
}
}

[Test]
Expand Down
2 changes: 1 addition & 1 deletion src/Yarhl/IO/DataStream.cs
Original file line number Diff line number Diff line change
Expand Up @@ -616,7 +616,7 @@ public void WriteSegmentTo(long start, long length, string fileOut)
}

// We use FileStream so it creates a file even when the length is zero
using var segment = new FileStream(fileOut, FileMode.OpenOrCreate, FileAccess.Write);
using var segment = new FileStream(fileOut, FileMode.Create, FileAccess.Write);
WriteSegmentTo(start, length, segment);
}

Expand Down

0 comments on commit c93e32e

Please sign in to comment.