<Link>Common\System\IO\Compression\ZipTestHelper.cs</Link>
</Compile>
</ItemGroup>
- <ItemGroup Condition="'$(TargetsNetCoreApp)' == 'true'">
- <Compile Include="ZipFile.Extract.netcoreapp.cs" />
- </ItemGroup>
<!--
Manually copy the contentFiles over as on macOS 10.12 unicode characters cause items to be flagged with buildaction compile.
TODO: Remove when macOS 10.12 support ended.
namespace System.IO.Compression.Tests
{
- public partial class ZipFile_Extract : ZipFileTestBase
+ public class ZipFile_Extract : ZipFileTestBase
{
[Theory]
[InlineData("normal.zip", "normal")]
Assert.Equal(1, results.Length);
Assert.Equal(fileName, Path.GetFileName(results[0]));
}
+
+ [Fact]
+ public void ExtractToDirectoryOverwrite()
+ {
+ string zipFileName = zfile("normal.zip");
+ string folderName = zfolder("normal");
+
+ using (var tempFolder = new TempDirectory(GetTestFilePath()))
+ {
+ ZipFile.ExtractToDirectory(zipFileName, tempFolder.Path, overwriteFiles: false);
+ Assert.Throws<IOException>(() => ZipFile.ExtractToDirectory(zipFileName, tempFolder.Path /* default false */));
+ Assert.Throws<IOException>(() => ZipFile.ExtractToDirectory(zipFileName, tempFolder.Path, overwriteFiles: false));
+ ZipFile.ExtractToDirectory(zipFileName, tempFolder.Path, overwriteFiles: true);
+
+ DirsEqual(tempFolder.Path, folderName);
+ }
+ }
+
+ [Fact]
+ public void ExtractToDirectoryOverwriteEncoding()
+ {
+ string zipFileName = zfile("normal.zip");
+ string folderName = zfolder("normal");
+
+ using (var tempFolder = new TempDirectory(GetTestFilePath()))
+ {
+ ZipFile.ExtractToDirectory(zipFileName, tempFolder.Path, Encoding.UTF8, overwriteFiles: false);
+ Assert.Throws<IOException>(() => ZipFile.ExtractToDirectory(zipFileName, tempFolder.Path, Encoding.UTF8 /* default false */));
+ Assert.Throws<IOException>(() => ZipFile.ExtractToDirectory(zipFileName, tempFolder.Path, Encoding.UTF8, overwriteFiles: false));
+ ZipFile.ExtractToDirectory(zipFileName, tempFolder.Path, Encoding.UTF8, overwriteFiles: true);
+
+ DirsEqual(tempFolder.Path, folderName);
+ }
+ }
+
+ [Fact]
+ public void ExtractToDirectoryZipArchiveOverwrite()
+ {
+ string zipFileName = zfile("normal.zip");
+ string folderName = zfolder("normal");
+
+ using (var tempFolder = new TempDirectory(GetTestFilePath()))
+ {
+ using (ZipArchive archive = ZipFile.Open(zipFileName, ZipArchiveMode.Read))
+ {
+ archive.ExtractToDirectory(tempFolder.Path);
+ Assert.Throws<IOException>(() => archive.ExtractToDirectory(tempFolder.Path /* default false */));
+ Assert.Throws<IOException>(() => archive.ExtractToDirectory(tempFolder.Path, overwriteFiles: false));
+ archive.ExtractToDirectory(tempFolder.Path, overwriteFiles: true);
+
+ DirsEqual(tempFolder.Path, folderName);
+ }
+ }
+ }
}
}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Text;
-using Xunit;
-
-namespace System.IO.Compression.Tests
-{
- public partial class ZipFile_Extract : ZipFileTestBase
- {
- [Fact]
- public void ExtractToDirectoryOverwrite()
- {
- string zipFileName = zfile("normal.zip");
- string folderName = zfolder("normal");
-
- using (var tempFolder = new TempDirectory(GetTestFilePath()))
- {
- ZipFile.ExtractToDirectory(zipFileName, tempFolder.Path, overwriteFiles: false);
- Assert.Throws<IOException>(() => ZipFile.ExtractToDirectory(zipFileName, tempFolder.Path /* default false */));
- Assert.Throws<IOException>(() => ZipFile.ExtractToDirectory(zipFileName, tempFolder.Path, overwriteFiles: false));
- ZipFile.ExtractToDirectory(zipFileName, tempFolder.Path, overwriteFiles: true);
-
- DirsEqual(tempFolder.Path, folderName);
- }
- }
-
- [Fact]
- public void ExtractToDirectoryOverwriteEncoding()
- {
- string zipFileName = zfile("normal.zip");
- string folderName = zfolder("normal");
-
- using (var tempFolder = new TempDirectory(GetTestFilePath()))
- {
- ZipFile.ExtractToDirectory(zipFileName, tempFolder.Path, Encoding.UTF8, overwriteFiles: false);
- Assert.Throws<IOException>(() => ZipFile.ExtractToDirectory(zipFileName, tempFolder.Path, Encoding.UTF8 /* default false */));
- Assert.Throws<IOException>(() => ZipFile.ExtractToDirectory(zipFileName, tempFolder.Path, Encoding.UTF8, overwriteFiles: false));
- ZipFile.ExtractToDirectory(zipFileName, tempFolder.Path, Encoding.UTF8, overwriteFiles: true);
-
- DirsEqual(tempFolder.Path, folderName);
- }
- }
-
- [Fact]
- public void ExtractToDirectoryZipArchiveOverwrite()
- {
- string zipFileName = zfile("normal.zip");
- string folderName = zfolder("normal");
-
- using (var tempFolder = new TempDirectory(GetTestFilePath()))
- {
- using (ZipArchive archive = ZipFile.Open(zipFileName, ZipArchiveMode.Read))
- {
- archive.ExtractToDirectory(tempFolder.Path);
- Assert.Throws<IOException>(() => archive.ExtractToDirectory(tempFolder.Path /* default false */));
- Assert.Throws<IOException>(() => archive.ExtractToDirectory(tempFolder.Path, overwriteFiles: false));
- archive.ExtractToDirectory(tempFolder.Path, overwriteFiles: true);
-
- DirsEqual(tempFolder.Path, folderName);
- }
- }
- }
- }
-}
<Compile Include="System\IO\Compression\Crc32Helper.ZLib.cs" />
<Compile Include="System\IO\Compression\GZipStream.cs" />
<Compile Include="System\IO\Compression\PositionPreservingWriteOnlyStreamWrapper.cs" />
- <Compile Include="System\IO\Compression\PositionPreservingWriteOnlyStreamWrapper.netcoreapp.cs" />
- <Compile Include="System\IO\Compression\ZipArchiveEntry.netcoreapp.cs" />
- <Compile Include="System\IO\Compression\ZipCustomStreams.netcoreapp.cs" />
<Compile Include="$(CommonPath)\CoreLib\System\IO\StreamHelpers.CopyValidation.cs">
<Link>Common\CoreLib\System\IO\StreamHelpers.CopyValidation.cs</Link>
</Compile>
namespace System.IO.Compression
{
- internal sealed partial class PositionPreservingWriteOnlyStreamWrapper : Stream
+ internal sealed class PositionPreservingWriteOnlyStreamWrapper : Stream
{
private readonly Stream _stream;
private long _position;
_stream.Write(buffer, offset, count);
}
+ public override void Write(ReadOnlySpan<byte> buffer)
+ {
+ _position += buffer.Length;
+ _stream.Write(buffer);
+ }
+
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object? state)
{
_position += count;
return _stream.WriteAsync(buffer, offset, count, cancellationToken);
}
+ public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default(CancellationToken))
+ {
+ _position += buffer.Length;
+ return _stream.WriteAsync(buffer, cancellationToken);
+ }
+
public override bool CanTimeout => _stream.CanTimeout;
public override int ReadTimeout
{
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Threading;
-using System.Threading.Tasks;
-
-namespace System.IO.Compression
-{
- internal sealed partial class PositionPreservingWriteOnlyStreamWrapper : Stream
- {
- public override void Write(ReadOnlySpan<byte> buffer)
- {
- _position += buffer.Length;
- _stream.Write(buffer);
- }
-
- public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default(CancellationToken))
- {
- _position += buffer.Length;
- return _stream.WriteAsync(buffer, cancellationToken);
- }
- }
-}
return path;
}
- private sealed partial class DirectToArchiveWriterStream : Stream
+ private sealed class DirectToArchiveWriterStream : Stream
{
private long _position;
private readonly CheckSumAndSizeWriteStream _crcSizeStream;
_position += count;
}
+ public override void Write(ReadOnlySpan<byte> source)
+ {
+ ThrowIfDisposed();
+ Debug.Assert(CanWrite);
+
+ // if we're not actually writing anything, we don't want to trigger the header
+ if (source.Length == 0)
+ return;
+
+ if (!_everWritten)
+ {
+ _everWritten = true;
+ // write local header, we are good to go
+ _usedZip64inLH = _entry.WriteLocalFileHeader(isEmptyFile: false);
+ }
+
+ _crcSizeStream.Write(source);
+ _position += source.Length;
+ }
+
public override void Flush()
{
ThrowIfDisposed();
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Diagnostics;
-
-namespace System.IO.Compression
-{
- public partial class ZipArchiveEntry
- {
- private sealed partial class DirectToArchiveWriterStream : Stream
- {
- public override void Write(ReadOnlySpan<byte> source)
- {
- ThrowIfDisposed();
- Debug.Assert(CanWrite);
-
- // if we're not actually writing anything, we don't want to trigger the header
- if (source.Length == 0)
- return;
-
- if (!_everWritten)
- {
- _everWritten = true;
- // write local header, we are good to go
- _usedZip64inLH = _entry.WriteLocalFileHeader(isEmptyFile: false);
- }
-
- _crcSizeStream.Write(source);
- _position += source.Length;
- }
- }
- }
-}
namespace System.IO.Compression
{
- internal sealed partial class WrappedStream : Stream
+ internal sealed class WrappedStream : Stream
{
private readonly Stream _baseStream;
private readonly bool _closeBaseStream;
_baseStream.Write(buffer, offset, count);
}
+ public override void Write(ReadOnlySpan<byte> source)
+ {
+ ThrowIfDisposed();
+ ThrowIfCantWrite();
+
+ _baseStream.Write(source);
+ }
+
public override void Flush()
{
ThrowIfDisposed();
}
}
- internal sealed partial class SubReadStream : Stream
+ internal sealed class SubReadStream : Stream
{
private readonly long _startInSuperStream;
private long _positionInSuperStream;
return ret;
}
+ public override int Read(Span<byte> destination)
+ {
+ // parameter validation sent to _superStream.Read
+ int origCount = destination.Length;
+ int count = destination.Length;
+
+ ThrowIfDisposed();
+ ThrowIfCantRead();
+
+ if (_superStream.Position != _positionInSuperStream)
+ _superStream.Seek(_positionInSuperStream, SeekOrigin.Begin);
+ if (_positionInSuperStream + count > _endInSuperStream)
+ count = (int)(_endInSuperStream - _positionInSuperStream);
+
+ Debug.Assert(count >= 0);
+ Debug.Assert(count <= origCount);
+
+ int ret = _superStream.Read(destination.Slice(0, count));
+
+ _positionInSuperStream += ret;
+ return ret;
+ }
+
public override long Seek(long offset, SeekOrigin origin)
{
ThrowIfDisposed();
}
}
- internal sealed partial class CheckSumAndSizeWriteStream : Stream
+ internal sealed class CheckSumAndSizeWriteStream : Stream
{
private readonly Stream _baseStream;
private readonly Stream _baseBaseStream;
_position += count;
}
+ public override void Write(ReadOnlySpan<byte> source)
+ {
+ // if we're not actually writing anything, we don't want to trigger as if we did write something
+ ThrowIfDisposed();
+ Debug.Assert(CanWrite);
+
+ if (source.Length == 0)
+ return;
+
+ if (!_everWritten)
+ {
+ _initialPosition = _baseBaseStream.Position;
+ _everWritten = true;
+ }
+
+ _checksum = Crc32Helper.UpdateCrc32(_checksum, source);
+ _baseStream.Write(source);
+ _position += source.Length;
+ }
+
public override void Flush()
{
ThrowIfDisposed();
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Diagnostics;
-
-namespace System.IO.Compression
-{
- internal sealed partial class WrappedStream : Stream
- {
- public override void Write(ReadOnlySpan<byte> source)
- {
- ThrowIfDisposed();
- ThrowIfCantWrite();
-
- _baseStream.Write(source);
- }
- }
-
- internal sealed partial class SubReadStream : Stream
- {
- public override int Read(Span<byte> destination)
- {
- // parameter validation sent to _superStream.Read
- int origCount = destination.Length;
- int count = destination.Length;
-
- ThrowIfDisposed();
- ThrowIfCantRead();
-
- if (_superStream.Position != _positionInSuperStream)
- _superStream.Seek(_positionInSuperStream, SeekOrigin.Begin);
- if (_positionInSuperStream + count > _endInSuperStream)
- count = (int)(_endInSuperStream - _positionInSuperStream);
-
- Debug.Assert(count >= 0);
- Debug.Assert(count <= origCount);
-
- int ret = _superStream.Read(destination.Slice(0, count));
-
- _positionInSuperStream += ret;
- return ret;
- }
- }
-
- internal sealed partial class CheckSumAndSizeWriteStream : Stream
- {
- public override void Write(ReadOnlySpan<byte> source)
- {
- // if we're not actually writing anything, we don't want to trigger as if we did write something
- ThrowIfDisposed();
- Debug.Assert(CanWrite);
-
- if (source.Length == 0)
- return;
-
- if (!_everWritten)
- {
- _initialPosition = _baseBaseStream.Position;
- _everWritten = true;
- }
-
- _checksum = Crc32Helper.UpdateCrc32(_checksum, source);
- _baseStream.Write(source);
- _position += source.Length;
- }
- }
-}
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using System;
using System.Collections.Generic;
using System.Linq;
using System.IO.Enumeration;
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using System.IO.Enumeration;
using System.Linq;
using Xunit;
// See the LICENSE file in the project root for more information.
using Xunit;
-using System.Linq;
namespace System.IO.Tests
{
- public partial class File_Move : FileSystemTest
+ public class File_Move : FileSystemTest
{
#region Utilities
File.Move(sourceFile, destFile);
}
+ protected virtual void Move(string sourceFile, string destFile, bool overwrite)
+ {
+ File.Move(sourceFile, destFile, overwrite);
+ }
+
+ private void MoveDestinationFileDoesNotExist(bool overwrite)
+ {
+ string srcPath = GetTestFilePath();
+ string destPath = GetTestFilePath();
+
+ byte[] srcContents = new byte[] { 1, 2, 3, 4, 5 };
+ File.WriteAllBytes(srcPath, srcContents);
+
+ Move(srcPath, destPath, overwrite);
+
+ Assert.False(File.Exists(srcPath));
+ Assert.Equal(srcContents, File.ReadAllBytes(destPath));
+ }
+
#endregion
#region UniversalTests
Assert.Throws<IOException>(() => Move(testFileAlternateStream, testFile2));
}
#endregion
+
+ [Fact]
+ public void BasicMoveWithOverwriteFileExists()
+ {
+ string srcPath = GetTestFilePath();
+ string destPath = GetTestFilePath();
+
+ byte[] srcContents = new byte[] { 1, 2, 3, 4, 5 };
+ byte[] destContents = new byte[] { 6, 7, 8, 9, 10 };
+ File.WriteAllBytes(srcPath, srcContents);
+ File.WriteAllBytes(destPath, destContents);
+
+ Move(srcPath, destPath, true);
+
+ Assert.False(File.Exists(srcPath));
+ Assert.Equal(srcContents, File.ReadAllBytes(destPath));
+ }
+
+ [Fact]
+ public void BasicMoveWithOverwriteFileDoesNotExist()
+ {
+ MoveDestinationFileDoesNotExist(true);
+ }
+
+ [Fact]
+ public void BasicMoveWithoutOverwriteFileDoesNotExist()
+ {
+ MoveDestinationFileDoesNotExist(false);
+ }
+
+ [Fact]
+ public void MoveOntoExistingFileNoOverwrite()
+ {
+ string srcPath = GetTestFilePath();
+ string destPath = GetTestFilePath();
+
+ byte[] srcContents = new byte[] { 1, 2, 3, 4, 5 };
+ byte[] destContents = new byte[] { 6, 7, 8, 9, 10 };
+ File.WriteAllBytes(srcPath, srcContents);
+ File.WriteAllBytes(destPath, destContents);
+
+ Assert.Throws<IOException>(() => Move(srcPath, destPath, false));
+ Assert.True(File.Exists(srcPath));
+ Assert.True(File.Exists(destPath));
+ Assert.Equal(destContents, File.ReadAllBytes(destPath));
+ }
}
}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using Xunit;
-using System.Linq;
-
-namespace System.IO.Tests
-{
- public partial class File_Move
- {
- #region Utilities
-
- protected virtual void Move(string sourceFile, string destFile, bool overwrite)
- {
- File.Move(sourceFile, destFile, overwrite);
- }
-
- private void MoveDestinationFileDoesNotExist(bool overwrite)
- {
- string srcPath = GetTestFilePath();
- string destPath = GetTestFilePath();
-
- byte[] srcContents = new byte[] { 1, 2, 3, 4, 5 };
- File.WriteAllBytes(srcPath, srcContents);
-
- Move(srcPath, destPath, overwrite);
-
- Assert.False(File.Exists(srcPath));
- Assert.Equal(srcContents, File.ReadAllBytes(destPath));
- }
-
- #endregion
-
- [Fact]
- public void BasicMoveWithOverwriteFileExists()
- {
- string srcPath = GetTestFilePath();
- string destPath = GetTestFilePath();
-
- byte[] srcContents = new byte[] { 1, 2, 3, 4, 5 };
- byte[] destContents = new byte[] { 6, 7, 8, 9, 10 };
- File.WriteAllBytes(srcPath, srcContents);
- File.WriteAllBytes(destPath, destContents);
-
- Move(srcPath, destPath, true);
-
- Assert.False(File.Exists(srcPath));
- Assert.Equal(srcContents, File.ReadAllBytes(destPath));
- }
-
- [Fact]
- public void BasicMoveWithOverwriteFileDoesNotExist()
- {
- MoveDestinationFileDoesNotExist(true);
- }
-
- [Fact]
- public void BasicMoveWithoutOverwriteFileDoesNotExist()
- {
- MoveDestinationFileDoesNotExist(false);
- }
-
- [Fact]
- public void MoveOntoExistingFileNoOverwrite()
- {
- string srcPath = GetTestFilePath();
- string destPath = GetTestFilePath();
-
- byte[] srcContents = new byte[] { 1, 2, 3, 4, 5 };
- byte[] destContents = new byte[] { 6, 7, 8, 9, 10 };
- File.WriteAllBytes(srcPath, srcContents);
- File.WriteAllBytes(destPath, destContents);
-
- Assert.Throws<IOException>(() => Move(srcPath, destPath, false));
- Assert.True(File.Exists(srcPath));
- Assert.True(File.Exists(destPath));
- Assert.Equal(destContents, File.ReadAllBytes(destPath));
- }
- }
-}
namespace System.IO.Tests
{
- public partial class FileInfo_MoveTo : File_Move
+ public class FileInfo_MoveTo : File_Move
{
protected override void Move(string sourceFile, string destFile)
{
new FileInfo(sourceFile).MoveTo(destFile);
}
+ protected override void Move(string sourceFile, string destFile, bool overwrite)
+ {
+ new FileInfo(sourceFile).MoveTo(destFile, overwrite);
+ }
+
[Fact]
public override void NonExistentPath()
{
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using Xunit;
-
-namespace System.IO.Tests
-{
- public partial class FileInfo_MoveTo
- {
- protected override void Move(string sourceFile, string destFile, bool overwrite)
- {
- new FileInfo(sourceFile).MoveTo(destFile, overwrite);
- }
- }
-}
<Compile Include="File\GetSetAttributesCommon.cs" />
<Compile Include="File\Replace.cs" />
<Compile Include="File\AppendAsync.cs" />
- <Compile Include="File\Move.netcoreapp.cs" />
<Compile Include="File\ReadWriteAllLinesAsync.cs" />
<Compile Include="File\ReadWriteAllBytesAsync.cs" />
<Compile Include="File\ReadWriteAllTextAsync.cs" />
- <Compile Include="FileInfo\MoveTo.netcoreapp.cs" />
- <Compile Include="FileStream\DisposeAsync.netcoreapp.cs" />
- <Compile Include="FileStream\ReadWriteSpan.netcoreapp.cs" />
- <Compile Include="Enumeration\ConstructionTests.netcoreapp.cs" />
- <Compile Include="Enumeration\SpecialDirectoryTests.netcoreapp.cs" />
- <Compile Include="Enumeration\SkipAttributeTests.netcoreapp.cs" />
- <Compile Include="Enumeration\FileSystemNameTests.netcoreapp.cs" />
- <Compile Include="Enumeration\MatchCasingTests.netcoreapp.cs" />
- <Compile Include="Enumeration\TrimmedPaths.netcoreapp.cs" />
- <Compile Include="Enumeration\ErrorHandlingTests.netcoreapp.cs" />
- <Compile Include="Enumeration\IncludePredicateTests.netcoreapp.cs" />
- <Compile Include="Enumeration\PatternTransformTests.netcoreapp.cs" />
- <Compile Include="Enumeration\RootTests.netcoreapp.cs" />
- <Compile Include="Enumeration\AttributeTests.netcoreapp.cs" />
- <Compile Include="Enumeration\MatchTypesTests.netcoreapp.cs" />
- <Compile Include="Enumeration\ExampleTests.netcoreapp.cs" />
- <Compile Include="Enumeration\RemovedDirectoryTests.netcoreapp.cs" />
+ <Compile Include="FileStream\DisposeAsync.cs" />
+ <Compile Include="FileStream\ReadWriteSpan.cs" />
+ <Compile Include="Enumeration\ConstructionTests.cs" />
+ <Compile Include="Enumeration\SpecialDirectoryTests.cs" />
+ <Compile Include="Enumeration\SkipAttributeTests.cs" />
+ <Compile Include="Enumeration\FileSystemNameTests.cs" />
+ <Compile Include="Enumeration\MatchCasingTests.cs" />
+ <Compile Include="Enumeration\TrimmedPaths.cs" />
+ <Compile Include="Enumeration\ErrorHandlingTests.cs" />
+ <Compile Include="Enumeration\IncludePredicateTests.cs" />
+ <Compile Include="Enumeration\PatternTransformTests.cs" />
+ <Compile Include="Enumeration\RootTests.cs" />
+ <Compile Include="Enumeration\AttributeTests.cs" />
+ <Compile Include="Enumeration\MatchTypesTests.cs" />
+ <Compile Include="Enumeration\ExampleTests.cs" />
+ <Compile Include="Enumeration\RemovedDirectoryTests.cs" />
</ItemGroup>
<ItemGroup Condition="'$(TargetsUnix)' == 'true'">
<Compile Include="FileSystemTest.Unix.cs" />
<ItemGroup>
<Compile Include="System\IO\IsolatedStorage\IdentityTests.cs" />
<Compile Include="System\IO\IsolatedStorage\IsolatedStorageBaseClassTests.cs" />
- <Compile Include="System\IO\IsolatedStorage\IsolatedStorageFileStreamTests.netcoreapp.cs" />
+ <Compile Include="System\IO\IsolatedStorage\IsolatedStorageFileStreamTests.cs" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\src\System\IO\IsolatedStorage\Helper.Win32Unix.cs">
namespace System.IO.IsolatedStorage
{
- public partial class IsolatedStorageFileStreamTests : IsoStorageTest
+ public class IsolatedStorageFileStreamTests : IsoStorageTest
{
[Theory, MemberData(nameof(ValidStores))]
public async Task DisposeAsync_MultipleInvokes_Idempotent(PresetScopes scope)
/// Tests that cover Read and ReadAsync behaviors that are shared between
/// AnonymousPipes and NamedPipes
/// </summary>
- public abstract partial class PipeTest_Read : PipeTestBase
+ public abstract class PipeTest_Read : PipeTestBase
{
public virtual bool SupportsBidirectionalReadingWriting => false;
}
}
}
+
+ [Fact]
+ public void WriteToReadOnlyPipe_Span_Throws_NotSupportedException()
+ {
+ if (SupportsBidirectionalReadingWriting)
+ {
+ return;
+ }
+
+ using (ServerClientPair pair = CreateServerClientPair())
+ {
+ PipeStream pipe = pair.readablePipe;
+ Assert.True(pipe.IsConnected);
+ Assert.False(pipe.CanWrite);
+ Assert.False(pipe.CanSeek);
+
+ Assert.Throws<NotSupportedException>(() => pipe.Write(new ReadOnlySpan<byte>(new byte[5])));
+ Assert.Throws<NotSupportedException>(() => { pipe.WriteAsync(new ReadOnlyMemory<byte>(new byte[5])); });
+ }
+ }
+
+ [Fact]
+ public async Task ReadWithZeroLengthBuffer_Span_Nop()
+ {
+ using (ServerClientPair pair = CreateServerClientPair())
+ {
+ PipeStream pipe = pair.readablePipe;
+ var buffer = new byte[] { };
+
+ Assert.Equal(0, pipe.Read(new Span<byte>(buffer)));
+ ValueTask<int> read = pipe.ReadAsync(new Memory<byte>(buffer));
+ Assert.Equal(0, await read);
+ }
+ }
+
+ [Fact]
+ public void ReadOnDisposedReadablePipe_Span_Throws_ObjectDisposedException()
+ {
+ using (ServerClientPair pair = CreateServerClientPair())
+ {
+ PipeStream pipe = pair.readablePipe;
+ pipe.Dispose();
+ byte[] buffer = new byte[] { 0, 0, 0, 0 };
+
+ Assert.Throws<ObjectDisposedException>(() => pipe.Read(new Span<byte>(buffer)));
+ Assert.Throws<ObjectDisposedException>(() => { pipe.ReadAsync(new Memory<byte>(buffer)); });
+ }
+ }
+
+ [Fact]
+ public virtual async Task ReadFromPipeWithClosedPartner_Span_ReadNoBytes()
+ {
+ using (ServerClientPair pair = CreateServerClientPair())
+ {
+ pair.writeablePipe.Dispose();
+ byte[] buffer = new byte[] { 0, 0, 0, 0 };
+
+ // The pipe won't be marked as Broken until the first read, so prime it
+ // to test both the case where it's not yet marked as "Broken" and then
+ // where it is.
+ Assert.Equal(0, pair.readablePipe.Read(new Span<byte>(buffer)));
+
+ Assert.Equal(0, pair.readablePipe.Read(new Span<byte>(buffer)));
+ Assert.Equal(0, await pair.readablePipe.ReadAsync(new Memory<byte>(buffer)));
+ }
+ }
+
+ [Fact]
+ public async Task ValidWriteAsync_Span_ValidReadAsync()
+ {
+ using (ServerClientPair pair = CreateServerClientPair())
+ {
+ Assert.True(pair.writeablePipe.IsConnected);
+ Assert.True(pair.readablePipe.IsConnected);
+
+ byte[] sent = new byte[] { 123, 0, 5 };
+ byte[] received = new byte[] { 0, 0, 0 };
+
+ ValueTask write = pair.writeablePipe.WriteAsync(new ReadOnlyMemory<byte>(sent));
+ Assert.Equal(sent.Length, await pair.readablePipe.ReadAsync(new Memory<byte>(received, 0, sent.Length)));
+ Assert.Equal(sent, received);
+ await write;
+ }
+ }
+
+ [Theory]
+ [OuterLoop]
+ [MemberData(nameof(AsyncReadWriteChain_MemberData))]
+ public async Task AsyncReadWriteChain_Span_ReadWrite(int iterations, int writeBufferSize, int readBufferSize, bool cancelableToken)
+ {
+ var writeBuffer = new byte[writeBufferSize];
+ var readBuffer = new byte[readBufferSize];
+ var rand = new Random();
+ var cancellationToken = cancelableToken ? new CancellationTokenSource().Token : CancellationToken.None;
+
+ using (ServerClientPair pair = CreateServerClientPair())
+ {
+ // Repeatedly and asynchronously write to the writable pipe and read from the readable pipe,
+ // verifying that the correct data made it through.
+ for (int iter = 0; iter < iterations; iter++)
+ {
+ rand.NextBytes(writeBuffer);
+ ValueTask writerTask = pair.writeablePipe.WriteAsync(new ReadOnlyMemory<byte>(writeBuffer), cancellationToken);
+
+ int totalRead = 0;
+ while (totalRead < writeBuffer.Length)
+ {
+ int numRead = await pair.readablePipe.ReadAsync(new Memory<byte>(readBuffer), cancellationToken);
+ Assert.True(numRead > 0);
+ Assert.Equal<byte>(
+ new ArraySegment<byte>(writeBuffer, totalRead, numRead),
+ new ArraySegment<byte>(readBuffer, 0, numRead));
+ totalRead += numRead;
+ }
+ Assert.Equal(writeBuffer.Length, totalRead);
+
+ await writerTask;
+ }
+ }
+ }
}
}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Threading;
-using System.Threading.Tasks;
-using Xunit;
-
-namespace System.IO.Pipes.Tests
-{
- public abstract partial class PipeTest_Read : PipeTestBase
- {
- [Fact]
- public void WriteToReadOnlyPipe_Span_Throws_NotSupportedException()
- {
- if (SupportsBidirectionalReadingWriting)
- {
- return;
- }
-
- using (ServerClientPair pair = CreateServerClientPair())
- {
- PipeStream pipe = pair.readablePipe;
- Assert.True(pipe.IsConnected);
- Assert.False(pipe.CanWrite);
- Assert.False(pipe.CanSeek);
-
- Assert.Throws<NotSupportedException>(() => pipe.Write(new ReadOnlySpan<byte>(new byte[5])));
- Assert.Throws<NotSupportedException>(() => { pipe.WriteAsync(new ReadOnlyMemory<byte>(new byte[5])); });
- }
- }
-
- [Fact]
- public async Task ReadWithZeroLengthBuffer_Span_Nop()
- {
- using (ServerClientPair pair = CreateServerClientPair())
- {
- PipeStream pipe = pair.readablePipe;
- var buffer = new byte[] { };
-
- Assert.Equal(0, pipe.Read(new Span<byte>(buffer)));
- ValueTask<int> read = pipe.ReadAsync(new Memory<byte>(buffer));
- Assert.Equal(0, await read);
- }
- }
-
- [Fact]
- public void ReadOnDisposedReadablePipe_Span_Throws_ObjectDisposedException()
- {
- using (ServerClientPair pair = CreateServerClientPair())
- {
- PipeStream pipe = pair.readablePipe;
- pipe.Dispose();
- byte[] buffer = new byte[] { 0, 0, 0, 0 };
-
- Assert.Throws<ObjectDisposedException>(() => pipe.Read(new Span<byte>(buffer)));
- Assert.Throws<ObjectDisposedException>(() => { pipe.ReadAsync(new Memory<byte>(buffer)); });
- }
- }
-
- [Fact]
- public virtual async Task ReadFromPipeWithClosedPartner_Span_ReadNoBytes()
- {
- using (ServerClientPair pair = CreateServerClientPair())
- {
- pair.writeablePipe.Dispose();
- byte[] buffer = new byte[] { 0, 0, 0, 0 };
-
- // The pipe won't be marked as Broken until the first read, so prime it
- // to test both the case where it's not yet marked as "Broken" and then
- // where it is.
- Assert.Equal(0, pair.readablePipe.Read(new Span<byte>(buffer)));
-
- Assert.Equal(0, pair.readablePipe.Read(new Span<byte>(buffer)));
- Assert.Equal(0, await pair.readablePipe.ReadAsync(new Memory<byte>(buffer)));
- }
- }
-
- [Fact]
- public async Task ValidWriteAsync_Span_ValidReadAsync()
- {
- using (ServerClientPair pair = CreateServerClientPair())
- {
- Assert.True(pair.writeablePipe.IsConnected);
- Assert.True(pair.readablePipe.IsConnected);
-
- byte[] sent = new byte[] { 123, 0, 5 };
- byte[] received = new byte[] { 0, 0, 0 };
-
- ValueTask write = pair.writeablePipe.WriteAsync(new ReadOnlyMemory<byte>(sent));
- Assert.Equal(sent.Length, await pair.readablePipe.ReadAsync(new Memory<byte>(received, 0, sent.Length)));
- Assert.Equal(sent, received);
- await write;
- }
- }
-
- [Theory]
- [OuterLoop]
- [MemberData(nameof(AsyncReadWriteChain_MemberData))]
- public async Task AsyncReadWriteChain_Span_ReadWrite(int iterations, int writeBufferSize, int readBufferSize, bool cancelableToken)
- {
- var writeBuffer = new byte[writeBufferSize];
- var readBuffer = new byte[readBufferSize];
- var rand = new Random();
- var cancellationToken = cancelableToken ? new CancellationTokenSource().Token : CancellationToken.None;
-
- using (ServerClientPair pair = CreateServerClientPair())
- {
- // Repeatedly and asynchronously write to the writable pipe and read from the readable pipe,
- // verifying that the correct data made it through.
- for (int iter = 0; iter < iterations; iter++)
- {
- rand.NextBytes(writeBuffer);
- ValueTask writerTask = pair.writeablePipe.WriteAsync(new ReadOnlyMemory<byte>(writeBuffer), cancellationToken);
-
- int totalRead = 0;
- while (totalRead < writeBuffer.Length)
- {
- int numRead = await pair.readablePipe.ReadAsync(new Memory<byte>(readBuffer), cancellationToken);
- Assert.True(numRead > 0);
- Assert.Equal<byte>(
- new ArraySegment<byte>(writeBuffer, totalRead, numRead),
- new ArraySegment<byte>(readBuffer, 0, numRead));
- totalRead += numRead;
- }
- Assert.Equal(writeBuffer.Length, totalRead);
-
- await writerTask;
- }
- }
- }
- }
-}
/// Tests that cover Write and WriteAsync behaviors that are shared between
/// AnonymousPipes and NamedPipes
/// </summary>
- public abstract partial class PipeTest_Write : PipeTestBase
+ public abstract class PipeTest_Write : PipeTestBase
{
public virtual bool SupportsBidirectionalReadingWriting => false;
await pair.writeablePipe.FlushAsync();
}
}
+
+ [Fact]
+ public void ReadOnWriteOnlyPipe_Span_Throws_NotSupportedException()
+ {
+ if (SupportsBidirectionalReadingWriting)
+ {
+ return;
+ }
+
+ using (ServerClientPair pair = CreateServerClientPair())
+ {
+ PipeStream pipe = pair.writeablePipe;
+ Assert.True(pipe.IsConnected);
+ Assert.False(pipe.CanRead);
+
+ Assert.Throws<NotSupportedException>(() => pipe.Read(new Span<byte>(new byte[9])));
+ Assert.Throws<NotSupportedException>(() => { pipe.ReadAsync(new Memory<byte>(new byte[10])); });
+ }
+ }
+
+ [Fact]
+ public async Task WriteZeroLengthBuffer_Span_Nop()
+ {
+ using (ServerClientPair pair = CreateServerClientPair())
+ {
+ PipeStream pipe = pair.writeablePipe;
+
+ // Shouldn't throw
+ pipe.Write(new Span<byte>(Array.Empty<byte>()));
+ await pipe.WriteAsync(new Memory<byte>(Array.Empty<byte>()));
+ }
+ }
+
+ [Fact]
+ public void WriteToDisposedWriteablePipe_Span_Throws_ObjectDisposedException()
+ {
+ using (ServerClientPair pair = CreateServerClientPair())
+ {
+ PipeStream pipe = pair.writeablePipe;
+ pipe.Dispose();
+ byte[] buffer = new byte[] { 0, 0, 0, 0 };
+
+ Assert.Throws<ObjectDisposedException>(() => pipe.Write(new Span<byte>(buffer)));
+ Assert.Throws<ObjectDisposedException>(() => { pipe.WriteAsync(new Memory<byte>(buffer)); });
+ }
+ }
+
+ [Fact]
+ public virtual void WriteToPipeWithClosedPartner_Span_Throws_IOException()
+ {
+ using (ServerClientPair pair = CreateServerClientPair())
+ {
+ if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows) &&
+ (pair.readablePipe is NamedPipeClientStream || pair.writeablePipe is NamedPipeClientStream))
+ {
+ // On Unix, NamedPipe*Stream is implemented in term of sockets, where information
+ // about shutdown is not immediately propagated.
+ return;
+ }
+
+ pair.readablePipe.Dispose();
+ byte[] buffer = new byte[] { 0, 0, 0, 0 };
+
+ Assert.Throws<IOException>(() => pair.writeablePipe.Write(new Span<byte>(buffer)));
+ Assert.Throws<IOException>(() => { pair.writeablePipe.WriteAsync(new Memory<byte>(buffer)); });
+ }
+ }
+
+ [Fact]
+ public void DisposeAsync_NothingWrittenNeedsToBeFlushed_CompletesSynchronously()
+ {
+ ServerClientPair pair = CreateServerClientPair();
+ for (int i = 0; i < 2; i++)
+ {
+ Assert.True(pair.readablePipe.DisposeAsync().IsCompletedSuccessfully);
+ Assert.True(pair.writeablePipe.DisposeAsync().IsCompletedSuccessfully);
+ }
+ Assert.Throws<ObjectDisposedException>(() => pair.writeablePipe.Write(new Span<byte>(new byte[1])));
+ }
}
}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Runtime.InteropServices;
-using System.Threading.Tasks;
-using Xunit;
-
-namespace System.IO.Pipes.Tests
-{
- /// <summary>
- /// Tests that cover Write and WriteAsync behaviors that are shared between
- /// AnonymousPipes and NamedPipes
- /// </summary>
- public abstract partial class PipeTest_Write : PipeTestBase
- {
- [Fact]
- public void ReadOnWriteOnlyPipe_Span_Throws_NotSupportedException()
- {
- if (SupportsBidirectionalReadingWriting)
- {
- return;
- }
-
- using (ServerClientPair pair = CreateServerClientPair())
- {
- PipeStream pipe = pair.writeablePipe;
- Assert.True(pipe.IsConnected);
- Assert.False(pipe.CanRead);
-
- Assert.Throws<NotSupportedException>(() => pipe.Read(new Span<byte>(new byte[9])));
- Assert.Throws<NotSupportedException>(() => { pipe.ReadAsync(new Memory<byte>(new byte[10])); });
- }
- }
-
- [Fact]
- public async Task WriteZeroLengthBuffer_Span_Nop()
- {
- using (ServerClientPair pair = CreateServerClientPair())
- {
- PipeStream pipe = pair.writeablePipe;
-
- // Shouldn't throw
- pipe.Write(new Span<byte>(Array.Empty<byte>()));
- await pipe.WriteAsync(new Memory<byte>(Array.Empty<byte>()));
- }
- }
-
- [Fact]
- public void WriteToDisposedWriteablePipe_Span_Throws_ObjectDisposedException()
- {
- using (ServerClientPair pair = CreateServerClientPair())
- {
- PipeStream pipe = pair.writeablePipe;
- pipe.Dispose();
- byte[] buffer = new byte[] { 0, 0, 0, 0 };
-
- Assert.Throws<ObjectDisposedException>(() => pipe.Write(new Span<byte>(buffer)));
- Assert.Throws<ObjectDisposedException>(() => { pipe.WriteAsync(new Memory<byte>(buffer)); });
- }
- }
-
- [Fact]
- public virtual void WriteToPipeWithClosedPartner_Span_Throws_IOException()
- {
- using (ServerClientPair pair = CreateServerClientPair())
- {
- if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows) &&
- (pair.readablePipe is NamedPipeClientStream || pair.writeablePipe is NamedPipeClientStream))
- {
- // On Unix, NamedPipe*Stream is implemented in term of sockets, where information
- // about shutdown is not immediately propagated.
- return;
- }
-
- pair.readablePipe.Dispose();
- byte[] buffer = new byte[] { 0, 0, 0, 0 };
-
- Assert.Throws<IOException>(() => pair.writeablePipe.Write(new Span<byte>(buffer)));
- Assert.Throws<IOException>(() => { pair.writeablePipe.WriteAsync(new Memory<byte>(buffer)); });
- }
- }
-
- [Fact]
- public void DisposeAsync_NothingWrittenNeedsToBeFlushed_CompletesSynchronously()
- {
- ServerClientPair pair = CreateServerClientPair();
- for (int i = 0; i < 2; i++)
- {
- Assert.True(pair.readablePipe.DisposeAsync().IsCompletedSuccessfully);
- Assert.True(pair.writeablePipe.DisposeAsync().IsCompletedSuccessfully);
- }
- Assert.Throws<ObjectDisposedException>(() => pair.writeablePipe.Write(new Span<byte>(new byte[1])));
- }
- }
-}
<Compile Include="$(CommonPath)\Interop\Windows\Kernel32\Interop.MaxLengths.cs">
<Link>Common\Interop\Windows\Interop.MaxLengths.cs</Link>
</Compile>
- <Compile Include="NamedPipeTests\NamedPipeTest.CurrentUserOnly.netcoreapp.cs" />
- <Compile Include="PipeTest.Read.netcoreapp.cs" />
- <Compile Include="PipeTest.Write.netcoreapp.cs" />
- <Compile Include="NamedPipeTests\NamedPipeTest.CurrentUserOnly.netcoreapp.Windows.cs" />
+ <Compile Include="NamedPipeTests\NamedPipeTest.CurrentUserOnly.cs" />
+ <Compile Include="NamedPipeTests\NamedPipeTest.CurrentUserOnly.Windows.cs" />
<Compile Include="InteropTest.Windows.cs" />
<Compile Include="NamedPipeTests\NamedPipeTest.RunAsClient.Windows.cs" />
<Compile Include="InteropTest.Windows.Win32.cs" />
</ItemGroup>
<ItemGroup Condition="'$(TargetsUnix)' == 'true'">
- <Compile Include="NamedPipeTests\NamedPipeTest.CurrentUserOnly.netcoreapp.Unix.cs" />
+ <Compile Include="NamedPipeTests\NamedPipeTest.CurrentUserOnly.Unix.cs" />
<Compile Include="NamedPipeTests\NamedPipeTest.UnixDomainSockets.cs" />
<Compile Include="InteropTest.Unix.cs" />
<Compile Include="NamedPipeTests\NamedPipeTest.RunAsClient.Unix.cs" />
<Compile Include="UmaTests.cs" />
<Compile Include="UmsCtorTests.cs" />
<Compile Include="HGlobalSafeBuffer.cs" />
- <Compile Include="UmsDisposeAsync.netcoreapp.cs" Condition="'$(TargetsNetCoreApp)' == 'true'" />
+ <Compile Include="UmsDisposeAsync.cs" />
<Compile Include="UmsReadWrite.cs" />
- <Compile Include="UmsReadWrite.netcoreapp.cs" Condition="'$(TargetsNetCoreApp)' == 'true'" />
<Compile Include="UmsSafeBuffer.cs" />
<Compile Include="UmaCtorTests.cs" />
<Compile Include="UmsFlush.cs" />
}
}
}
+
+ public sealed class SpanUmsReadWriteTests : UmsReadWriteTests
+ {
+ protected override int Read(UnmanagedMemoryStream stream, byte[] array, int offset, int count) =>
+ stream.Read(new Span<byte>(array, offset, count));
+ protected override void Write(UnmanagedMemoryStream stream, byte[] array, int offset, int count) =>
+ stream.Write(new Span<byte>(array, offset, count));
+ }
+
+ public sealed class MemoryUmsReadWriteTests : UmsReadWriteTests
+ {
+ protected override int Read(UnmanagedMemoryStream stream, byte[] array, int offset, int count) =>
+ stream.ReadAsync(new Memory<byte>(array, offset, count)).GetAwaiter().GetResult();
+ protected override void Write(UnmanagedMemoryStream stream, byte[] array, int offset, int count) =>
+ stream.WriteAsync(new Memory<byte>(array, offset, count)).GetAwaiter().GetResult();
+ }
}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-namespace System.IO.Tests
-{
- public sealed class SpanUmsReadWriteTests : UmsReadWriteTests
- {
- protected override int Read(UnmanagedMemoryStream stream, byte[] array, int offset, int count) =>
- stream.Read(new Span<byte>(array, offset, count));
- protected override void Write(UnmanagedMemoryStream stream, byte[] array, int offset, int count) =>
- stream.Write(new Span<byte>(array, offset, count));
- }
-
- public sealed class MemoryUmsReadWriteTests : UmsReadWriteTests
- {
- protected override int Read(UnmanagedMemoryStream stream, byte[] array, int offset, int count) =>
- stream.ReadAsync(new Memory<byte>(array, offset, count)).GetAwaiter().GetResult();
- protected override void Write(UnmanagedMemoryStream stream, byte[] array, int offset, int count) =>
- stream.WriteAsync(new Memory<byte>(array, offset, count)).GetAwaiter().GetResult();
- }
-}
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using System;
-using System.Collections.Generic;
-using System.IO;
using System.Linq;
using System.Text;
using Xunit;
namespace System.IO.Tests
{
- public partial class BinaryReaderTests
+ public class BinaryReaderTests
{
protected virtual Stream CreateStream()
{
}
}
}
+
+ [Theory]
+ [InlineData(100, 100, 100)]
+ [InlineData(100, 50, 50)]
+ [InlineData(50, 100, 50)]
+ [InlineData(10, 0, 0)]
+ [InlineData(0, 10, 0)]
+ public void Read_ByteSpan(int sourceSize, int destinationSize, int expectedReadLength)
+ {
+ using (var stream = CreateStream())
+ {
+ var source = new byte[sourceSize];
+ new Random(345).NextBytes(source);
+ stream.Write(source, 0, source.Length);
+ stream.Position = 0;
+
+ using (var reader = new BinaryReader(stream))
+ {
+ var destination = new byte[destinationSize];
+
+ int readCount = reader.Read(new Span<byte>(destination));
+
+ Assert.Equal(expectedReadLength, readCount);
+ Assert.Equal(source.Take(expectedReadLength), destination.Take(expectedReadLength));
+
+ // Make sure we didn't write past the end
+ Assert.True(destination.Skip(expectedReadLength).All(b => b == default(byte)));
+ }
+ }
+ }
+
+ [Fact]
+ public void Read_ByteSpan_ThrowIfDisposed()
+ {
+ using (var memStream = CreateStream())
+ {
+ var binaryReader = new BinaryReader(memStream);
+ binaryReader.Dispose();
+ Assert.Throws<ObjectDisposedException>(() => binaryReader.Read(new Span<byte>()));
+ }
+ }
+
+ [Theory]
+ [InlineData(100, 100, 100)]
+ [InlineData(100, 50, 50)]
+ [InlineData(50, 100, 50)]
+ [InlineData(10, 0, 0)]
+ [InlineData(0, 10, 0)]
+ public void Read_CharSpan(int sourceSize, int destinationSize, int expectedReadLength)
+ {
+ using (var stream = CreateStream())
+ {
+ var source = new char[sourceSize];
+ var random = new Random(345);
+
+ for (int i = 0; i < sourceSize; i++)
+ {
+ source[i] = (char)random.Next(0, 127);
+ }
+
+ stream.Write(Encoding.ASCII.GetBytes(source), 0, source.Length);
+ stream.Position = 0;
+
+ using (var reader = new BinaryReader(stream, Encoding.ASCII))
+ {
+ var destination = new char[destinationSize];
+
+ int readCount = reader.Read(new Span<char>(destination));
+
+ Assert.Equal(expectedReadLength, readCount);
+ Assert.Equal(source.Take(expectedReadLength), destination.Take(expectedReadLength));
+
+ // Make sure we didn't write past the end
+ Assert.True(destination.Skip(expectedReadLength).All(b => b == default(char)));
+ }
+ }
+ }
+
+ [Fact]
+ public void Read_CharSpan_ThrowIfDisposed()
+ {
+ using (var memStream = CreateStream())
+ {
+ var binaryReader = new BinaryReader(memStream);
+ binaryReader.Dispose();
+ Assert.Throws<ObjectDisposedException>(() => binaryReader.Read(new Span<char>()));
+ }
+ }
}
}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Linq;
-using System.Text;
-using Xunit;
-
-namespace System.IO.Tests
-{
- public partial class BinaryReaderTests
- {
- [Theory]
- [InlineData(100, 100, 100)]
- [InlineData(100, 50, 50)]
- [InlineData(50, 100, 50)]
- [InlineData(10, 0, 0)]
- [InlineData(0, 10, 0)]
- public void Read_ByteSpan(int sourceSize, int destinationSize, int expectedReadLength)
- {
- using (var stream = CreateStream())
- {
- var source = new byte[sourceSize];
- new Random(345).NextBytes(source);
- stream.Write(source, 0, source.Length);
- stream.Position = 0;
-
- using (var reader = new BinaryReader(stream))
- {
- var destination = new byte[destinationSize];
-
- int readCount = reader.Read(new Span<byte>(destination));
-
- Assert.Equal(expectedReadLength, readCount);
- Assert.Equal(source.Take(expectedReadLength), destination.Take(expectedReadLength));
-
- // Make sure we didn't write past the end
- Assert.True(destination.Skip(expectedReadLength).All(b => b == default(byte)));
- }
- }
- }
-
- [Fact]
- public void Read_ByteSpan_ThrowIfDisposed()
- {
- using (var memStream = CreateStream())
- {
- var binaryReader = new BinaryReader(memStream);
- binaryReader.Dispose();
- Assert.Throws<ObjectDisposedException>(() => binaryReader.Read(new Span<byte>()));
- }
- }
-
- [Theory]
- [InlineData(100, 100, 100)]
- [InlineData(100, 50, 50)]
- [InlineData(50, 100, 50)]
- [InlineData(10, 0, 0)]
- [InlineData(0, 10, 0)]
- public void Read_CharSpan(int sourceSize, int destinationSize, int expectedReadLength)
- {
- using (var stream = CreateStream())
- {
- var source = new char[sourceSize];
- var random = new Random(345);
-
- for (int i = 0; i < sourceSize; i++)
- {
- source[i] = (char)random.Next(0, 127);
- }
-
- stream.Write(Encoding.ASCII.GetBytes(source), 0, source.Length);
- stream.Position = 0;
-
- using (var reader = new BinaryReader(stream, Encoding.ASCII))
- {
- var destination = new char[destinationSize];
-
- int readCount = reader.Read(new Span<char>(destination));
-
- Assert.Equal(expectedReadLength, readCount);
- Assert.Equal(source.Take(expectedReadLength), destination.Take(expectedReadLength));
-
- // Make sure we didn't write past the end
- Assert.True(destination.Skip(expectedReadLength).All(b => b == default(char)));
- }
- }
- }
-
- [Fact]
- public void Read_CharSpan_ThrowIfDisposed()
- {
- using (var memStream = CreateStream())
- {
- var binaryReader = new BinaryReader(memStream);
- binaryReader.Dispose();
- Assert.Throws<ObjectDisposedException>(() => binaryReader.Read(new Span<char>()));
- }
- }
- }
-}
namespace System.IO.Tests
{
- public partial class BinaryWriter_DisposeAsync
+ public class BinaryWriter_DisposeAsync
{
[Fact]
public void DisposeAsync_CanInvokeMultipleTimes()
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using Xunit;
-using System;
-using System.IO;
using System.Text;
+using Xunit;
namespace System.IO.Tests
{
- public partial class BinaryWriter_WriteByteCharTests
+ public class BinaryWriter_WriteByteCharTests
{
protected virtual Stream CreateStream()
{
mstr.Dispose();
dw2.Dispose();
}
+
+ [Fact]
+ public void BinaryWriter_WriteSpan()
+ {
+ byte[] bytes = new byte[] { 4, 2, 7, 0xFF };
+ char[] chars = new char[] { 'a', '7', char.MaxValue };
+ Span<byte> byteSpan = new Span<byte>(bytes);
+ Span<char> charSpan = new Span<char>(chars);
+
+ using (Stream memoryStream = CreateStream())
+ {
+ using (BinaryWriter binaryWriter = new BinaryWriter(memoryStream, Encoding.Unicode))
+ {
+ binaryWriter.Write(byteSpan);
+ binaryWriter.Write(charSpan);
+
+ Stream baseStream = binaryWriter.BaseStream;
+ baseStream.Position = 2;
+
+ Assert.Equal(7, baseStream.ReadByte());
+ Assert.Equal(0xFF, baseStream.ReadByte());
+
+ char testChar;
+
+ testChar = BitConverter.ToChar(new byte[] { (byte)baseStream.ReadByte(), (byte)baseStream.ReadByte() }, 0);
+ Assert.Equal('a', testChar);
+
+ testChar = BitConverter.ToChar(new byte[] { (byte)baseStream.ReadByte(), (byte)baseStream.ReadByte() }, 0);
+ Assert.Equal('7', testChar);
+
+ testChar = BitConverter.ToChar(new byte[] { (byte)baseStream.ReadByte(), (byte)baseStream.ReadByte() }, 0);
+ Assert.Equal(char.MaxValue, testChar);
+ }
+ }
+ }
}
}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using Xunit;
-using System;
-using System.IO;
-using System.Text;
-
-namespace System.IO.Tests
-{
- public partial class BinaryWriter_WriteByteCharTests
- {
- [Fact]
- public void BinaryWriter_WriteSpan()
- {
- byte[] bytes = new byte[] { 4, 2, 7, 0xFF };
- char[] chars = new char[] { 'a', '7', char.MaxValue };
- Span<byte> byteSpan = new Span<byte>(bytes);
- Span<char> charSpan = new Span<char>(chars);
-
- using (Stream memoryStream = CreateStream())
- {
- using (BinaryWriter binaryWriter = new BinaryWriter(memoryStream, Encoding.Unicode))
- {
- binaryWriter.Write(byteSpan);
- binaryWriter.Write(charSpan);
-
- Stream baseStream = binaryWriter.BaseStream;
- baseStream.Position = 2;
-
- Assert.Equal(7, baseStream.ReadByte());
- Assert.Equal(0xFF, baseStream.ReadByte());
-
- char testChar;
-
- testChar = BitConverter.ToChar(new byte[] { (byte)baseStream.ReadByte(), (byte)baseStream.ReadByte() }, 0);
- Assert.Equal('a', testChar);
-
- testChar = BitConverter.ToChar(new byte[] { (byte)baseStream.ReadByte(), (byte)baseStream.ReadByte() }, 0);
- Assert.Equal('7', testChar);
-
- testChar = BitConverter.ToChar(new byte[] { (byte)baseStream.ReadByte(), (byte)baseStream.ReadByte() }, 0);
- Assert.Equal(char.MaxValue, testChar);
- }
- }
- }
- }
-}
stream.EndWrite(result);
}
}
+
+ public class BufferedStreamTests
+ {
+ [Fact]
+ public void UnderlyingStream()
+ {
+ var underlyingStream = new MemoryStream();
+ var bufferedStream = new BufferedStream(underlyingStream);
+ Assert.Same(underlyingStream, bufferedStream.UnderlyingStream);
+ }
+
+ [Fact]
+ public void BufferSize()
+ {
+ var bufferedStream = new BufferedStream(new MemoryStream(), 1234);
+ Assert.Equal(1234, bufferedStream.BufferSize);
+ }
+
+ [Theory]
+ [InlineData(1, 1)]
+ [InlineData(1, 2)]
+ [InlineData(1024, 4096)]
+ [InlineData(4096, 4097)]
+ [InlineData(4096, 1)]
+ [InlineData(2047, 4096)]
+ public void ReadSpan_WriteSpan_AllDataCopied(int spanSize, int bufferSize)
+ {
+ byte[] data = new byte[80000];
+ new Random(42).NextBytes(data);
+
+ var result = new MemoryStream();
+ using (var output = new BufferedStream(result, bufferSize))
+ using (var input = new BufferedStream(new MemoryStream(data), bufferSize))
+ {
+ Span<byte> span = new byte[spanSize];
+ int bytesRead;
+ while ((bytesRead = input.Read(span)) != 0)
+ {
+ output.Write(span.Slice(0, bytesRead));
+ }
+ }
+ Assert.Equal(data, result.ToArray());
+ }
+
+ [Theory]
+ [InlineData(1, 1)]
+ [InlineData(1, 2)]
+ [InlineData(1024, 4096)]
+ [InlineData(4096, 4097)]
+ [InlineData(4096, 1)]
+ [InlineData(2047, 4096)]
+ public async Task ReadMemory_WriteMemory_AllDataCopied(int spanSize, int bufferSize)
+ {
+ byte[] data = new byte[80000];
+ new Random(42).NextBytes(data);
+
+ var result = new MemoryStream();
+ using (var output = new BufferedStream(result, bufferSize))
+ using (var input = new BufferedStream(new MemoryStream(data), bufferSize))
+ {
+ Memory<byte> memory = new byte[spanSize];
+ int bytesRead;
+ while ((bytesRead = await input.ReadAsync(memory)) != 0)
+ {
+ await output.WriteAsync(memory.Slice(0, bytesRead));
+ }
+ }
+ Assert.Equal(data, result.ToArray());
+ }
+
+ [Fact]
+ public void ReadWriteMemory_Precanceled_Throws()
+ {
+ using (var bs = new BufferedStream(new MemoryStream()))
+ {
+ Assert.Equal(TaskStatus.Canceled, bs.ReadAsync(new byte[1], new CancellationToken(true)).AsTask().Status);
+ Assert.Equal(TaskStatus.Canceled, bs.WriteAsync(new byte[1], new CancellationToken(true)).AsTask().Status);
+ }
+ }
+
+ [Fact]
+ public async Task DisposeAsync_FlushesAndClosesStream()
+ {
+ var ms = new MemoryStream();
+ var bs = new BufferedStream(ms);
+ bs.Write(new byte[1], 0, 1);
+ Assert.Equal(0, ms.Position);
+ await bs.DisposeAsync();
+ Assert.True(bs.DisposeAsync().IsCompletedSuccessfully);
+ Assert.Throws<ObjectDisposedException>(() => ms.Position);
+ Assert.Equal(1, ms.ToArray().Length);
+ }
+ }
}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Threading;
-using System.Threading.Tasks;
-using Xunit;
-
-namespace System.IO.Tests
-{
- public partial class BufferedStreamTests
- {
- [Fact]
- public void UnderlyingStream()
- {
- var underlyingStream = new MemoryStream();
- var bufferedStream = new BufferedStream(underlyingStream);
- Assert.Same(underlyingStream, bufferedStream.UnderlyingStream);
- }
-
- [Fact]
- public void BufferSize()
- {
- var bufferedStream = new BufferedStream(new MemoryStream(), 1234);
- Assert.Equal(1234, bufferedStream.BufferSize);
- }
-
- [Theory]
- [InlineData(1, 1)]
- [InlineData(1, 2)]
- [InlineData(1024, 4096)]
- [InlineData(4096, 4097)]
- [InlineData(4096, 1)]
- [InlineData(2047, 4096)]
- public void ReadSpan_WriteSpan_AllDataCopied(int spanSize, int bufferSize)
- {
- byte[] data = new byte[80000];
- new Random(42).NextBytes(data);
-
- var result = new MemoryStream();
- using (var output = new BufferedStream(result, bufferSize))
- using (var input = new BufferedStream(new MemoryStream(data), bufferSize))
- {
- Span<byte> span = new byte[spanSize];
- int bytesRead;
- while ((bytesRead = input.Read(span)) != 0)
- {
- output.Write(span.Slice(0, bytesRead));
- }
- }
- Assert.Equal(data, result.ToArray());
- }
-
- [Theory]
- [InlineData(1, 1)]
- [InlineData(1, 2)]
- [InlineData(1024, 4096)]
- [InlineData(4096, 4097)]
- [InlineData(4096, 1)]
- [InlineData(2047, 4096)]
- public async Task ReadMemory_WriteMemory_AllDataCopied(int spanSize, int bufferSize)
- {
- byte[] data = new byte[80000];
- new Random(42).NextBytes(data);
-
- var result = new MemoryStream();
- using (var output = new BufferedStream(result, bufferSize))
- using (var input = new BufferedStream(new MemoryStream(data), bufferSize))
- {
- Memory<byte> memory = new byte[spanSize];
- int bytesRead;
- while ((bytesRead = await input.ReadAsync(memory)) != 0)
- {
- await output.WriteAsync(memory.Slice(0, bytesRead));
- }
- }
- Assert.Equal(data, result.ToArray());
- }
-
- [Fact]
- public void ReadWriteMemory_Precanceled_Throws()
- {
- using (var bs = new BufferedStream(new MemoryStream()))
- {
- Assert.Equal(TaskStatus.Canceled, bs.ReadAsync(new byte[1], new CancellationToken(true)).AsTask().Status);
- Assert.Equal(TaskStatus.Canceled, bs.WriteAsync(new byte[1], new CancellationToken(true)).AsTask().Status);
- }
- }
-
- [Fact]
- public async Task DisposeAsync_FlushesAndClosesStream()
- {
- var ms = new MemoryStream();
- var bs = new BufferedStream(ms);
- bs.Write(new byte[1], 0, 1);
- Assert.Equal(0, ms.Position);
- await bs.DisposeAsync();
- Assert.True(bs.DisposeAsync().IsCompletedSuccessfully);
- Assert.Throws<ObjectDisposedException>(() => ms.Position);
- Assert.Equal(1, ms.ToArray().Length);
- }
- }
-}
using Xunit;
using System.Collections.Generic;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
namespace System.IO.Tests
{
- public partial class MemoryStreamTests
+ public class MemoryStreamTests
{
[Fact]
public static void MemoryStream_Write_BeyondCapacity()
yield return new object[] { stream3, Array.Empty<byte>() };
}
+
+ [Fact]
+ public void WriteSpan_DataWrittenAndPositionUpdated_Success()
+ {
+ const int Iters = 100;
+ var rand = new Random();
+ byte[] data = Enumerable.Range(0, (Iters * (Iters + 1)) / 2).Select(_ => (byte)rand.Next(256)).ToArray();
+ var s = new MemoryStream();
+
+ int expectedPos = 0;
+ for (int i = 0; i <= Iters; i++)
+ {
+ s.Write(new ReadOnlySpan<byte>(data, expectedPos, i));
+ expectedPos += i;
+ Assert.Equal(expectedPos, s.Position);
+ }
+
+ Assert.Equal(data, s.ToArray());
+ }
+
+ [Fact]
+ public void ReadSpan_DataReadAndPositionUpdated_Success()
+ {
+ const int Iters = 100;
+ var rand = new Random();
+ byte[] data = Enumerable.Range(0, (Iters * (Iters + 1)) / 2).Select(_ => (byte)rand.Next(256)).ToArray();
+ var s = new MemoryStream(data);
+
+ int expectedPos = 0;
+ for (int i = 0; i <= Iters; i++)
+ {
+ var toRead = new Span<byte>(new byte[i * 3]); // enough room to read the data and have some offset and have slack at the end
+
+ // Do the read and validate we read the expected number of bytes
+ Assert.Equal(i, s.Read(toRead.Slice(i, i)));
+
+ // The contents prior to and after the read should be empty.
+ Assert.Equal<byte>(new byte[i], toRead.Slice(0, i).ToArray());
+ Assert.Equal<byte>(new byte[i], toRead.Slice(i * 2, i).ToArray());
+
+ // And the data read should match what was expected.
+ Assert.Equal(new Span<byte>(data, expectedPos, i).ToArray(), toRead.Slice(i, i).ToArray());
+
+ // Updated position should match
+ expectedPos += i;
+ Assert.Equal(expectedPos, s.Position);
+ }
+
+ // A final read should be empty
+ Assert.Equal(0, s.Read(new Span<byte>(new byte[1])));
+ }
+
+ [Fact]
+ public void DerivedMemoryStream_ReadWriteSpanCalled_ReadWriteArrayUsed()
+ {
+ var s = new ReadWriteOverridingMemoryStream();
+ Assert.False(s.WriteArrayInvoked);
+ Assert.False(s.ReadArrayInvoked);
+
+ s.Write((ReadOnlySpan<byte>)new byte[1]);
+ Assert.True(s.WriteArrayInvoked);
+ Assert.False(s.ReadArrayInvoked);
+
+ s.Position = 0;
+ s.Read((Span<byte>)new byte[1]);
+ Assert.True(s.WriteArrayInvoked);
+ Assert.True(s.ReadArrayInvoked);
+ }
+
+ [Fact]
+ public async Task WriteAsyncReadOnlyMemory_DataWrittenAndPositionUpdated_Success()
+ {
+ const int Iters = 100;
+ var rand = new Random();
+ byte[] data = Enumerable.Range(0, (Iters * (Iters + 1)) / 2).Select(_ => (byte)rand.Next(256)).ToArray();
+ var s = new MemoryStream();
+
+ int expectedPos = 0;
+ for (int i = 0; i <= Iters; i++)
+ {
+ await s.WriteAsync(new ReadOnlyMemory<byte>(data, expectedPos, i));
+ expectedPos += i;
+ Assert.Equal(expectedPos, s.Position);
+ }
+
+ Assert.Equal(data, s.ToArray());
+ }
+
+ [Fact]
+ public async Task ReadAsyncMemory_DataReadAndPositionUpdated_Success()
+ {
+ const int Iters = 100;
+ var rand = new Random();
+ byte[] data = Enumerable.Range(0, (Iters * (Iters + 1)) / 2).Select(_ => (byte)rand.Next(256)).ToArray();
+ var s = new MemoryStream(data);
+
+ int expectedPos = 0;
+ for (int i = 0; i <= Iters; i++)
+ {
+ var toRead = new Memory<byte>(new byte[i * 3]); // enough room to read the data and have some offset and have slack at the end
+
+ // Do the read and validate we read the expected number of bytes
+ Assert.Equal(i, await s.ReadAsync(toRead.Slice(i, i)));
+
+ // The contents prior to and after the read should be empty.
+ Assert.Equal<byte>(new byte[i], toRead.Slice(0, i).ToArray());
+ Assert.Equal<byte>(new byte[i], toRead.Slice(i * 2, i).ToArray());
+
+ // And the data read should match what was expected.
+ Assert.Equal(new Span<byte>(data, expectedPos, i).ToArray(), toRead.Slice(i, i).ToArray());
+
+ // Updated position should match
+ expectedPos += i;
+ Assert.Equal(expectedPos, s.Position);
+ }
+
+ // A final read should be empty
+ Assert.Equal(0, await s.ReadAsync(new Memory<byte>(new byte[1])));
+ }
+
+ [Fact]
+ public async Task DerivedMemoryStream_ReadWriteAsyncMemoryCalled_ReadWriteAsyncArrayUsed()
+ {
+ var s = new ReadWriteOverridingMemoryStream();
+ Assert.False(s.WriteArrayInvoked);
+ Assert.False(s.ReadArrayInvoked);
+
+ await s.WriteAsync((ReadOnlyMemory<byte>)new byte[1]);
+ Assert.True(s.WriteArrayInvoked);
+ Assert.False(s.ReadArrayInvoked);
+
+ s.Position = 0;
+ await s.ReadAsync((Memory<byte>)new byte[1]);
+ Assert.True(s.WriteArrayInvoked);
+ Assert.True(s.ReadArrayInvoked);
+ }
+
+ [Fact]
+ public void DisposeAsync_ClosesStream()
+ {
+ var ms = new MemoryStream();
+ Assert.True(ms.DisposeAsync().IsCompletedSuccessfully);
+ Assert.True(ms.DisposeAsync().IsCompletedSuccessfully);
+ Assert.Throws<ObjectDisposedException>(() => ms.Position);
+ }
+
+ private class ReadWriteOverridingMemoryStream : MemoryStream
+ {
+ public bool ReadArrayInvoked, WriteArrayInvoked;
+ public bool ReadAsyncArrayInvoked, WriteAsyncArrayInvoked;
+
+ public override int Read(byte[] buffer, int offset, int count)
+ {
+ ReadArrayInvoked = true;
+ return base.Read(buffer, offset, count);
+ }
+
+ public override void Write(byte[] buffer, int offset, int count)
+ {
+ WriteArrayInvoked = true;
+ base.Write(buffer, offset, count);
+ }
+
+ public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
+ {
+ ReadAsyncArrayInvoked = true;
+ return base.ReadAsync(buffer, offset, count, cancellationToken);
+ }
+
+ public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
+ {
+ WriteAsyncArrayInvoked = true;
+ return base.WriteAsync(buffer, offset, count, cancellationToken);
+ }
+ }
}
}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using Xunit;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-
-namespace System.IO.Tests
-{
- public partial class MemoryStreamTests
- {
- [Fact]
- public void WriteSpan_DataWrittenAndPositionUpdated_Success()
- {
- const int Iters = 100;
- var rand = new Random();
- byte[] data = Enumerable.Range(0, (Iters * (Iters + 1)) / 2).Select(_ => (byte)rand.Next(256)).ToArray();
- var s = new MemoryStream();
-
- int expectedPos = 0;
- for (int i = 0; i <= Iters; i++)
- {
- s.Write(new ReadOnlySpan<byte>(data, expectedPos, i));
- expectedPos += i;
- Assert.Equal(expectedPos, s.Position);
- }
-
- Assert.Equal(data, s.ToArray());
- }
-
- [Fact]
- public void ReadSpan_DataReadAndPositionUpdated_Success()
- {
- const int Iters = 100;
- var rand = new Random();
- byte[] data = Enumerable.Range(0, (Iters * (Iters + 1)) / 2).Select(_ => (byte)rand.Next(256)).ToArray();
- var s = new MemoryStream(data);
-
- int expectedPos = 0;
- for (int i = 0; i <= Iters; i++)
- {
- var toRead = new Span<byte>(new byte[i * 3]); // enough room to read the data and have some offset and have slack at the end
-
- // Do the read and validate we read the expected number of bytes
- Assert.Equal(i, s.Read(toRead.Slice(i, i)));
-
- // The contents prior to and after the read should be empty.
- Assert.Equal<byte>(new byte[i], toRead.Slice(0, i).ToArray());
- Assert.Equal<byte>(new byte[i], toRead.Slice(i * 2, i).ToArray());
-
- // And the data read should match what was expected.
- Assert.Equal(new Span<byte>(data, expectedPos, i).ToArray(), toRead.Slice(i, i).ToArray());
-
- // Updated position should match
- expectedPos += i;
- Assert.Equal(expectedPos, s.Position);
- }
-
- // A final read should be empty
- Assert.Equal(0, s.Read(new Span<byte>(new byte[1])));
- }
-
- [Fact]
- public void DerivedMemoryStream_ReadWriteSpanCalled_ReadWriteArrayUsed()
- {
- var s = new ReadWriteOverridingMemoryStream();
- Assert.False(s.WriteArrayInvoked);
- Assert.False(s.ReadArrayInvoked);
-
- s.Write((ReadOnlySpan<byte>)new byte[1]);
- Assert.True(s.WriteArrayInvoked);
- Assert.False(s.ReadArrayInvoked);
-
- s.Position = 0;
- s.Read((Span<byte>)new byte[1]);
- Assert.True(s.WriteArrayInvoked);
- Assert.True(s.ReadArrayInvoked);
- }
-
- [Fact]
- public async Task WriteAsyncReadOnlyMemory_DataWrittenAndPositionUpdated_Success()
- {
- const int Iters = 100;
- var rand = new Random();
- byte[] data = Enumerable.Range(0, (Iters * (Iters + 1)) / 2).Select(_ => (byte)rand.Next(256)).ToArray();
- var s = new MemoryStream();
-
- int expectedPos = 0;
- for (int i = 0; i <= Iters; i++)
- {
- await s.WriteAsync(new ReadOnlyMemory<byte>(data, expectedPos, i));
- expectedPos += i;
- Assert.Equal(expectedPos, s.Position);
- }
-
- Assert.Equal(data, s.ToArray());
- }
-
- [Fact]
- public async Task ReadAsyncMemory_DataReadAndPositionUpdated_Success()
- {
- const int Iters = 100;
- var rand = new Random();
- byte[] data = Enumerable.Range(0, (Iters * (Iters + 1)) / 2).Select(_ => (byte)rand.Next(256)).ToArray();
- var s = new MemoryStream(data);
-
- int expectedPos = 0;
- for (int i = 0; i <= Iters; i++)
- {
- var toRead = new Memory<byte>(new byte[i * 3]); // enough room to read the data and have some offset and have slack at the end
-
- // Do the read and validate we read the expected number of bytes
- Assert.Equal(i, await s.ReadAsync(toRead.Slice(i, i)));
-
- // The contents prior to and after the read should be empty.
- Assert.Equal<byte>(new byte[i], toRead.Slice(0, i).ToArray());
- Assert.Equal<byte>(new byte[i], toRead.Slice(i * 2, i).ToArray());
-
- // And the data read should match what was expected.
- Assert.Equal(new Span<byte>(data, expectedPos, i).ToArray(), toRead.Slice(i, i).ToArray());
-
- // Updated position should match
- expectedPos += i;
- Assert.Equal(expectedPos, s.Position);
- }
-
- // A final read should be empty
- Assert.Equal(0, await s.ReadAsync(new Memory<byte>(new byte[1])));
- }
-
- [Fact]
- public async Task DerivedMemoryStream_ReadWriteAsyncMemoryCalled_ReadWriteAsyncArrayUsed()
- {
- var s = new ReadWriteOverridingMemoryStream();
- Assert.False(s.WriteArrayInvoked);
- Assert.False(s.ReadArrayInvoked);
-
- await s.WriteAsync((ReadOnlyMemory<byte>)new byte[1]);
- Assert.True(s.WriteArrayInvoked);
- Assert.False(s.ReadArrayInvoked);
-
- s.Position = 0;
- await s.ReadAsync((Memory<byte>)new byte[1]);
- Assert.True(s.WriteArrayInvoked);
- Assert.True(s.ReadArrayInvoked);
- }
-
- [Fact]
- public void DisposeAsync_ClosesStream()
- {
- var ms = new MemoryStream();
- Assert.True(ms.DisposeAsync().IsCompletedSuccessfully);
- Assert.True(ms.DisposeAsync().IsCompletedSuccessfully);
- Assert.Throws<ObjectDisposedException>(() => ms.Position);
- }
-
- private class ReadWriteOverridingMemoryStream : MemoryStream
- {
- public bool ReadArrayInvoked, WriteArrayInvoked;
- public bool ReadAsyncArrayInvoked, WriteAsyncArrayInvoked;
-
- public override int Read(byte[] buffer, int offset, int count)
- {
- ReadArrayInvoked = true;
- return base.Read(buffer, offset, count);
- }
-
- public override void Write(byte[] buffer, int offset, int count)
- {
- WriteArrayInvoked = true;
- base.Write(buffer, offset, count);
- }
-
- public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
- {
- ReadAsyncArrayInvoked = true;
- return base.ReadAsync(buffer, offset, count, cancellationToken);
- }
-
- public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
- {
- WriteAsyncArrayInvoked = true;
- return base.WriteAsync(buffer, offset, count, cancellationToken);
- }
- }
- }
-}
namespace System.IO.Tests
{
- public partial class StreamCopyToTests
+ public class StreamCopyToTests
{
[Fact]
public void IfCanSeekIsFalseLengthAndPositionShouldNotBeCalled()
Assert.Equal(ReadLimit - 1, dest.TimesCalled(nameof(dest.WriteAsync))); // dest.WriteAsync will still get called repeatedly
}
+ [Fact]
+ public void CopyToAsync_StreamToken_InvalidArgsThrows()
+ {
+ Stream s = new MemoryStream();
+ AssertExtensions.Throws<ArgumentNullException>("destination", () => { s.CopyToAsync(null, default(CancellationToken)); });
+ }
+
+ [Theory]
+ [InlineData(0)]
+ [InlineData(42)]
+ [InlineData(100000)] // greater than 81920, the DefaultCopyBufferSize
+ public void CopyToAsync_StreamToken_ExpectedBufferSizePropagated(int length)
+ {
+ Stream s = new CustomMemoryStream();
+ s.Write(new byte[length], 0, length);
+ s.Position = 0;
+
+ const int DefaultCopyBufferSize = 81920;
+ Assert.Equal(Math.Max(1, Math.Min(length, DefaultCopyBufferSize)), ((Task<int>)s.CopyToAsync(Stream.Null, default(CancellationToken))).Result);
+ }
+
+ private sealed class CustomMemoryStream : MemoryStream
+ {
+ public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken) =>
+ Task.FromResult(bufferSize);
+ }
+
+ [Fact]
+ public void CopyToAsync_StreamToken_PrecanceledToken_Cancels()
+ {
+ var src = new MemoryStream();
+ Assert.Equal(TaskStatus.Canceled, src.CopyToAsync(Stream.Null, new CancellationToken(true)).Status);
+ }
+
+ [Fact]
+ public async Task CopyToAsync_StreamToken_AllDataCopied()
+ {
+ var src = new MemoryStream();
+ src.Write(Enumerable.Range(0, 10000).Select(i => (byte)i).ToArray(), 0, 256);
+ src.Position = 0;
+
+ var dst = new MemoryStream();
+ await src.CopyToAsync(dst, default(CancellationToken));
+
+ Assert.Equal<byte>(src.ToArray(), dst.ToArray());
+ }
+
// Member data
public static IEnumerable<object[]> LengthIsLessThanOrEqualToPosition()
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using Xunit;
-
-namespace System.IO.Tests
-{
- public partial class StreamCopyToTests
- {
- [Fact]
- public void CopyToAsync_StreamToken_InvalidArgsThrows()
- {
- Stream s = new MemoryStream();
- AssertExtensions.Throws<ArgumentNullException>("destination", () => { s.CopyToAsync(null, default(CancellationToken)); });
- }
-
- [Theory]
- [InlineData(0)]
- [InlineData(42)]
- [InlineData(100000)] // greater than 81920, the DefaultCopyBufferSize
- public void CopyToAsync_StreamToken_ExpectedBufferSizePropagated(int length)
- {
- Stream s = new CustomMemoryStream();
- s.Write(new byte[length], 0, length);
- s.Position = 0;
-
- const int DefaultCopyBufferSize = 81920;
- Assert.Equal(Math.Max(1, Math.Min(length, DefaultCopyBufferSize)), ((Task<int>)s.CopyToAsync(Stream.Null, default(CancellationToken))).Result);
- }
-
- private sealed class CustomMemoryStream : MemoryStream
- {
- public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken) =>
- Task.FromResult(bufferSize);
- }
-
- [Fact]
- public void CopyToAsync_StreamToken_PrecanceledToken_Cancels()
- {
- var src = new MemoryStream();
- Assert.Equal(TaskStatus.Canceled, src.CopyToAsync(Stream.Null, new CancellationToken(true)).Status);
- }
-
- [Fact]
- public async Task CopyToAsync_StreamToken_AllDataCopied()
- {
- var src = new MemoryStream();
- src.Write(Enumerable.Range(0, 10000).Select(i => (byte)i).ToArray(), 0, 256);
- src.Position = 0;
-
- var dst = new MemoryStream();
- await src.CopyToAsync(dst, default(CancellationToken));
-
- Assert.Equal<byte>(src.ToArray(), dst.ToArray());
- }
- }
-}
namespace System.IO.Tests
{
- public partial class StreamDisposeAsyncTests
+ public class StreamDisposeAsyncTests
{
[Fact]
public async Task DisposeAsync_MultipleDisposalSuccessful()
namespace System.IO.Tests
{
- public partial class NullTests
+ public class NullTests
{
[Fact]
public static async Task TestNullStream_Flush()
output.Dispose();
}
+ [Theory]
+ [MemberData(nameof(NullStream_ReadWriteData))]
+ public void TestNullStream_ReadSpan(byte[] buffer, int offset, int count)
+ {
+ if (buffer == null) return;
+
+ byte[] copy = buffer.ToArray();
+ Stream source = Stream.Null;
+
+ int read = source.Read(new Span<byte>(buffer, offset, count));
+ Assert.Equal(0, read);
+ Assert.Equal(copy, buffer); // Make sure Read doesn't modify the buffer
+ Assert.Equal(0, source.Position);
+ }
+
+ [Theory]
+ [MemberData(nameof(NullStream_ReadWriteData))]
+ public void TestNullStream_WriteSpan(byte[] buffer, int offset, int count)
+ {
+ if (buffer == null) return;
+
+ byte[] copy = buffer.ToArray();
+ Stream source = Stream.Null;
+
+ source.Write(new Span<byte>(buffer, offset, count));
+ Assert.Equal(copy, buffer); // Make sure Write doesn't modify the buffer
+ Assert.Equal(0, source.Position);
+ }
+
+ [Fact]
+ public void DisposeAsync_Nop()
+ {
+ Assert.True(Stream.Null.DisposeAsync().IsCompletedSuccessfully);
+ Stream.Null.Write(new byte[42]); // still usable
+ }
+
public static IEnumerable<object[]> NullReaders
{
get
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Linq;
-using Xunit;
-
-namespace System.IO.Tests
-{
- public partial class NullTests
- {
- [Theory]
- [MemberData(nameof(NullStream_ReadWriteData))]
- public void TestNullStream_ReadSpan(byte[] buffer, int offset, int count)
- {
- if (buffer == null) return;
-
- byte[] copy = buffer.ToArray();
- Stream source = Stream.Null;
-
- int read = source.Read(new Span<byte>(buffer, offset, count));
- Assert.Equal(0, read);
- Assert.Equal(copy, buffer); // Make sure Read doesn't modify the buffer
- Assert.Equal(0, source.Position);
- }
-
- [Theory]
- [MemberData(nameof(NullStream_ReadWriteData))]
- public void TestNullStream_WriteSpan(byte[] buffer, int offset, int count)
- {
- if (buffer == null) return;
-
- byte[] copy = buffer.ToArray();
- Stream source = Stream.Null;
-
- source.Write(new Span<byte>(buffer, offset, count));
- Assert.Equal(copy, buffer); // Make sure Write doesn't modify the buffer
- Assert.Equal(0, source.Position);
- }
-
- [Fact]
- public void DisposeAsync_Nop()
- {
- Assert.True(Stream.Null.DisposeAsync().IsCompletedSuccessfully);
- Stream.Null.Write(new byte[42]); // still usable
- }
- }
-}
// See the LICENSE file in the project root for more information.
using System.Buffers;
-using System.Runtime.InteropServices;
-using System.Threading;
using System.Threading.Tasks;
using Xunit;
using System;
using System.Collections.Generic;
-using System.IO;
+using System.Linq;
using System.Text;
+using System.Threading;
using System.Threading.Tasks;
using Xunit;
Assert.Equal(Encoding.Unicode, sr.CurrentEncoding);
}
+
+ [Theory]
+ [InlineData(0)]
+ [InlineData(10)]
+ public async Task Read_EmptySpan_ReadsNothing(int length)
+ {
+ using (var r = new StreamReader(new MemoryStream(Enumerable.Repeat((byte)'s', length).ToArray())))
+ {
+ Assert.Equal(0, r.Read(Span<char>.Empty));
+ Assert.Equal(0, r.ReadBlock(Span<char>.Empty));
+ Assert.Equal(0, await r.ReadAsync(Memory<char>.Empty));
+ Assert.Equal(0, await r.ReadBlockAsync(Memory<char>.Empty));
+ }
+ }
+
+ [Theory]
+ [InlineData(1, 100, 1)]
+ [InlineData(1, 100, 101)]
+ [InlineData(100, 50, 1)]
+ [InlineData(100, 50, 101)]
+ public void Read_ReadsExpectedData(int readLength, int totalLength, int bufferSize)
+ {
+ var data = new char[totalLength];
+ var r = new Random(42);
+ for (int i = 0; i < data.Length; i++)
+ {
+ data[i] = (char)('a' + r.Next(0, 26));
+ }
+
+ var result = new char[data.Length];
+ Span<char> dst = result;
+
+ using (var sr = new StreamReader(new MemoryStream(data.Select(i => (byte)i).ToArray()), Encoding.ASCII, false, bufferSize))
+ {
+ while (dst.Length > 0)
+ {
+ int toRead = Math.Min(readLength, dst.Length);
+ int read = sr.Read(dst.Slice(0, toRead));
+ Assert.InRange(read, 1, dst.Length);
+ dst = dst.Slice(read);
+ }
+ }
+
+ Assert.Equal<char>(data, result);
+ }
+
+ [Theory]
+ [InlineData(1, 100, 1)]
+ [InlineData(1, 100, 101)]
+ [InlineData(100, 50, 1)]
+ [InlineData(100, 50, 101)]
+ public void ReadBlock_ReadsExpectedData(int readLength, int totalLength, int bufferSize)
+ {
+ var data = new char[totalLength];
+ var r = new Random(42);
+ for (int i = 0; i < data.Length; i++)
+ {
+ data[i] = (char)('a' + r.Next(0, 26));
+ }
+
+ var result = new char[data.Length];
+ Span<char> dst = result;
+
+ using (var sr = new StreamReader(new MemoryStream(data.Select(i => (byte)i).ToArray()), Encoding.ASCII, false, bufferSize))
+ {
+ while (dst.Length > 0)
+ {
+ int toRead = Math.Min(readLength, dst.Length);
+ int read = sr.ReadBlock(dst.Slice(0, toRead));
+ Assert.InRange(read, 1, dst.Length);
+ dst = dst.Slice(read);
+ }
+ }
+
+ Assert.Equal<char>(data, result);
+ }
+
+ [Theory]
+ [InlineData(1, 100, 1)]
+ [InlineData(1, 100, 101)]
+ [InlineData(100, 50, 1)]
+ [InlineData(100, 50, 101)]
+ public async Task ReadAsync_ReadsExpectedData(int readLength, int totalLength, int bufferSize)
+ {
+ var data = new char[totalLength];
+ var r = new Random(42);
+ for (int i = 0; i < data.Length; i++)
+ {
+ data[i] = (char)('a' + r.Next(0, 26));
+ }
+
+ var result = new char[data.Length];
+ Memory<char> dst = result;
+
+ using (var sr = new StreamReader(new MemoryStream(data.Select(i => (byte)i).ToArray()), Encoding.ASCII, false, bufferSize))
+ {
+ while (dst.Length > 0)
+ {
+ int toRead = Math.Min(readLength, dst.Length);
+ int read = await sr.ReadAsync(dst.Slice(0, toRead));
+ Assert.InRange(read, 1, dst.Length);
+ dst = dst.Slice(read);
+ }
+ }
+
+ Assert.Equal<char>(data, result);
+ }
+
+ [Theory]
+ [InlineData(1, 100, 1)]
+ [InlineData(1, 100, 101)]
+ [InlineData(100, 50, 1)]
+ [InlineData(100, 50, 101)]
+ public async Task ReadBlockAsync_ReadsExpectedData(int readLength, int totalLength, int bufferSize)
+ {
+ var data = new char[totalLength];
+ var r = new Random(42);
+ for (int i = 0; i < data.Length; i++)
+ {
+ data[i] = (char)('a' + r.Next(0, 26));
+ }
+
+ var result = new char[data.Length];
+ Memory<char> dst = result;
+
+ using (var sr = new StreamReader(new MemoryStream(data.Select(i => (byte)i).ToArray()), Encoding.ASCII, false, bufferSize))
+ {
+ while (dst.Length > 0)
+ {
+ int toRead = Math.Min(readLength, dst.Length);
+ int read = await sr.ReadBlockAsync(dst.Slice(0, toRead));
+ Assert.InRange(read, 1, dst.Length);
+ dst = dst.Slice(read);
+ }
+ }
+
+ Assert.Equal<char>(data, result);
+ }
+
+ [Fact]
+ public void ReadBlock_RepeatsReadsUntilReadDesiredAmount()
+ {
+ char[] data = "hello world".ToCharArray();
+ var ms = new MemoryStream(Encoding.UTF8.GetBytes(data));
+ var s = new DelegateStream(
+ canReadFunc: () => true,
+ readFunc: (buffer, offset, count) => ms.Read(buffer, offset, 1)); // do actual reads a byte at a time
+ using (var r = new StreamReader(s, Encoding.UTF8, false, 2))
+ {
+ var result = new char[data.Length];
+ Assert.Equal(data.Length, r.ReadBlock((Span<char>)result));
+ Assert.Equal<char>(data, result);
+ }
+ }
+
+ [Fact]
+ public async Task ReadBlockAsync_RepeatsReadsUntilReadDesiredAmount()
+ {
+ char[] data = "hello world".ToCharArray();
+ var ms = new MemoryStream(Encoding.UTF8.GetBytes(data));
+ var s = new DelegateStream(
+ canReadFunc: () => true,
+ readAsyncFunc: (buffer, offset, count, cancellationToken) => ms.ReadAsync(buffer, offset, 1)); // do actual reads a byte at a time
+ using (var r = new StreamReader(s, Encoding.UTF8, false, 2))
+ {
+ var result = new char[data.Length];
+ Assert.Equal(data.Length, await r.ReadBlockAsync((Memory<char>)result));
+ Assert.Equal<char>(data, result);
+ }
+ }
+
+ [Fact]
+ public async Task ReadAsync_Precanceled_ThrowsException()
+ {
+ using (var sr = new StreamReader(new MemoryStream()))
+ {
+ await Assert.ThrowsAnyAsync<OperationCanceledException>(() => sr.ReadAsync(Memory<char>.Empty, new CancellationToken(true)).AsTask());
+ await Assert.ThrowsAnyAsync<OperationCanceledException>(() => sr.ReadBlockAsync(Memory<char>.Empty, new CancellationToken(true)).AsTask());
+ }
+ }
+
+ [Fact]
+ public async Task Read_SpanMemory_DisposedStream_ThrowsException()
+ {
+ var sr = new StreamReader(new MemoryStream());
+ sr.Dispose();
+
+ Assert.Throws<ObjectDisposedException>(() => sr.Read(Span<char>.Empty));
+ Assert.Throws<ObjectDisposedException>(() => sr.ReadBlock(Span<char>.Empty));
+ await Assert.ThrowsAsync<ObjectDisposedException>(() => sr.ReadAsync(Memory<char>.Empty).AsTask());
+ await Assert.ThrowsAsync<ObjectDisposedException>(() => sr.ReadBlockAsync(Memory<char>.Empty).AsTask());
+ }
+
+ [Fact]
+ public void StreamReader_WithOptionalArguments()
+ {
+ byte[] ByteOrderMaskUtf7 = new byte[] { 0x2B, 0x2F, 0x76, 0x38 };
+ byte[] ByteOrderMaskUtf8 = new byte[] { 0xEF, 0xBB, 0xBF };
+ byte[] ByteOrderMaskUtf16_BE = new byte[] { 0xFE, 0xFF, 0x20, 0x20 };
+ byte[] ByteOrderMaskUtf16_LE = new byte[] { 0xFF, 0xFE, 0x20, 0x20 };
+ byte[] ByteOrderMaskUtf32 = new byte[] { 0x00, 0x00, 0xFE, 0xFF };
+
+ // check enabled leaveOpen and default encoding
+ using (var tempStream = new MemoryStream())
+ {
+ using (var sr = new StreamReader(tempStream, leaveOpen: true))
+ {
+ Assert.Equal(Encoding.UTF8, sr.CurrentEncoding);
+ }
+ Assert.True(tempStream.CanRead);
+ }
+
+ // check null encoding, default encoding, default leaveOpen
+ using (var tempStream = new MemoryStream())
+ {
+ using (var sr = new StreamReader(tempStream, encoding: null))
+ {
+ Assert.Equal(Encoding.UTF8, sr.CurrentEncoding);
+ }
+ Assert.False(tempStream.CanRead);
+ }
+
+ // check bufferSize, default BOM and default leaveOpen
+ using (var tempStream = new MemoryStream(ByteOrderMaskUtf16_BE))
+ {
+ using (var sr = new StreamReader(tempStream, bufferSize: -1))
+ {
+ sr.Read();
+ Assert.Equal(Encoding.BigEndianUnicode, sr.CurrentEncoding);
+ }
+ Assert.False(tempStream.CanRead);
+ }
+
+ // check BOM enabled/disabled encoding, enabled/disabled leaveOpen
+ using (var tempStream = new MemoryStream(ByteOrderMaskUtf16_BE))
+ {
+ // check disabled BOM, default encoding
+ using (var sr = new StreamReader(new MemoryStream(ByteOrderMaskUtf7), detectEncodingFromByteOrderMarks: false))
+ {
+ sr.Read();
+ Assert.Equal(Encoding.UTF8, sr.CurrentEncoding);
+ }
+
+ // check disabled BOM, default enconding and leaveOpen
+ tempStream.Seek(0, SeekOrigin.Begin);
+ using (var sr = new StreamReader(tempStream, detectEncodingFromByteOrderMarks: false, leaveOpen: true))
+ {
+ sr.Read();
+ Assert.Equal(Encoding.UTF8, sr.CurrentEncoding);
+ }
+ Assert.True(tempStream.CanRead);
+
+ // check enabled BOM and leaveOpen
+ tempStream.Seek(0, SeekOrigin.Begin);
+ using (var sr = new StreamReader(tempStream, detectEncodingFromByteOrderMarks: true))
+ {
+ sr.Read();
+ Assert.Equal(Encoding.BigEndianUnicode, sr.CurrentEncoding);
+ }
+ Assert.False(tempStream.CanRead);
+ }
+ }
}
}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Linq;
-using System.Text;
-using System.Threading;
-using System.Threading.Tasks;
-using Xunit;
-
-namespace System.IO.Tests
-{
- public partial class StreamReaderTests
- {
- [Theory]
- [InlineData(0)]
- [InlineData(10)]
- public async Task Read_EmptySpan_ReadsNothing(int length)
- {
- using (var r = new StreamReader(new MemoryStream(Enumerable.Repeat((byte)'s', length).ToArray())))
- {
- Assert.Equal(0, r.Read(Span<char>.Empty));
- Assert.Equal(0, r.ReadBlock(Span<char>.Empty));
- Assert.Equal(0, await r.ReadAsync(Memory<char>.Empty));
- Assert.Equal(0, await r.ReadBlockAsync(Memory<char>.Empty));
- }
- }
-
- [Theory]
- [InlineData(1, 100, 1)]
- [InlineData(1, 100, 101)]
- [InlineData(100, 50, 1)]
- [InlineData(100, 50, 101)]
- public void Read_ReadsExpectedData(int readLength, int totalLength, int bufferSize)
- {
- var data = new char[totalLength];
- var r = new Random(42);
- for (int i = 0; i < data.Length; i++)
- {
- data[i] = (char)('a' + r.Next(0, 26));
- }
-
- var result = new char[data.Length];
- Span<char> dst = result;
-
- using (var sr = new StreamReader(new MemoryStream(data.Select(i => (byte)i).ToArray()), Encoding.ASCII, false, bufferSize))
- {
- while (dst.Length > 0)
- {
- int toRead = Math.Min(readLength, dst.Length);
- int read = sr.Read(dst.Slice(0, toRead));
- Assert.InRange(read, 1, dst.Length);
- dst = dst.Slice(read);
- }
- }
-
- Assert.Equal<char>(data, result);
- }
-
- [Theory]
- [InlineData(1, 100, 1)]
- [InlineData(1, 100, 101)]
- [InlineData(100, 50, 1)]
- [InlineData(100, 50, 101)]
- public void ReadBlock_ReadsExpectedData(int readLength, int totalLength, int bufferSize)
- {
- var data = new char[totalLength];
- var r = new Random(42);
- for (int i = 0; i < data.Length; i++)
- {
- data[i] = (char)('a' + r.Next(0, 26));
- }
-
- var result = new char[data.Length];
- Span<char> dst = result;
-
- using (var sr = new StreamReader(new MemoryStream(data.Select(i => (byte)i).ToArray()), Encoding.ASCII, false, bufferSize))
- {
- while (dst.Length > 0)
- {
- int toRead = Math.Min(readLength, dst.Length);
- int read = sr.ReadBlock(dst.Slice(0, toRead));
- Assert.InRange(read, 1, dst.Length);
- dst = dst.Slice(read);
- }
- }
-
- Assert.Equal<char>(data, result);
- }
-
- [Theory]
- [InlineData(1, 100, 1)]
- [InlineData(1, 100, 101)]
- [InlineData(100, 50, 1)]
- [InlineData(100, 50, 101)]
- public async Task ReadAsync_ReadsExpectedData(int readLength, int totalLength, int bufferSize)
- {
- var data = new char[totalLength];
- var r = new Random(42);
- for (int i = 0; i < data.Length; i++)
- {
- data[i] = (char)('a' + r.Next(0, 26));
- }
-
- var result = new char[data.Length];
- Memory<char> dst = result;
-
- using (var sr = new StreamReader(new MemoryStream(data.Select(i => (byte)i).ToArray()), Encoding.ASCII, false, bufferSize))
- {
- while (dst.Length > 0)
- {
- int toRead = Math.Min(readLength, dst.Length);
- int read = await sr.ReadAsync(dst.Slice(0, toRead));
- Assert.InRange(read, 1, dst.Length);
- dst = dst.Slice(read);
- }
- }
-
- Assert.Equal<char>(data, result);
- }
-
- [Theory]
- [InlineData(1, 100, 1)]
- [InlineData(1, 100, 101)]
- [InlineData(100, 50, 1)]
- [InlineData(100, 50, 101)]
- public async Task ReadBlockAsync_ReadsExpectedData(int readLength, int totalLength, int bufferSize)
- {
- var data = new char[totalLength];
- var r = new Random(42);
- for (int i = 0; i < data.Length; i++)
- {
- data[i] = (char)('a' + r.Next(0, 26));
- }
-
- var result = new char[data.Length];
- Memory<char> dst = result;
-
- using (var sr = new StreamReader(new MemoryStream(data.Select(i => (byte)i).ToArray()), Encoding.ASCII, false, bufferSize))
- {
- while (dst.Length > 0)
- {
- int toRead = Math.Min(readLength, dst.Length);
- int read = await sr.ReadBlockAsync(dst.Slice(0, toRead));
- Assert.InRange(read, 1, dst.Length);
- dst = dst.Slice(read);
- }
- }
-
- Assert.Equal<char>(data, result);
- }
-
- [Fact]
- public void ReadBlock_RepeatsReadsUntilReadDesiredAmount()
- {
- char[] data = "hello world".ToCharArray();
- var ms = new MemoryStream(Encoding.UTF8.GetBytes(data));
- var s = new DelegateStream(
- canReadFunc: () => true,
- readFunc: (buffer, offset, count) => ms.Read(buffer, offset, 1)); // do actual reads a byte at a time
- using (var r = new StreamReader(s, Encoding.UTF8, false, 2))
- {
- var result = new char[data.Length];
- Assert.Equal(data.Length, r.ReadBlock((Span<char>)result));
- Assert.Equal<char>(data, result);
- }
- }
-
- [Fact]
- public async Task ReadBlockAsync_RepeatsReadsUntilReadDesiredAmount()
- {
- char[] data = "hello world".ToCharArray();
- var ms = new MemoryStream(Encoding.UTF8.GetBytes(data));
- var s = new DelegateStream(
- canReadFunc: () => true,
- readAsyncFunc: (buffer, offset, count, cancellationToken) => ms.ReadAsync(buffer, offset, 1)); // do actual reads a byte at a time
- using (var r = new StreamReader(s, Encoding.UTF8, false, 2))
- {
- var result = new char[data.Length];
- Assert.Equal(data.Length, await r.ReadBlockAsync((Memory<char>)result));
- Assert.Equal<char>(data, result);
- }
- }
-
- [Fact]
- public async Task ReadAsync_Precanceled_ThrowsException()
- {
- using (var sr = new StreamReader(new MemoryStream()))
- {
- await Assert.ThrowsAnyAsync<OperationCanceledException>(() => sr.ReadAsync(Memory<char>.Empty, new CancellationToken(true)).AsTask());
- await Assert.ThrowsAnyAsync<OperationCanceledException>(() => sr.ReadBlockAsync(Memory<char>.Empty, new CancellationToken(true)).AsTask());
- }
- }
-
- [Fact]
- public async Task Read_SpanMemory_DisposedStream_ThrowsException()
- {
- var sr = new StreamReader(new MemoryStream());
- sr.Dispose();
-
- Assert.Throws<ObjectDisposedException>(() => sr.Read(Span<char>.Empty));
- Assert.Throws<ObjectDisposedException>(() => sr.ReadBlock(Span<char>.Empty));
- await Assert.ThrowsAsync<ObjectDisposedException>(() => sr.ReadAsync(Memory<char>.Empty).AsTask());
- await Assert.ThrowsAsync<ObjectDisposedException>(() => sr.ReadBlockAsync(Memory<char>.Empty).AsTask());
- }
-
- [Fact]
- public void StreamReader_WithOptionalArguments()
- {
- byte[] ByteOrderMaskUtf7 = new byte[] { 0x2B, 0x2F, 0x76, 0x38 };
- byte[] ByteOrderMaskUtf8 = new byte[] { 0xEF, 0xBB, 0xBF };
- byte[] ByteOrderMaskUtf16_BE = new byte[] { 0xFE, 0xFF, 0x20, 0x20 };
- byte[] ByteOrderMaskUtf16_LE = new byte[] { 0xFF, 0xFE, 0x20, 0x20 };
- byte[] ByteOrderMaskUtf32 = new byte[] { 0x00, 0x00, 0xFE, 0xFF };
-
- // check enabled leaveOpen and default encoding
- using (var tempStream = new MemoryStream())
- {
- using (var sr = new StreamReader(tempStream, leaveOpen: true))
- {
- Assert.Equal(Encoding.UTF8, sr.CurrentEncoding);
- }
- Assert.True(tempStream.CanRead);
- }
-
- // check null encoding, default encoding, default leaveOpen
- using (var tempStream = new MemoryStream())
- {
- using (var sr = new StreamReader(tempStream, encoding: null))
- {
- Assert.Equal(Encoding.UTF8, sr.CurrentEncoding);
- }
- Assert.False(tempStream.CanRead);
- }
-
- // check bufferSize, default BOM and default leaveOpen
- using (var tempStream = new MemoryStream(ByteOrderMaskUtf16_BE))
- {
- using (var sr = new StreamReader(tempStream, bufferSize: -1))
- {
- sr.Read();
- Assert.Equal(Encoding.BigEndianUnicode, sr.CurrentEncoding);
- }
- Assert.False(tempStream.CanRead);
- }
-
- // check BOM enabled/disabled encoding, enabled/disabled leaveOpen
- using (var tempStream = new MemoryStream(ByteOrderMaskUtf16_BE))
- {
- // check disabled BOM, default encoding
- using (var sr = new StreamReader(new MemoryStream(ByteOrderMaskUtf7), detectEncodingFromByteOrderMarks: false))
- {
- sr.Read();
- Assert.Equal(Encoding.UTF8, sr.CurrentEncoding);
- }
-
- // check disabled BOM, default enconding and leaveOpen
- tempStream.Seek(0, SeekOrigin.Begin);
- using (var sr = new StreamReader(tempStream, detectEncodingFromByteOrderMarks: false, leaveOpen: true))
- {
- sr.Read();
- Assert.Equal(Encoding.UTF8, sr.CurrentEncoding);
- }
- Assert.True(tempStream.CanRead);
-
- // check enabled BOM and leaveOpen
- tempStream.Seek(0, SeekOrigin.Begin);
- using (var sr = new StreamReader(tempStream, detectEncodingFromByteOrderMarks: true))
- {
- sr.Read();
- Assert.Equal(Encoding.BigEndianUnicode, sr.CurrentEncoding);
- }
- Assert.False(tempStream.CanRead);
- }
- }
- }
-}
namespace System.IO.Tests
{
- public partial class StreamWriterTests
+ public class StreamWriterTests
{
[Fact]
// See the LICENSE file in the project root for more information.
using System;
-using System.IO;
+using System.Linq;
using System.Text;
+using System.Threading;
using System.Threading.Tasks;
using Xunit;
}
}
}
+
+ [Fact]
+ public void Write_EmptySpan_WritesNothing()
+ {
+ using (var s = new MemoryStream())
+ using (var writer = new StreamWriter(s))
+ {
+ writer.Write(ReadOnlySpan<char>.Empty);
+ writer.Flush();
+ Assert.Equal(0, s.Position);
+ }
+ }
+
+ [Fact]
+ public void WriteLine_EmptySpan_WritesNewLine()
+ {
+ using (var s = new MemoryStream())
+ using (var writer = new StreamWriter(s))
+ {
+ writer.WriteLine(ReadOnlySpan<char>.Empty);
+ writer.Flush();
+ Assert.Equal(Environment.NewLine.Length, s.Position);
+ }
+ }
+
+ [Fact]
+ public async Task WriteAsync_EmptyMemory_WritesNothing()
+ {
+ using (var s = new MemoryStream())
+ using (var writer = new StreamWriter(s))
+ {
+ await writer.WriteAsync(ReadOnlyMemory<char>.Empty);
+ await writer.FlushAsync();
+ Assert.Equal(0, s.Position);
+ }
+ }
+
+ [Fact]
+ public async Task WriteLineAsync_EmptyMemory_WritesNothing()
+ {
+ using (var s = new MemoryStream())
+ using (var writer = new StreamWriter(s))
+ {
+ await writer.WriteLineAsync(ReadOnlyMemory<char>.Empty);
+ await writer.FlushAsync();
+ Assert.Equal(Environment.NewLine.Length, s.Position);
+ }
+ }
+
+ [Theory]
+ [InlineData(1, 1, 1, false)]
+ [InlineData(100, 1, 100, false)]
+ [InlineData(100, 10, 3, false)]
+ [InlineData(1, 1, 1, true)]
+ [InlineData(100, 1, 100, true)]
+ [InlineData(100, 10, 3, true)]
+ public void Write_Span_WritesExpectedData(int length, int writeSize, int writerBufferSize, bool autoFlush)
+ {
+ using (var s = new MemoryStream())
+ using (var writer = new StreamWriter(s, Encoding.ASCII, writerBufferSize) { AutoFlush = autoFlush })
+ {
+ var data = new char[length];
+ var rand = new Random(42);
+ for (int i = 0; i < data.Length; i++)
+ {
+ data[i] = (char)(rand.Next(0, 26) + 'a');
+ }
+
+ Span<char> source = data;
+ while (source.Length > 0)
+ {
+ int n = Math.Min(source.Length, writeSize);
+ writer.Write(source.Slice(0, n));
+ source = source.Slice(n);
+ }
+
+ writer.Flush();
+
+ Assert.Equal(data, s.ToArray().Select(b => (char)b));
+ }
+ }
+
+ [Theory]
+ [InlineData(1, 1, 1, false)]
+ [InlineData(100, 1, 100, false)]
+ [InlineData(100, 10, 3, false)]
+ [InlineData(1, 1, 1, true)]
+ [InlineData(100, 1, 100, true)]
+ [InlineData(100, 10, 3, true)]
+ public async Task Write_Memory_WritesExpectedData(int length, int writeSize, int writerBufferSize, bool autoFlush)
+ {
+ using (var s = new MemoryStream())
+ using (var writer = new StreamWriter(s, Encoding.ASCII, writerBufferSize) { AutoFlush = autoFlush })
+ {
+ var data = new char[length];
+ var rand = new Random(42);
+ for (int i = 0; i < data.Length; i++)
+ {
+ data[i] = (char)(rand.Next(0, 26) + 'a');
+ }
+
+ ReadOnlyMemory<char> source = data;
+ while (source.Length > 0)
+ {
+ int n = Math.Min(source.Length, writeSize);
+ await writer.WriteAsync(source.Slice(0, n));
+ source = source.Slice(n);
+ }
+
+ await writer.FlushAsync();
+
+ Assert.Equal(data, s.ToArray().Select(b => (char)b));
+ }
+ }
+
+ [Theory]
+ [InlineData(1, 1, 1, false)]
+ [InlineData(100, 1, 100, false)]
+ [InlineData(100, 10, 3, false)]
+ [InlineData(1, 1, 1, true)]
+ [InlineData(100, 1, 100, true)]
+ [InlineData(100, 10, 3, true)]
+ public void WriteLine_Span_WritesExpectedData(int length, int writeSize, int writerBufferSize, bool autoFlush)
+ {
+ using (var s = new MemoryStream())
+ using (var writer = new StreamWriter(s, Encoding.ASCII, writerBufferSize) { AutoFlush = autoFlush })
+ {
+ var data = new char[length];
+ var rand = new Random(42);
+ for (int i = 0; i < data.Length; i++)
+ {
+ data[i] = (char)(rand.Next(0, 26) + 'a');
+ }
+
+ Span<char> source = data;
+ while (source.Length > 0)
+ {
+ int n = Math.Min(source.Length, writeSize);
+ writer.WriteLine(source.Slice(0, n));
+ source = source.Slice(n);
+ }
+
+ writer.Flush();
+
+ Assert.Equal(length + (Environment.NewLine.Length * (length / writeSize)), s.Length);
+ }
+ }
+
+ [Theory]
+ [InlineData(1, 1, 1, false)]
+ [InlineData(100, 1, 100, false)]
+ [InlineData(100, 10, 3, false)]
+ [InlineData(1, 1, 1, true)]
+ [InlineData(100, 1, 100, true)]
+ [InlineData(100, 10, 3, true)]
+ public async Task WriteLineAsync_Memory_WritesExpectedData(int length, int writeSize, int writerBufferSize, bool autoFlush)
+ {
+ using (var s = new MemoryStream())
+ using (var writer = new StreamWriter(s, Encoding.ASCII, writerBufferSize) { AutoFlush = autoFlush })
+ {
+ var data = new char[length];
+ var rand = new Random(42);
+ for (int i = 0; i < data.Length; i++)
+ {
+ data[i] = (char)(rand.Next(0, 26) + 'a');
+ }
+
+ ReadOnlyMemory<char> source = data;
+ while (source.Length > 0)
+ {
+ int n = Math.Min(source.Length, writeSize);
+ await writer.WriteLineAsync(source.Slice(0, n));
+ source = source.Slice(n);
+ }
+
+ await writer.FlushAsync();
+
+ Assert.Equal(length + (Environment.NewLine.Length * (length / writeSize)), s.Length);
+ }
+ }
+
+ [Fact]
+ public async Task WriteAsync_Precanceled_ThrowsCancellationException()
+ {
+ using (var writer = new StreamWriter(Stream.Null))
+ {
+ await Assert.ThrowsAnyAsync<OperationCanceledException>(() => writer.WriteAsync(ReadOnlyMemory<char>.Empty, new CancellationToken(true)));
+ await Assert.ThrowsAnyAsync<OperationCanceledException>(() => writer.WriteLineAsync(ReadOnlyMemory<char>.Empty, new CancellationToken(true)));
+ }
+ }
+
+ [Fact]
+ public void StreamWriter_WithOptionalArguments_NoExceptions()
+ {
+ Encoding UTF8NoBOM = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);
+
+ // check enabled leaveOpen and default encoding
+ using (var tempStream = new MemoryStream())
+ {
+ using (var sw = new StreamWriter(tempStream, leaveOpen: true))
+ {
+ Assert.Equal(UTF8NoBOM, sw.Encoding);
+ }
+ Assert.True(tempStream.CanRead);
+ }
+
+ // check null encoding, default encoding, default leaveOpen
+ using (var tempStream = new MemoryStream())
+ {
+ using (var sw = new StreamWriter(tempStream, encoding: null))
+ {
+ Assert.Equal(UTF8NoBOM, sw.Encoding);
+ }
+ Assert.False(tempStream.CanRead);
+ }
+
+ // check bufferSize, default BOM, default leaveOpen
+ using (var tempStream = new MemoryStream())
+ {
+ using (var sw = new StreamWriter(tempStream, bufferSize: -1))
+ {
+ Assert.Equal(UTF8NoBOM, sw.Encoding);
+ }
+ Assert.False(tempStream.CanRead);
+ }
+ }
}
}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Linq;
-using System.Text;
-using System.Threading;
-using System.Threading.Tasks;
-using Xunit;
-
-namespace System.IO.Tests
-{
- public partial class StreamWriterTests
- {
- [Fact]
- public void Write_EmptySpan_WritesNothing()
- {
- using (var s = new MemoryStream())
- using (var writer = new StreamWriter(s))
- {
- writer.Write(ReadOnlySpan<char>.Empty);
- writer.Flush();
- Assert.Equal(0, s.Position);
- }
- }
-
- [Fact]
- public void WriteLine_EmptySpan_WritesNewLine()
- {
- using (var s = new MemoryStream())
- using (var writer = new StreamWriter(s))
- {
- writer.WriteLine(ReadOnlySpan<char>.Empty);
- writer.Flush();
- Assert.Equal(Environment.NewLine.Length, s.Position);
- }
- }
-
- [Fact]
- public async Task WriteAsync_EmptyMemory_WritesNothing()
- {
- using (var s = new MemoryStream())
- using (var writer = new StreamWriter(s))
- {
- await writer.WriteAsync(ReadOnlyMemory<char>.Empty);
- await writer.FlushAsync();
- Assert.Equal(0, s.Position);
- }
- }
-
- [Fact]
- public async Task WriteLineAsync_EmptyMemory_WritesNothing()
- {
- using (var s = new MemoryStream())
- using (var writer = new StreamWriter(s))
- {
- await writer.WriteLineAsync(ReadOnlyMemory<char>.Empty);
- await writer.FlushAsync();
- Assert.Equal(Environment.NewLine.Length, s.Position);
- }
- }
-
- [Theory]
- [InlineData(1, 1, 1, false)]
- [InlineData(100, 1, 100, false)]
- [InlineData(100, 10, 3, false)]
- [InlineData(1, 1, 1, true)]
- [InlineData(100, 1, 100, true)]
- [InlineData(100, 10, 3, true)]
- public void Write_Span_WritesExpectedData(int length, int writeSize, int writerBufferSize, bool autoFlush)
- {
- using (var s = new MemoryStream())
- using (var writer = new StreamWriter(s, Encoding.ASCII, writerBufferSize) { AutoFlush = autoFlush })
- {
- var data = new char[length];
- var rand = new Random(42);
- for (int i = 0; i < data.Length; i++)
- {
- data[i] = (char)(rand.Next(0, 26) + 'a');
- }
-
- Span<char> source = data;
- while (source.Length > 0)
- {
- int n = Math.Min(source.Length, writeSize);
- writer.Write(source.Slice(0, n));
- source = source.Slice(n);
- }
-
- writer.Flush();
-
- Assert.Equal(data, s.ToArray().Select(b => (char)b));
- }
- }
-
- [Theory]
- [InlineData(1, 1, 1, false)]
- [InlineData(100, 1, 100, false)]
- [InlineData(100, 10, 3, false)]
- [InlineData(1, 1, 1, true)]
- [InlineData(100, 1, 100, true)]
- [InlineData(100, 10, 3, true)]
- public async Task Write_Memory_WritesExpectedData(int length, int writeSize, int writerBufferSize, bool autoFlush)
- {
- using (var s = new MemoryStream())
- using (var writer = new StreamWriter(s, Encoding.ASCII, writerBufferSize) { AutoFlush = autoFlush })
- {
- var data = new char[length];
- var rand = new Random(42);
- for (int i = 0; i < data.Length; i++)
- {
- data[i] = (char)(rand.Next(0, 26) + 'a');
- }
-
- ReadOnlyMemory<char> source = data;
- while (source.Length > 0)
- {
- int n = Math.Min(source.Length, writeSize);
- await writer.WriteAsync(source.Slice(0, n));
- source = source.Slice(n);
- }
-
- await writer.FlushAsync();
-
- Assert.Equal(data, s.ToArray().Select(b => (char)b));
- }
- }
-
- [Theory]
- [InlineData(1, 1, 1, false)]
- [InlineData(100, 1, 100, false)]
- [InlineData(100, 10, 3, false)]
- [InlineData(1, 1, 1, true)]
- [InlineData(100, 1, 100, true)]
- [InlineData(100, 10, 3, true)]
- public void WriteLine_Span_WritesExpectedData(int length, int writeSize, int writerBufferSize, bool autoFlush)
- {
- using (var s = new MemoryStream())
- using (var writer = new StreamWriter(s, Encoding.ASCII, writerBufferSize) { AutoFlush = autoFlush })
- {
- var data = new char[length];
- var rand = new Random(42);
- for (int i = 0; i < data.Length; i++)
- {
- data[i] = (char)(rand.Next(0, 26) + 'a');
- }
-
- Span<char> source = data;
- while (source.Length > 0)
- {
- int n = Math.Min(source.Length, writeSize);
- writer.WriteLine(source.Slice(0, n));
- source = source.Slice(n);
- }
-
- writer.Flush();
-
- Assert.Equal(length + (Environment.NewLine.Length * (length / writeSize)), s.Length);
- }
- }
-
- [Theory]
- [InlineData(1, 1, 1, false)]
- [InlineData(100, 1, 100, false)]
- [InlineData(100, 10, 3, false)]
- [InlineData(1, 1, 1, true)]
- [InlineData(100, 1, 100, true)]
- [InlineData(100, 10, 3, true)]
- public async Task WriteLineAsync_Memory_WritesExpectedData(int length, int writeSize, int writerBufferSize, bool autoFlush)
- {
- using (var s = new MemoryStream())
- using (var writer = new StreamWriter(s, Encoding.ASCII, writerBufferSize) { AutoFlush = autoFlush })
- {
- var data = new char[length];
- var rand = new Random(42);
- for (int i = 0; i < data.Length; i++)
- {
- data[i] = (char)(rand.Next(0, 26) + 'a');
- }
-
- ReadOnlyMemory<char> source = data;
- while (source.Length > 0)
- {
- int n = Math.Min(source.Length, writeSize);
- await writer.WriteLineAsync(source.Slice(0, n));
- source = source.Slice(n);
- }
-
- await writer.FlushAsync();
-
- Assert.Equal(length + (Environment.NewLine.Length * (length / writeSize)), s.Length);
- }
- }
-
- [Fact]
- public async Task WriteAsync_Precanceled_ThrowsCancellationException()
- {
- using (var writer = new StreamWriter(Stream.Null))
- {
- await Assert.ThrowsAnyAsync<OperationCanceledException>(() => writer.WriteAsync(ReadOnlyMemory<char>.Empty, new CancellationToken(true)));
- await Assert.ThrowsAnyAsync<OperationCanceledException>(() => writer.WriteLineAsync(ReadOnlyMemory<char>.Empty, new CancellationToken(true)));
- }
- }
-
- [Fact]
- public void StreamWriter_WithOptionalArguments_NoExceptions()
- {
- Encoding UTF8NoBOM = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);
-
- // check enabled leaveOpen and default encoding
- using (var tempStream = new MemoryStream())
- {
- using (var sw = new StreamWriter(tempStream, leaveOpen: true))
- {
- Assert.Equal(UTF8NoBOM, sw.Encoding);
- }
- Assert.True(tempStream.CanRead);
- }
-
- // check null encoding, default encoding, default leaveOpen
- using (var tempStream = new MemoryStream())
- {
- using (var sw = new StreamWriter(tempStream, encoding: null))
- {
- Assert.Equal(UTF8NoBOM, sw.Encoding);
- }
- Assert.False(tempStream.CanRead);
- }
-
- // check bufferSize, default BOM, default leaveOpen
- using (var tempStream = new MemoryStream())
- {
- using (var sw = new StreamWriter(tempStream, bufferSize: -1))
- {
- Assert.Equal(UTF8NoBOM, sw.Encoding);
- }
- Assert.False(tempStream.CanRead);
- }
- }
- }
-}
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using System;
-using System.IO;
+using System.Threading;
+using System.Threading.Tasks;
using Xunit;
namespace System.IO.Tests
{
- public partial class StringReaderTests
+ public class StringReaderTests
{
[Fact]
public static void StringReaderWithNullString()
ValidateDisposedExceptions(sr);
}
+ [Fact]
+ public void ReadSpan_Success()
+ {
+ string input = "abcdef";
+ var reader = new StringReader(input);
+ Span<char> s = new char[2];
+
+ Assert.Equal(2, reader.Read(s));
+ Assert.Equal("ab", new string(s.ToArray()));
+
+ Assert.Equal(1, reader.Read(s.Slice(0, 1)));
+ Assert.Equal("cb", new string(s.ToArray()));
+
+ Assert.Equal(2, reader.Read(s));
+ Assert.Equal("de", new string(s.ToArray()));
+
+ Assert.Equal(1, reader.Read(s));
+ Assert.Equal("f", new string(s.Slice(0, 1).ToArray()));
+
+ Assert.Equal(0, reader.Read(s));
+ }
+
+ [Fact]
+ public void ReadBlockSpan_Success()
+ {
+ string input = "abcdef";
+ var reader = new StringReader(input);
+ Span<char> s = new char[2];
+
+ Assert.Equal(2, reader.ReadBlock(s));
+ Assert.Equal("ab", new string(s.ToArray()));
+
+ Assert.Equal(1, reader.ReadBlock(s.Slice(0, 1)));
+ Assert.Equal("cb", new string(s.ToArray()));
+
+ Assert.Equal(2, reader.ReadBlock(s));
+ Assert.Equal("de", new string(s.ToArray()));
+
+ Assert.Equal(1, reader.ReadBlock(s));
+ Assert.Equal("f", new string(s.Slice(0, 1).ToArray()));
+
+ Assert.Equal(0, reader.ReadBlock(s));
+ }
+
+ [Fact]
+ public async Task ReadMemoryAsync_Success()
+ {
+ string input = "abcdef";
+ var reader = new StringReader(input);
+ Memory<char> m = new char[2];
+
+ Assert.Equal(2, await reader.ReadAsync(m));
+ Assert.Equal("ab", new string(m.ToArray()));
+
+ Assert.Equal(1, await reader.ReadAsync(m.Slice(0, 1)));
+ Assert.Equal("cb", new string(m.ToArray()));
+
+ Assert.Equal(2, await reader.ReadAsync(m));
+ Assert.Equal("de", new string(m.ToArray()));
+
+ Assert.Equal(1, await reader.ReadAsync(m));
+ Assert.Equal("f", new string(m.Slice(0, 1).ToArray()));
+
+ Assert.Equal(0, await reader.ReadAsync(m));
+ }
+
+ [Fact]
+ public async Task ReadBlockMemoryAsync_Success()
+ {
+ string input = "abcdef";
+ var reader = new StringReader(input);
+ Memory<char> m = new char[2];
+
+ Assert.Equal(2, await reader.ReadBlockAsync(m));
+ Assert.Equal("ab", new string(m.ToArray()));
+
+ Assert.Equal(1, await reader.ReadBlockAsync(m.Slice(0, 1)));
+ Assert.Equal("cb", new string(m.ToArray()));
+
+ Assert.Equal(2, await reader.ReadBlockAsync(m));
+ Assert.Equal("de", new string(m.ToArray()));
+
+ Assert.Equal(1, await reader.ReadBlockAsync(m));
+ Assert.Equal("f", new string(m.Slice(0, 1).ToArray()));
+
+ Assert.Equal(0, await reader.ReadBlockAsync(m));
+ }
+
+ [Fact]
+ public void Disposed_ThrowsException()
+ {
+ var reader = new StringReader("abc");
+ reader.Dispose();
+
+ Assert.Throws<ObjectDisposedException>(() => reader.Read(Span<char>.Empty));
+ Assert.Throws<ObjectDisposedException>(() => reader.ReadBlock(Span<char>.Empty));
+ Assert.Throws<ObjectDisposedException>(() => { reader.ReadAsync(Memory<char>.Empty); });
+ Assert.Throws<ObjectDisposedException>(() => { reader.ReadBlockAsync(Memory<char>.Empty); });
+ }
+
+ [Fact]
+ public async Task Precanceled_ThrowsException()
+ {
+ var reader = new StringReader("abc");
+
+ await Assert.ThrowsAnyAsync<OperationCanceledException>(() => reader.ReadAsync(Memory<char>.Empty, new CancellationToken(true)).AsTask());
+ await Assert.ThrowsAnyAsync<OperationCanceledException>(() => reader.ReadBlockAsync(Memory<char>.Empty, new CancellationToken(true)).AsTask());
+ }
+
private static void ValidateDisposedExceptions(StringReader sr)
{
Assert.Throws<ObjectDisposedException>(() => { sr.Peek(); });
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Threading;
-using System.Threading.Tasks;
-using Xunit;
-
-namespace System.IO.Tests
-{
- public partial class StringReaderTests
- {
- [Fact]
- public void ReadSpan_Success()
- {
- string input = "abcdef";
- var reader = new StringReader(input);
- Span<char> s = new char[2];
-
- Assert.Equal(2, reader.Read(s));
- Assert.Equal("ab", new string(s.ToArray()));
-
- Assert.Equal(1, reader.Read(s.Slice(0, 1)));
- Assert.Equal("cb", new string(s.ToArray()));
-
- Assert.Equal(2, reader.Read(s));
- Assert.Equal("de", new string(s.ToArray()));
-
- Assert.Equal(1, reader.Read(s));
- Assert.Equal("f", new string(s.Slice(0, 1).ToArray()));
-
- Assert.Equal(0, reader.Read(s));
- }
-
- [Fact]
- public void ReadBlockSpan_Success()
- {
- string input = "abcdef";
- var reader = new StringReader(input);
- Span<char> s = new char[2];
-
- Assert.Equal(2, reader.ReadBlock(s));
- Assert.Equal("ab", new string(s.ToArray()));
-
- Assert.Equal(1, reader.ReadBlock(s.Slice(0, 1)));
- Assert.Equal("cb", new string(s.ToArray()));
-
- Assert.Equal(2, reader.ReadBlock(s));
- Assert.Equal("de", new string(s.ToArray()));
-
- Assert.Equal(1, reader.ReadBlock(s));
- Assert.Equal("f", new string(s.Slice(0, 1).ToArray()));
-
- Assert.Equal(0, reader.ReadBlock(s));
- }
-
- [Fact]
- public async Task ReadMemoryAsync_Success()
- {
- string input = "abcdef";
- var reader = new StringReader(input);
- Memory<char> m = new char[2];
-
- Assert.Equal(2, await reader.ReadAsync(m));
- Assert.Equal("ab", new string(m.ToArray()));
-
- Assert.Equal(1, await reader.ReadAsync(m.Slice(0, 1)));
- Assert.Equal("cb", new string(m.ToArray()));
-
- Assert.Equal(2, await reader.ReadAsync(m));
- Assert.Equal("de", new string(m.ToArray()));
-
- Assert.Equal(1, await reader.ReadAsync(m));
- Assert.Equal("f", new string(m.Slice(0, 1).ToArray()));
-
- Assert.Equal(0, await reader.ReadAsync(m));
- }
-
- [Fact]
- public async Task ReadBlockMemoryAsync_Success()
- {
- string input = "abcdef";
- var reader = new StringReader(input);
- Memory<char> m = new char[2];
-
- Assert.Equal(2, await reader.ReadBlockAsync(m));
- Assert.Equal("ab", new string(m.ToArray()));
-
- Assert.Equal(1, await reader.ReadBlockAsync(m.Slice(0, 1)));
- Assert.Equal("cb", new string(m.ToArray()));
-
- Assert.Equal(2, await reader.ReadBlockAsync(m));
- Assert.Equal("de", new string(m.ToArray()));
-
- Assert.Equal(1, await reader.ReadBlockAsync(m));
- Assert.Equal("f", new string(m.Slice(0, 1).ToArray()));
-
- Assert.Equal(0, await reader.ReadBlockAsync(m));
- }
-
- [Fact]
- public void Disposed_ThrowsException()
- {
- var reader = new StringReader("abc");
- reader.Dispose();
-
- Assert.Throws<ObjectDisposedException>(() => reader.Read(Span<char>.Empty));
- Assert.Throws<ObjectDisposedException>(() => reader.ReadBlock(Span<char>.Empty));
- Assert.Throws<ObjectDisposedException>(() => { reader.ReadAsync(Memory<char>.Empty); });
- Assert.Throws<ObjectDisposedException>(() => { reader.ReadBlockAsync(Memory<char>.Empty); });
- }
-
- [Fact]
- public async Task Precanceled_ThrowsException()
- {
- var reader = new StringReader("abc");
-
- await Assert.ThrowsAnyAsync<OperationCanceledException>(() => reader.ReadAsync(Memory<char>.Empty, new CancellationToken(true)).AsTask());
- await Assert.ThrowsAnyAsync<OperationCanceledException>(() => reader.ReadBlockAsync(Memory<char>.Empty, new CancellationToken(true)).AsTask());
- }
- }
-}
// See the LICENSE file in the project root for more information.
using System;
-using System.Diagnostics;
using System.Globalization;
-using System.IO;
using System.Tests;
using System.Text;
+using System.Threading;
using System.Threading.Tasks;
-using Microsoft.DotNet.RemoteExecutor;
using Xunit;
namespace System.IO.Tests
{
- public partial class StringWriterTests
+ public class StringWriterTests
{
static int[] iArrInvalidValues = new int[] { -1, -2, -100, -1000, -10000, -100000, -1000000, -10000000, -100000000, -1000000000, int.MinValue, short.MinValue };
static int[] iArrLargeValues = new int[] { int.MaxValue, int.MaxValue - 1, int.MaxValue / 2, int.MaxValue / 10, int.MaxValue / 100 };
}
}
}
+
+ [Fact]
+ public async Task WriteSpanMemory_Success()
+ {
+ var sw = new StringWriter();
+
+ sw.Write((Span<char>)new char[0]);
+ sw.Write((Span<char>)new char[] { 'a' });
+ sw.Write((Span<char>)new char[] { 'b', 'c', 'd' });
+ sw.WriteLine((Span<char>)new char[] { 'e' });
+
+ await sw.WriteAsync((ReadOnlyMemory<char>)new char[0]);
+ await sw.WriteAsync((ReadOnlyMemory<char>)new char[] { 'f' });
+ await sw.WriteAsync((ReadOnlyMemory<char>)new char[] { 'g', 'h', 'i' });
+ await sw.WriteLineAsync((ReadOnlyMemory<char>)new char[] { 'j' });
+
+ Assert.Equal("abcde" + Environment.NewLine + "fghij" + Environment.NewLine, sw.ToString());
+ }
+
+ [Fact]
+ public async Task Precanceled_ThrowsException()
+ {
+ var writer = new StringWriter();
+
+ await Assert.ThrowsAnyAsync<OperationCanceledException>(() => writer.WriteAsync(Memory<char>.Empty, new CancellationToken(true)));
+ await Assert.ThrowsAnyAsync<OperationCanceledException>(() => writer.WriteLineAsync(Memory<char>.Empty, new CancellationToken(true)));
+ }
+
+ [Fact]
+ public void TestWriteStringBuilder()
+ {
+ StringBuilder sb = getSb();
+ StringWriter sw = new StringWriter();
+ sw.Write(sb);
+ Assert.Equal(sb.ToString(), sw.ToString());
+ }
+
+ [Fact]
+ public async Task TestWriteAsyncStringBuilder()
+ {
+ StringBuilder sb = getSb();
+ StringWriter sw = new StringWriter();
+ await sw.WriteAsync(sb);
+ Assert.Equal(sb.ToString(), sw.ToString());
+ }
+
+ [Fact]
+ public void TestWriteAsyncStringBuilderCancelled()
+ {
+ StringBuilder sb = getSb();
+ StringWriter sw = new StringWriter();
+ CancellationTokenSource cts = new CancellationTokenSource();
+ cts.Cancel();
+ Assert.Equal(TaskStatus.Canceled, sw.WriteAsync(sb, cts.Token).Status);
+ }
+
+ [Fact]
+ public void TestWriteLineStringBuilder()
+ {
+ StringBuilder sb = getSb();
+ StringWriter sw = new StringWriter();
+ sw.WriteLine(sb);
+ Assert.Equal(sb.ToString() + Environment.NewLine, sw.ToString());
+ }
+
+ [Fact]
+ public async Task TestWriteLineAsyncStringBuilder()
+ {
+ StringBuilder sb = getSb();
+ StringWriter sw = new StringWriter();
+ await sw.WriteLineAsync(sb);
+ Assert.Equal(sb.ToString() + Environment.NewLine, sw.ToString());
+ }
+
+ [Fact]
+ public void TestWriteLineAsyncStringBuilderCancelled()
+ {
+ StringBuilder sb = getSb();
+ StringWriter sw = new StringWriter();
+ CancellationTokenSource cts = new CancellationTokenSource();
+ cts.Cancel();
+ Assert.Equal(TaskStatus.Canceled, sw.WriteLineAsync(sb, cts.Token).Status);
+ }
+
+ [Fact]
+ public void DisposeAsync_ClosesWriterAndLeavesBuilderAvailable()
+ {
+ var sb = new StringBuilder();
+ var sw = new StringWriter(sb);
+ sw.Write("hello");
+ Assert.True(sw.DisposeAsync().IsCompletedSuccessfully);
+ Assert.True(sw.DisposeAsync().IsCompletedSuccessfully);
+ Assert.Throws<ObjectDisposedException>(() => sw.Write(42));
+ Assert.Equal("hello", sb.ToString());
+ }
}
}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Text;
-using System.Threading;
-using System.Threading.Tasks;
-using Xunit;
-
-namespace System.IO.Tests
-{
- public partial class StringWriterTests
- {
- [Fact]
- public async Task WriteSpanMemory_Success()
- {
- var sw = new StringWriter();
-
- sw.Write((Span<char>)new char[0]);
- sw.Write((Span<char>)new char[] { 'a' });
- sw.Write((Span<char>)new char[] { 'b', 'c', 'd' });
- sw.WriteLine((Span<char>)new char[] { 'e' });
-
- await sw.WriteAsync((ReadOnlyMemory<char>)new char[0]);
- await sw.WriteAsync((ReadOnlyMemory<char>)new char[] { 'f' });
- await sw.WriteAsync((ReadOnlyMemory<char>)new char[] { 'g', 'h', 'i' });
- await sw.WriteLineAsync((ReadOnlyMemory<char>)new char[] { 'j' });
-
- Assert.Equal("abcde" + Environment.NewLine + "fghij" + Environment.NewLine, sw.ToString());
- }
-
- [Fact]
- public async Task Precanceled_ThrowsException()
- {
- var writer = new StringWriter();
-
- await Assert.ThrowsAnyAsync<OperationCanceledException>(() => writer.WriteAsync(Memory<char>.Empty, new CancellationToken(true)));
- await Assert.ThrowsAnyAsync<OperationCanceledException>(() => writer.WriteLineAsync(Memory<char>.Empty, new CancellationToken(true)));
- }
-
- [Fact]
- public void TestWriteStringBuilder()
- {
- StringBuilder sb = getSb();
- StringWriter sw = new StringWriter();
- sw.Write(sb);
- Assert.Equal(sb.ToString(), sw.ToString());
- }
-
- [Fact]
- public async Task TestWriteAsyncStringBuilder()
- {
- StringBuilder sb = getSb();
- StringWriter sw = new StringWriter();
- await sw.WriteAsync(sb);
- Assert.Equal(sb.ToString(), sw.ToString());
- }
-
- [Fact]
- public void TestWriteAsyncStringBuilderCancelled()
- {
- StringBuilder sb = getSb();
- StringWriter sw = new StringWriter();
- CancellationTokenSource cts = new CancellationTokenSource();
- cts.Cancel();
- Assert.Equal(TaskStatus.Canceled, sw.WriteAsync(sb, cts.Token).Status);
- }
-
- [Fact]
- public void TestWriteLineStringBuilder()
- {
- StringBuilder sb = getSb();
- StringWriter sw = new StringWriter();
- sw.WriteLine(sb);
- Assert.Equal(sb.ToString() + Environment.NewLine, sw.ToString());
- }
-
- [Fact]
- public async Task TestWriteLineAsyncStringBuilder()
- {
- StringBuilder sb = getSb();
- StringWriter sw = new StringWriter();
- await sw.WriteLineAsync(sb);
- Assert.Equal(sb.ToString() + Environment.NewLine, sw.ToString());
- }
-
- [Fact]
- public void TestWriteLineAsyncStringBuilderCancelled()
- {
- StringBuilder sb = getSb();
- StringWriter sw = new StringWriter();
- CancellationTokenSource cts = new CancellationTokenSource();
- cts.Cancel();
- Assert.Equal(TaskStatus.Canceled, sw.WriteLineAsync(sb, cts.Token).Status);
- }
-
- [Fact]
- public void DisposeAsync_ClosesWriterAndLeavesBuilderAvailable()
- {
- var sb = new StringBuilder();
- var sw = new StringWriter(sb);
- sw.Write("hello");
- Assert.True(sw.DisposeAsync().IsCompletedSuccessfully);
- Assert.True(sw.DisposeAsync().IsCompletedSuccessfully);
- Assert.Throws<ObjectDisposedException>(() => sw.Write(42));
- Assert.Equal("hello", sb.ToString());
- }
- }
-}
<Configurations>netcoreapp-Debug;netcoreapp-Release</Configurations>
</PropertyGroup>
<ItemGroup>
- <Compile Include="BinaryReader\BinaryReaderTests.netcoreapp.cs" Condition="'$(TargetsNetCoreApp)' == 'true'" />
<Compile Include="IndentedTextWriter.cs" />
<Compile Include="BinaryReader\BinaryReaderTests.cs" />
<Compile Include="MemoryStream\MemoryStream.GetBufferTests.cs" />
<Compile Include="StreamWriter\StreamWriter.cs" />
<Compile Include="StreamWriter\StreamWriter.StringCtorTests.cs" />
<Compile Include="Stream\Stream.APMMethodsTests.cs" />
- <Compile Include="BinaryWriter\BinaryWriter.DisposeAsync.netcoreapp.cs" Condition="'$(TargetsNetCoreApp)' == 'true'" />
+ <Compile Include="BinaryWriter\BinaryWriter.DisposeAsync.cs" />
<Compile Include="BinaryWriter\BinaryWriter.WriteByteCharTests.cs" />
- <Compile Include="BinaryWriter\BinaryWriter.WriteByteCharTests.netcoreapp.cs" Condition="'$(TargetsNetCoreApp)' == 'true'" />
<Compile Include="BinaryWriter\BinaryWriter.WriteTests.cs" />
<Compile Include="BinaryWriter\BinaryWriterTests.cs" />
<Compile Include="BufferedStream\BufferedStream.FlushTests.cs" />
<Compile Include="BufferedStream\BufferedStream.InvalidParameters.cs" />
<Compile Include="BufferedStream\BufferedStreamTests.cs" />
- <Compile Include="BufferedStream\BufferedStreamTests.netcoreapp.cs" Condition="'$(TargetsNetCoreApp)' == 'true'" />
<Compile Include="InvalidDataException\InvalidDataExceptionTests.cs" />
<Compile Include="MemoryStream\MemoryStream.ConstructorTests.cs" />
<Compile Include="MemoryStream\MemoryStream.TryGetBufferTests.cs" />
<Compile Include="MemoryStream\MemoryStreamTests.cs" />
- <Compile Include="MemoryStream\MemoryStreamTests.netcoreapp.cs" Condition="'$(TargetsNetCoreApp)' == 'true'" />
<Compile Include="StreamReader\StreamReader.CtorTests.cs" />
<Compile Include="StreamReader\StreamReaderTests.cs" />
- <Compile Include="StreamReader\StreamReaderTests.netcoreapp.cs" Condition="'$(TargetsNetCoreApp)' == 'true'" />
<Compile Include="StreamWriter\StreamWriter.BaseStream.cs" />
<Compile Include="StreamWriter\StreamWriter.CloseTests.cs" />
<Compile Include="StreamWriter\StreamWriter.CtorTests.cs" />
- <Compile Include="StreamWriter\StreamWriter.DisposeAsync.netcoreapp.cs" Condition="'$(TargetsNetCoreApp)' == 'true'" />
+ <Compile Include="StreamWriter\StreamWriter.DisposeAsync.cs" />
<Compile Include="StreamWriter\StreamWriter.FlushTests.cs" />
<Compile Include="StreamWriter\StreamWriter.WriteTests.cs" />
- <Compile Include="StreamWriter\StreamWriter.WriteTests.netcoreapp.cs" Condition="'$(TargetsNetCoreApp)' == 'true'" />
- <Compile Include="Stream\Stream.DisposeAsync.netcoreapp.cs" Condition="'$(TargetsNetCoreApp)' == 'true'" />
- <Compile Include="Stream\Stream.ReadWriteSpan.netcoreapp.cs" Condition="'$(TargetsNetCoreApp)' == 'true'" />
- <Compile Include="Stream\Stream.NullTests.netcoreapp.cs" Condition="'$(TargetsNetCoreApp)' == 'true'" />
+ <Compile Include="Stream\Stream.DisposeAsync.cs" />
+ <Compile Include="Stream\Stream.ReadWriteSpan.cs" />
<Compile Include="Stream\Stream.NullTests.cs" />
<Compile Include="Stream\Stream.AsyncTests.cs" />
<Compile Include="Stream\Stream.CopyToTests.cs" />
- <Compile Include="Stream\Stream.CopyToTests.netcoreapp.cs" Condition="'$(TargetsNetCoreApp)' == 'true'" />
<Compile Include="Stream\Stream.Methods.cs" />
<Compile Include="Stream\Stream.TestLeaveOpen.cs" />
<Compile Include="Stream\Stream.TimeoutTests.cs" />
- <Compile Include="StringReader\StringReaderTests.netcoreapp.cs" Condition="'$(TargetsNetCoreApp)' == 'true'" />
<Compile Include="StringReader\StringReader.CtorTests.cs" />
- <Compile Include="StringWriter\StringWriterTests.netcoreapp.cs" Condition="'$(TargetsNetCoreApp)' == 'true'" />
<Compile Include="StringWriter\StringWriterTests.cs" />
- <Compile Include="$(CommonTestPath)\System\Buffers\NativeMemoryManager.cs" Condition="'$(TargetsNetCoreApp)' == 'true'">
+ <Compile Include="$(CommonTestPath)\System\Buffers\NativeMemoryManager.cs">
<Link>Common\System\Buffers\NativeMemoryManager.cs</Link>
</Compile>
<Compile Include="$(CommonTestPath)\System\IO\CallTrackingStream.cs">
<Compile Include="TestDataProvider\TestDataProvider.cs" />
<Compile Include="TextReader\CharArrayTextReader.cs" />
<Compile Include="TextReader\TextReaderTests.cs" />
- <Compile Include="TextReader\TextReaderTests.netcoreapp.cs" Condition="'$(TargetsNetCoreApp)' == 'true'" />
<Compile Include="TextWriter\CharArrayTextWriter.cs" />
<Compile Include="TextWriter\TextWriterTests.cs" />
- <Compile Include="TextWriter\TextWriterTests.netcoreapp.cs" Condition="'$(TargetsNetCoreApp)' == 'true'" />
</ItemGroup>
</Project>
\ No newline at end of file
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using System.Collections.Generic;
using System.Threading.Tasks;
using Xunit;
namespace System.IO.Tests
{
- public partial class TextReaderTests
+ public class TextReaderTests
{
protected (char[] chArr, CharArrayTextReader textReader) GetCharArray()
{
Assert.Null(eol);
}
}
+
+ [Fact]
+ public void ReadSpan()
+ {
+ (char[] chArr, CharArrayTextReader textReader) baseInfo = GetCharArray();
+ using (CharArrayTextReader tr = baseInfo.textReader)
+ {
+ char[] chArr = new char[baseInfo.chArr.Length];
+ var chSpan = new Span<char>(chArr, 0, baseInfo.chArr.Length);
+
+ var read = tr.Read(chSpan);
+ Assert.Equal(chArr.Length, read);
+
+ for (int i = 0; i < baseInfo.chArr.Length; i++)
+ {
+ Assert.Equal(baseInfo.chArr[i], chArr[i]);
+ }
+ }
+ }
+
+ [Fact]
+ public void ReadBlockSpan()
+ {
+ (char[] chArr, CharArrayTextReader textReader) baseInfo = GetCharArray();
+ using (CharArrayTextReader tr = baseInfo.textReader)
+ {
+ char[] chArr = new char[baseInfo.chArr.Length];
+ var chSpan = new Span<char>(chArr, 0, baseInfo.chArr.Length);
+
+ var read = tr.ReadBlock(chSpan);
+ Assert.Equal(chArr.Length, read);
+
+ for (int i = 0; i < baseInfo.chArr.Length; i++)
+ {
+ Assert.Equal(baseInfo.chArr[i], chArr[i]);
+ }
+ }
+ }
}
}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Collections.Generic;
-using System.Threading.Tasks;
-using Xunit;
-
-namespace System.IO.Tests
-{
- public partial class TextReaderTests
- {
- [Fact]
- public void ReadSpan()
- {
- (char[] chArr, CharArrayTextReader textReader) baseInfo = GetCharArray();
- using (CharArrayTextReader tr = baseInfo.textReader)
- {
- char[] chArr = new char[baseInfo.chArr.Length];
- var chSpan = new Span<char>(chArr, 0, baseInfo.chArr.Length);
-
- var read = tr.Read(chSpan);
- Assert.Equal(chArr.Length, read);
-
- for (int i = 0; i < baseInfo.chArr.Length; i++)
- {
- Assert.Equal(baseInfo.chArr[i], chArr[i]);
- }
- }
- }
-
- [Fact]
- public void ReadBlockSpan()
- {
- (char[] chArr, CharArrayTextReader textReader) baseInfo = GetCharArray();
- using (CharArrayTextReader tr = baseInfo.textReader)
- {
- char[] chArr = new char[baseInfo.chArr.Length];
- var chSpan = new Span<char>(chArr, 0, baseInfo.chArr.Length);
-
- var read = tr.ReadBlock(chSpan);
- Assert.Equal(chArr.Length, read);
-
- for (int i = 0; i < baseInfo.chArr.Length; i++)
- {
- Assert.Equal(baseInfo.chArr[i], chArr[i]);
- }
- }
- }
- }
-}
using System.Collections.Generic;
using System.Linq;
+using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace System.IO.Tests
{
- public partial class TextWriterTests
+ public class TextWriterTests
{
protected static CharArrayTextWriter NewTextWriter => new CharArrayTextWriter() { NewLine = "---" };
}
#endregion
+
+ [Fact]
+ public void WriteCharSpanTest()
+ {
+ using (CharArrayTextWriter tw = NewTextWriter)
+ {
+ var rs = new ReadOnlySpan<char>(TestDataProvider.CharData, 4, 6);
+ tw.Write(rs);
+ Assert.Equal(new string(rs), tw.Text);
+ }
+ }
+
+ [Fact]
+ public void WriteLineCharSpanTest()
+ {
+ using (CharArrayTextWriter tw = NewTextWriter)
+ {
+ var rs = new ReadOnlySpan<char>(TestDataProvider.CharData, 4, 6);
+ tw.WriteLine(rs);
+ Assert.Equal(new string(rs) + tw.NewLine, tw.Text);
+ }
+ }
+
+ [Fact]
+ public async Task WriteCharMemoryTest()
+ {
+ using (CharArrayTextWriter tw = NewTextWriter)
+ {
+ var rs = new Memory<char>(TestDataProvider.CharData, 4, 6);
+ await tw.WriteAsync(rs);
+ Assert.Equal(new string(rs.Span), tw.Text);
+ }
+ }
+
+ [Fact]
+ public async Task WriteLineCharMemoryTest()
+ {
+ using (CharArrayTextWriter tw = NewTextWriter)
+ {
+ var rs = new Memory<char>(TestDataProvider.CharData, 4, 6);
+ await tw.WriteLineAsync(rs);
+ Assert.Equal(new string(rs.Span) + tw.NewLine, tw.Text);
+ }
+ }
+
+ [Theory]
+ [MemberData(nameof(GetStringBuilderTestData))]
+ public void WriteStringBuilderTest(bool isSynchronized, StringBuilder testData)
+ {
+ using (CharArrayTextWriter ctw = NewTextWriter)
+ {
+ TextWriter tw = isSynchronized ? TextWriter.Synchronized(ctw) : ctw;
+ tw.Write(testData);
+ tw.Flush();
+ Assert.Equal(testData.ToString(), ctw.Text);
+ }
+ }
+
+ [Theory]
+ [MemberData(nameof(GetStringBuilderTestData))]
+ public void WriteLineStringBuilderTest(bool isSynchronized, StringBuilder testData)
+ {
+ using (CharArrayTextWriter ctw = NewTextWriter)
+ {
+ TextWriter tw = isSynchronized ? TextWriter.Synchronized(ctw) : ctw;
+ tw.WriteLine(testData);
+ tw.Flush();
+ Assert.Equal(testData.ToString() + tw.NewLine, ctw.Text);
+ }
+ }
+
+ [Theory]
+ [MemberData(nameof(GetStringBuilderTestData))]
+ public async Task WriteAsyncStringBuilderTest(bool isSynchronized, StringBuilder testData)
+ {
+ using (CharArrayTextWriter ctw = NewTextWriter)
+ {
+ TextWriter tw = isSynchronized ? TextWriter.Synchronized(ctw) : ctw;
+ await tw.WriteAsync(testData);
+ tw.Flush();
+ Assert.Equal(testData.ToString(), ctw.Text);
+ }
+ }
+
+ [Theory]
+ [MemberData(nameof(GetStringBuilderTestData))]
+ public async Task WriteLineAsyncStringBuilderTest(bool isSynchronized, StringBuilder testData)
+ {
+ using (CharArrayTextWriter ctw = NewTextWriter)
+ {
+ TextWriter tw = isSynchronized ? TextWriter.Synchronized(ctw) : ctw;
+ await tw.WriteLineAsync(testData);
+ tw.Flush();
+ Assert.Equal(testData + tw.NewLine, ctw.Text);
+ }
+ }
+
+ [Fact]
+ public void DisposeAsync_InvokesDisposeSynchronously()
+ {
+ bool disposeInvoked = false;
+ var tw = new InvokeActionOnDisposeTextWriter() { DisposeAction = () => disposeInvoked = true };
+ Assert.False(disposeInvoked);
+ Assert.True(tw.DisposeAsync().IsCompletedSuccessfully);
+ Assert.True(disposeInvoked);
+ }
+
+ [Fact]
+ public void DisposeAsync_ExceptionReturnedInTask()
+ {
+ Exception e = new FormatException();
+ var tw = new InvokeActionOnDisposeTextWriter() { DisposeAction = () => { throw e; } };
+ ValueTask vt = tw.DisposeAsync();
+ Assert.True(vt.IsFaulted);
+ Assert.Same(e, vt.AsTask().Exception.InnerException);
+ }
+
+ private sealed class InvokeActionOnDisposeTextWriter : TextWriter
+ {
+ public Action DisposeAction;
+ public override Encoding Encoding => Encoding.UTF8;
+ protected override void Dispose(bool disposing) => DisposeAction?.Invoke();
+ }
+
+ // Generate data for TextWriter.Write* methods that take a stringBuilder.
+ // We test both the synchronized and unsynchronized variation, on strinbuilder swith 0, small and large values.
+ public static IEnumerable<object[]> GetStringBuilderTestData()
+ {
+ // Make a string that has 10 or so 8K chunks (probably).
+ StringBuilder complexStringBuilder = new StringBuilder();
+ for (int i = 0; i < 4000; i++)
+ complexStringBuilder.Append(TestDataProvider.CharData); // CharData ~ 25 chars
+
+ foreach (StringBuilder testData in new StringBuilder[] { new StringBuilder(""), new StringBuilder(new string(TestDataProvider.CharData)), complexStringBuilder })
+ {
+ foreach (bool isSynchronized in new bool[] { true, false })
+ {
+ yield return new object[] { isSynchronized, testData };
+ }
+ }
+ }
}
}
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Collections.Generic;
-using System.Text;
-using System.Threading;
-using System.Threading.Tasks;
-using Xunit;
-
-namespace System.IO.Tests
-{
- public partial class TextWriterTests
- {
- [Fact]
- public void WriteCharSpanTest()
- {
- using (CharArrayTextWriter tw = NewTextWriter)
- {
- var rs = new ReadOnlySpan<char>(TestDataProvider.CharData, 4, 6);
- tw.Write(rs);
- Assert.Equal(new string(rs), tw.Text);
- }
- }
-
- [Fact]
- public void WriteLineCharSpanTest()
- {
- using (CharArrayTextWriter tw = NewTextWriter)
- {
- var rs = new ReadOnlySpan<char>(TestDataProvider.CharData, 4, 6);
- tw.WriteLine(rs);
- Assert.Equal(new string(rs) + tw.NewLine, tw.Text);
- }
- }
-
- [Fact]
- public async Task WriteCharMemoryTest()
- {
- using (CharArrayTextWriter tw = NewTextWriter)
- {
- var rs = new Memory<char>(TestDataProvider.CharData, 4, 6);
- await tw.WriteAsync(rs);
- Assert.Equal(new string(rs.Span), tw.Text);
- }
- }
-
- [Fact]
- public async Task WriteLineCharMemoryTest()
- {
- using (CharArrayTextWriter tw = NewTextWriter)
- {
- var rs = new Memory<char>(TestDataProvider.CharData, 4, 6);
- await tw.WriteLineAsync(rs);
- Assert.Equal(new string(rs.Span) + tw.NewLine, tw.Text);
- }
- }
-
- [Theory]
- [MemberData(nameof(GetStringBuilderTestData))]
- public void WriteStringBuilderTest(bool isSynchronized, StringBuilder testData)
- {
- using (CharArrayTextWriter ctw = NewTextWriter)
- {
- TextWriter tw = isSynchronized ? TextWriter.Synchronized(ctw) : ctw;
- tw.Write(testData);
- tw.Flush();
- Assert.Equal(testData.ToString(), ctw.Text);
- }
- }
-
- [Theory]
- [MemberData(nameof(GetStringBuilderTestData))]
- public void WriteLineStringBuilderTest(bool isSynchronized, StringBuilder testData)
- {
- using (CharArrayTextWriter ctw = NewTextWriter)
- {
- TextWriter tw = isSynchronized ? TextWriter.Synchronized(ctw) : ctw;
- tw.WriteLine(testData);
- tw.Flush();
- Assert.Equal(testData.ToString() + tw.NewLine, ctw.Text);
- }
- }
-
- [Theory]
- [MemberData(nameof(GetStringBuilderTestData))]
- public async Task WriteAsyncStringBuilderTest(bool isSynchronized, StringBuilder testData)
- {
- using (CharArrayTextWriter ctw = NewTextWriter)
- {
- TextWriter tw = isSynchronized ? TextWriter.Synchronized(ctw) : ctw;
- await tw.WriteAsync(testData);
- tw.Flush();
- Assert.Equal(testData.ToString(), ctw.Text);
- }
- }
-
- [Theory]
- [MemberData(nameof(GetStringBuilderTestData))]
- public async Task WriteLineAsyncStringBuilderTest(bool isSynchronized, StringBuilder testData)
- {
- using (CharArrayTextWriter ctw = NewTextWriter)
- {
- TextWriter tw = isSynchronized ? TextWriter.Synchronized(ctw) : ctw;
- await tw.WriteLineAsync(testData);
- tw.Flush();
- Assert.Equal(testData + tw.NewLine, ctw.Text);
- }
- }
-
- [Fact]
- public void DisposeAsync_InvokesDisposeSynchronously()
- {
- bool disposeInvoked = false;
- var tw = new InvokeActionOnDisposeTextWriter() { DisposeAction = () => disposeInvoked = true };
- Assert.False(disposeInvoked);
- Assert.True(tw.DisposeAsync().IsCompletedSuccessfully);
- Assert.True(disposeInvoked);
- }
-
- [Fact]
- public void DisposeAsync_ExceptionReturnedInTask()
- {
- Exception e = new FormatException();
- var tw = new InvokeActionOnDisposeTextWriter() { DisposeAction = () => { throw e; } };
- ValueTask vt = tw.DisposeAsync();
- Assert.True(vt.IsFaulted);
- Assert.Same(e, vt.AsTask().Exception.InnerException);
- }
-
- private sealed class InvokeActionOnDisposeTextWriter : TextWriter
- {
- public Action DisposeAction;
- public override Encoding Encoding => Encoding.UTF8;
- protected override void Dispose(bool disposing) => DisposeAction?.Invoke();
- }
-
- // Generate data for TextWriter.Write* methods that take a stringBuilder.
- // We test both the synchronized and unsynchronized variation, on strinbuilder swith 0, small and large values.
- public static IEnumerable<object[]> GetStringBuilderTestData()
- {
- // Make a string that has 10 or so 8K chunks (probably).
- StringBuilder complexStringBuilder = new StringBuilder();
- for (int i = 0; i < 4000; i++)
- complexStringBuilder.Append(TestDataProvider.CharData); // CharData ~ 25 chars
-
- foreach (StringBuilder testData in new StringBuilder[] { new StringBuilder(""), new StringBuilder(new string(TestDataProvider.CharData)), complexStringBuilder })
- {
- foreach (bool isSynchronized in new bool[] { true, false })
- {
- yield return new object[] { isSynchronized, testData };
- }
- }
- }
- }
-}