Skip to content

Commit

Permalink
Delete unnecessary seek from SetLengthInternal on Unix (#44097)
Browse files Browse the repository at this point in the history
Also, improve test coverage for FileStream.SetLength
  • Loading branch information
jkotas authored Nov 1, 2020
1 parent 8d007a7 commit c03edca
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 18 deletions.
23 changes: 23 additions & 0 deletions src/libraries/System.IO.FileSystem/tests/FileStream/SetLength.cs
Original file line number Diff line number Diff line change
Expand Up @@ -137,5 +137,28 @@ public void SetLengthShorter()
Assert.Equal(0, fs.Position);
}
}

[Fact]
public void SetLengthMaxValue()
{
using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
{
// Depending on the file system, this can:
// - Throw IOException : No space left on device
// - Throw ArgumentOutOfRangeException : Specified file length was too large for the file system.
// - Succeed.
try
{
fs.SetLength(long.MaxValue);
}
catch (Exception e)
{
Assert.True(e is IOException || e is ArgumentOutOfRangeException, $"Unexpected exception {e}");
return;
}

Assert.Equal(long.MaxValue, fs.Length);
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ public void TooLargeCapacity_Unix()
// due to differences in OS behaviors and Unix not actually having a notion of
// a view separate from a map. It could also come from CreateNew, depending
// on what backing store is being used.
Assert.Throws<IOException>(() =>
AssertExtensions.ThrowsAny<IOException, ArgumentOutOfRangeException>(() =>
{
using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(null, (IntPtr.Size == 4) ? uint.MaxValue : long.MaxValue))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -401,28 +401,14 @@ private void SetLengthInternal(long value)
throw new IOException(SR.IO_SetLengthAppendTruncate);
}

long origPos = _filePosition;

VerifyOSHandlePosition();

if (_filePosition != value)
{
SeekCore(_fileHandle, value, SeekOrigin.Begin);
}

CheckFileCall(Interop.Sys.FTruncate(_fileHandle, value));

// Return file pointer to where it was before setting length
if (origPos != value)
// Set file pointer to end of file
if (_filePosition > value)
{
if (origPos < value)
{
SeekCore(_fileHandle, origPos, SeekOrigin.Begin);
}
else
{
SeekCore(_fileHandle, 0, SeekOrigin.End);
}
SeekCore(_fileHandle, 0, SeekOrigin.End);
}
}

Expand Down

0 comments on commit c03edca

Please sign in to comment.