This commit is contained in:
josesimoes 2022-02-15 18:09:13 +00:00
Родитель b7ba5a6658
Коммит 343117fd3e
46 изменённых файлов: 4914 добавлений и 1 удалений

32
.github/workflows/update-dependencies.yml поставляемый Normal file
Просмотреть файл

@ -0,0 +1,32 @@
# Copyright (c) .NET Foundation and Contributors
# See LICENSE file in the project root for full license information.
# This workflow will periodically check .NET nanoFramework dependencies and updates them in the repository it's running.
name: Daily update dependencies
on:
schedule:
# At 00:00 UTC every day.
- cron: '00 00 * * *'
repository_dispatch:
types: update-dependencies
defaults:
run:
shell: pwsh
jobs:
update-dotnet-preview:
name: Update .NET nanoFramework dependencies
timeout-minutes: 15
runs-on: windows-latest
env:
GITHUB_TOKEN: ${{ github.token }}
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Update dependencies
uses: nanoframework/nanodu@v1
with:
solutionsToCheck: 'nanoFramework.System.IO.Streams.sln'

Просмотреть файл

@ -0,0 +1,13 @@
user=nanoframework
project=System.IO.Ports
issues=true
add_issues_wo_labels=false
add_pr_wo_labels=false
add_issues_wo_labels=false
filter_issues_by_milestone=false
exclude_labels=Area: Config-and-Build,Area: Infrastructure-and-Organization,reverted
enhancement_labels=Type: enhancement
bug_labels=Type: bug
merge_prefix=**Documentation and other chores:**
unreleased_label=**Changes available only in 'Preview' NuGet packages:**
author=false

255
.gitignore поставляемый Normal file
Просмотреть файл

@ -0,0 +1,255 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# DNX
project.lock.json
artifacts/
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# TODO: Comment the next line if you want to checkin your web deploy settings
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# NuGet v3's project.json files produces more ignoreable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.pfx
*.publishsettings
node_modules/
orleans.codegen.cs
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
*.mdf
*.ldf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
#SoundCloud
*.sonarqube/

3
CODE_OF_CONDUCT.md Normal file
Просмотреть файл

@ -0,0 +1,3 @@
# Contributor Code of Conduct
Please refer to the contributor Code of Conduct at the Home repository [here](https://github.com/nanoframework/Home/blob/main/CODE_OF_CONDUCT.md.

21
LICENSE.md Normal file
Просмотреть файл

@ -0,0 +1,21 @@
MIT License
Copyright (c) .NET Foundation and Contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

7
NuGet.Config Normal file
Просмотреть файл

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<add key="NuGet" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
<add key="Azure Artifacts nanoFramework dev" value="https://pkgs.dev.azure.com/nanoframework/feed/_packaging/sandbox/nuget/v3/index.json" protocolVersion="3" />
</packageSources>
</configuration>

Просмотреть файл

@ -1 +1,66 @@
# System.IO.Streams
# System.IO.Streams[![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=nanoframework_System.IO.Streams&metric=alert_status)](https://sonarcloud.io/dashboard?id=nanoframework_System.IO.Streams) [![Reliability Rating](https://sonarcloud.io/api/project_badges/measure?project=nanoframework_System.IO.Streams&metric=reliability_rating)](https://sonarcloud.io/dashboard?id=nanoframework_System.IO.Streams) [![License](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE) [![NuGet](https://img.shields.io/nuget/dt/nanoFramework.System.IO.Streams.svg?label=NuGet&style=flat&logo=nuget)](https://www.nuget.org/packages/nanoFramework.System.IO.Streams/) [![#yourfirstpr](https://img.shields.io/badge/first--timers--only-friendly-blue.svg)](https://github.com/nanoframework/Home/blob/main/CONTRIBUTING.md) [![Discord](https://img.shields.io/discord/478725473862549535.svg?logo=discord&logoColor=white&label=Discord&color=7289DA)](https://discord.gg/gCyBu8T)
![nanoFramework logo](https://raw.githubusercontent.com/nanoframework/Home/main/resources/logo/nanoFramework-repo-logo.png)
-----
# Welcome to the .NET **nanoFramework** System.IO.Streams Library repository
## Build status
| Component | Build Status | NuGet Package |
|:-|---|---|
| System.IO.Streams | [![Build Status](https://dev.azure.com/nanoframework/System.IO.Streams/_apis/build/status/nanoframework.System.IO.Streams?repoName=nanoframework%2FSystem.IO.Streams&branchName=main)](https://dev.azure.com/nanoframework/System.IO.Streams/_build/latest?definitionId=74&repoName=nanoframework%2FSystem.IO.Streams&branchName=main) | [![NuGet](https://img.shields.io/nuget/v/nanoFramework.System.IO.Streams.svg?label=NuGet&style=flat&logo=nuget)](https://www.nuget.org/packages/nanoFramework.System.IO.Streams/) |
| System.IO.Streams (preview) | [![Build Status](https://dev.azure.com/nanoframework/System.IO.Streams/_apis/build/status/nanoframework.System.IO.Streams?repoName=nanoframework%2FSystem.IO.Streams&branchName=develop)](https://dev.azure.com/nanoframework/System.IO.Streams/_build/latest?definitionId=74&repoName=nanoframework%2FSystem.IO.Streams&branchName=develop) | [![NuGet](https://img.shields.io/nuget/vpre/nanoFramework.System.IO.Streams.svg?label=NuGet&style=flat&logo=nuget)](https://www.nuget.org/packages/nanoFramework.System.IO.Streams/) |
## Usage examples
### Using a MemoryStream
Write data using memory as a backing store.
```csharp
using MemoryStream memStream = new MemoryStream(100);
string test = "nanoFramework Test";
memStream.Write(Encoding.UTF8.GetBytes(test), 0, test.Length);
memStream.Flush();
```
Reset stream position.
```csharp
memStream.Seek(0, SeekOrigin.Begin);
```
Read from from stream.
```csharp
byte[] readbuff = new byte[20];
memStream.Read(readbuff, 0, readbuff.Length);
string testResult = new string(Encoding.UTF8.GetChars(readbuff));
```
## Feedback and documentation
For documentation, providing feedback, issues and finding out how to contribute please refer to the [Home repo](https://github.com/nanoframework/Home).
Join our Discord community [here](https://discord.gg/gCyBu8T).
## Credits
The list of contributors to this project can be found at [CONTRIBUTORS](https://github.com/nanoframework/Home/blob/main/CONTRIBUTORS.md).
## License
The **nanoFramework** Class Libraries are licensed under the [MIT license](LICENSE.md).
## Code of Conduct
This project has adopted the code of conduct defined by the Contributor Covenant to clarify expected behaviour in our community.
For more information see the [.NET Foundation Code of Conduct](https://dotnetfoundation.org/code-of-conduct).
### .NET Foundation
This project is supported by the [.NET Foundation](https://dotnetfoundation.org).

Просмотреть файл

@ -0,0 +1,462 @@
//
// Copyright (c) .NET Foundation and Contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
namespace System.IO
{
/// <summary>
/// Creates a stream whose backing store is memory.
/// </summary>
public class MemoryStream : Stream
{
// Either allocated internally or externally.
private byte[] _buffer;
// For user-provided arrays, start at this origin
private int _origin;
// read/write head.
private int _position;
// Number of bytes within the memory stream
private int _length;
// length of usable portion of buffer for stream
private int _capacity;
// User-provided buffers aren't expandable.
private bool _expandable;
// Is this stream open or closed?
private bool _isOpen;
private const int MemStreamMaxLength = 0xFFFF;
/// <summary>
/// Initializes a new instance of the <see cref="MemoryStream"/> class with an expandable capacity initialized to zero.
/// </summary>
/// <remarks>
/// <para>
/// The <see cref="CanRead"/>, <see cref="CanSeek"/>, and <see cref="CanWrite"/> properties are all set to <see langword="true"/>.
/// </para>
/// <para>
/// The capacity of the current stream automatically increases when you use the <see cref="SetLength"/> method to set the length to a value larger than the capacity of the current stream.
/// </para>
/// </remarks>
public MemoryStream()
{
_buffer = new byte[256];
_capacity = 256;
_expandable = true;
// Must be 0 for byte[]'s created by MemoryStream
_origin = 0;
_isOpen = true;
}
/// <summary>
/// Initializes a new non-resizable instance of the <see cref="MemoryStream"/> class based on the specified byte array.
/// </summary>
/// <param name="buffer">The array of unsigned bytes from which to create the current stream.</param>
/// <exception cref="ArgumentNullException"><paramref name="buffer"/> is <see langword="null"/>./exception>
/// <remarks>
/// <para>
/// The <see cref="CanRead"/>, <see cref="CanSeek"/>, and <see cref="CanWrite"/> properties are all set to <see langword="true"/>.
/// </para>
/// <para>
/// The capacity of the current stream automatically increases when you use the <see cref="SetLength"/> method to set the length to a value larger than the capacity of the current stream.
/// </para>
/// </remarks>
public MemoryStream(byte[] buffer)
{
_buffer = buffer ?? throw new ArgumentNullException();
_length = _capacity = buffer.Length;
_expandable = false;
_origin = 0;
_isOpen = true;
}
/// <summary>
/// Gets a value indicating whether the current stream supports reading.
/// </summary>
/// <value>/// <see langword="true"/> if the stream is open./// </value>
/// <remarks>
/// <para>
/// If a class derived from <see cref="Stream"/> does not support reading, calls to the <see cref="Read"/> and <see cref="ReadByte"/> methods throw a <see cref="NotSupportedException"/>.
/// </para>
/// <para>
/// If the stream is closed, this property returns <see langword="false"/>.
/// </para>
/// </remarks>
public override bool CanRead => _isOpen;
/// <summary>
/// Gets a value indicating whether the current stream supports seeking.
/// </summary>
/// <value><see langword="true"/> if the stream is open.</value>
/// <remarks>
/// <para>
/// If a class derived from <see cref="Stream"/> does not support reading, calls to the <see cref="Length"/>, <see cref="SetLength"/>, <see cref="Position"/> and <see cref="Seek"/> throw a <see cref="NotSupportedException"/>.
/// </para>
/// <para>
/// If the stream is closed, this property returns <see langword="false"/>.
/// </para>
/// </remarks>
public override bool CanSeek => _isOpen;
/// <summary>
/// Gets a value indicating whether the current stream supports writing.
/// </summary>
/// <value><see langword="true"/> if the stream supports writing; otherwise, <see langword="false"/>.</value>
/// <remarks>
/// <para>
/// If a class derived from <see cref="Stream"/> does not support reading, calls to the <see cref="SetLength(long)"/> and <see cref="Write"/> or <see cref="WriteByte"/> methods throw a <see cref="NotSupportedException"/>.
/// </para>
/// <para>
/// If the stream is closed, this property returns <see langword="false"/>.
/// </para>
/// </remarks>
public override bool CanWrite => _isOpen;
/// <inheritdoc/>
protected override void Dispose(bool disposing)
{
if (disposing)
{
_isOpen = false;
}
}
// returns a bool saying whether we allocated a new array.
private bool EnsureCapacity(int value)
{
if (value > _capacity)
{
int newCapacity = value;
if (newCapacity < 256)
{
newCapacity = 256;
}
if (newCapacity < _capacity * 2)
{
newCapacity = _capacity * 2;
}
if (!_expandable && newCapacity > _capacity)
{
throw new NotSupportedException();
}
if (newCapacity > 0)
{
byte[] newBuffer = new byte[newCapacity];
if (_length > 0)
{
Array.Copy(_buffer, 0, newBuffer, 0, _length);
}
_buffer = newBuffer;
}
else
{
_buffer = null;
}
_capacity = newCapacity;
return true;
}
return false;
}
/// <inheritdoc/>
public override void Flush()
{
}
/// <inheritdoc/>
public override long Length
{
get
{
if (!_isOpen)
{
throw new ObjectDisposedException();
}
return _length - _origin;
}
}
/// <inheritdoc/>
public override long Position
{
get
{
if (!_isOpen)
{
throw new ObjectDisposedException();
}
return _position - _origin;
}
set
{
if (!_isOpen)
{
throw new ObjectDisposedException();
}
if (value < 0 || value > MemStreamMaxLength)
{
throw new ArgumentOutOfRangeException();
}
_position = _origin + (int)value;
}
}
/// <inheritdoc/>
/// <exception cref="ObjectDisposedException">The current stream instance is closed.</exception>
/// <exception cref="ArgumentNullException"><paramref name="buffer"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="offset"/> or <paramref name="count"/> is negative.</exception>
/// <exception cref="ArgumentException"><paramref name="offset"/> subtracted from the buffer length is less than <paramref name="count"/>.</exception>
public override int Read(
byte[] buffer,
int offset,
int count)
{
if (!_isOpen)
{
throw new ObjectDisposedException();
}
if (buffer == null)
{
throw new ArgumentNullException();
}
if (offset < 0 || count < 0)
{
throw new ArgumentOutOfRangeException();
}
if (buffer.Length - offset < count)
{
throw new ArgumentException();
}
int n = _length - _position;
if (n > count)
{
n = count;
}
if (n <= 0)
{
return 0;
}
Array.Copy(_buffer, _position, buffer, offset, n);
_position += n;
return n;
}
/// <inheritdoc/>
/// <exception cref="ObjectDisposedException">The current stream instance is closed.</exception>
public override int ReadByte()
{
if (!_isOpen)
{
throw new ObjectDisposedException();
}
if (_position >= _length)
{
return -1;
}
return _buffer[_position++];
}
/// <inheritdoc/>
/// <exception cref="ObjectDisposedException"></exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="offset"/> is greater than <see cref="int.MaxValue"/>.</exception>
/// <exception cref="IOException">Seeking is attempted before the beginning of the stream.</exception>
/// <exception cref="ArgumentException">
/// There is an invalid <see cref="SeekOrigin"/>.
/// -or-
/// <paramref name="offset"/> caused an arithmetic overflow.
/// </exception>
public override long Seek(
long offset,
SeekOrigin origin)
{
if (!_isOpen)
{
throw new ObjectDisposedException();
}
if (offset > MemStreamMaxLength)
{
throw new ArgumentOutOfRangeException();
}
switch (origin)
{
case SeekOrigin.Begin:
if (offset < 0)
{
throw new IOException();
}
_position = _origin + (int)offset;
break;
case SeekOrigin.Current:
if (offset + _position < _origin)
{
throw new IOException();
}
_position += (int)offset;
break;
case SeekOrigin.End:
if (_length + offset < _origin)
{
throw new IOException();
}
_position = _length + (int)offset;
break;
default:
throw new ArgumentException();
}
return _position;
}
/// <inheritdoc/>
public override void SetLength(long value)
{
if (!_isOpen)
{
throw new ObjectDisposedException();
}
if (value > MemStreamMaxLength || value < 0)
{
throw new ArgumentOutOfRangeException();
}
int newLength = _origin + (int)value;
bool allocatedNewArray = EnsureCapacity(newLength);
if (!allocatedNewArray && newLength > _length)
{
Array.Clear(_buffer, _length, newLength - _length);
}
_length = newLength;
if (_position > newLength)
{
_position = newLength;
}
}
/// <inheritdoc/>
public virtual byte[] ToArray()
{
byte[] copy = new byte[_length - _origin];
Array.Copy(_buffer, _origin, copy, 0, _length - _origin);
return copy;
}
/// <inheritdoc/>
public override void Write(byte[] buffer, int offset, int count)
{
if (!_isOpen)
{
throw new ObjectDisposedException();
}
if (buffer == null)
{
throw new ArgumentNullException();
}
if (offset < 0 || count < 0)
{
throw new ArgumentOutOfRangeException();
}
if (buffer.Length - offset < count)
{
throw new ArgumentException();
}
int i = _position + count;
// check for overflow
if (i > _length)
{
if (i > _capacity)
{
EnsureCapacity(i);
}
_length = i;
}
Array.Copy(buffer, offset, _buffer, _position, count);
_position = i;
}
/// <inheritdoc/>
public override void WriteByte(byte value)
{
if (!_isOpen)
{
throw new ObjectDisposedException();
}
if (_position >= _capacity)
{
EnsureCapacity(_position + 1);
}
_buffer[_position++] = value;
if (_position > _length)
{
_length = _position;
}
}
/// <inheritdoc/>
public virtual void WriteTo(Stream stream)
{
if (!_isOpen)
{
throw new ObjectDisposedException();
}
if (stream == null)
{
throw new ArgumentNullException();
}
stream.Write(_buffer, _origin, _length - _origin);
}
}
}

Просмотреть файл

@ -0,0 +1,22 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("nanoFramework.System.IO.Streams")]
[assembly: AssemblyCompany("nanoFramework Contributors")]
[assembly: AssemblyProduct("nanoFramework.System.IO.Streams")]
[assembly: AssemblyCopyright("Copyright (c) .NET Foundation and Contributors")]
////////////////////////////////////////////////////////////////
// update this whenever the native assembly signature changes //
[assembly: AssemblyNativeVersion("100.0.0.1")]
////////////////////////////////////////////////////////////////
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

Просмотреть файл

@ -0,0 +1,547 @@
//
// Copyright (c) .NET Foundation and Contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
using System.Collections;
using System.Text;
namespace System.IO
{
/// <summary>
/// Implements a <see cref="TextReader"/> that reads characters from a byte stream in a particular encoding.
/// </summary>
public class StreamReader : TextReader
{
private const int c_MaxReadLineLen = 0xFFFF;
private const int c_BufferSize = 512;
private Stream _stream;
// Initialized in constructor by CurrentEncoding scheme.
// Encoding can be changed by resetting this variable.
readonly Decoder _decoder;
// temporary buffer used for decoder in Read() function.
// Made it class member to save creation of buffer on each call to Read()
// Initialized in StreamReader(String path)
readonly char[] _singleCharBuff;
private bool _disposed;
// internal stream read buffer
private byte[] _buffer;
private int _curBufPos;
private int _curBufLen;
/// <summary>
/// Returns the underlying stream.
/// </summary>
/// <value>The underlying stream.</value>
/// <remarks>
/// You use this property to access the underlying stream. The StreamReader class buffers input from the underlying stream when you call one of the Read methods. If you manipulate the position of the underlying stream after reading data into the buffer, the position of the underlying stream might not match the position of the internal buffer. To reset the internal buffer, call the DiscardBufferedData method; however, this method slows performance and should be called only when absolutely necessary. The StreamReader constructors that have the detectEncodingFromByteOrderMarks parameter can change the encoding the first time you read from the StreamReader object.
/// </remarks>
public virtual Stream BaseStream => _stream;
/// <summary>
/// Gets the current character encoding that the current <see cref="StreamReader"/> object is using.
/// </summary>
/// <value>The current character encoding used by the current reader. The value can be different after the first call to any <see cref="Read"/> method of <see cref="StreamReader"/>, since encoding autodetection is not done until the first call to a <see cref="Read"/> method.</value>
public virtual Encoding CurrentEncoding => System.Text.Encoding.UTF8;
public bool EndOfStream
{
get
{
return _curBufLen == _curBufPos;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="StreamReader"/> class for the specified stream.
/// </summary>
/// <param name="stream">The stream to be read.</param>
/// <exception cref="ArgumentNullException"><paramref name="stream"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentException"><paramref name="stream"/> does not support reading.</exception>
public StreamReader(Stream stream)
{
if (stream == null)
{
throw new ArgumentNullException();
}
if (!stream.CanRead)
{
throw new ArgumentException();
}
_singleCharBuff = new char[1];
_buffer = new byte[c_BufferSize];
_curBufPos = 0;
_curBufLen = 0;
_stream = stream;
_decoder = CurrentEncoding.GetDecoder();
_disposed = false;
}
/// <summary>
/// Closes the <see cref="StreamReader"/> object and the underlying stream, and releases any system resources associated with the reader.
/// </summary>
/// <remarks>
/// This method overrides the <see cref="TextReader.Close"/> method.
/// This implementation of <see cref="Close"/> calls the <see cref="Dispose"/> method, passing a <see langword="true"/> value.
/// Following a call to <see cref="Close"/>, any operations on the reader might raise exceptions.
/// </remarks>
public override void Close()
{
Dispose();
}
/// <summary>
/// Closes the underlying stream, releases the unmanaged resources used by the <see cref="StreamReader"/>, and optionally releases the managed resources.
/// </summary>
/// <param name="disposing"><see langword="true"/> to release both managed and unmanaged resources; <see langword="false"/> to release only unmanaged resources.</param>
/// <remarks>
/// This method is called by the public <see cref="Dispose"/> method and the Finalize method. Dispose invokes the protected <see cref="Dispose"/> method with the disposing parameter set to <see langword="true"/>. Finalize invokes <see cref="Dispose"/> with disposing set to <see langword="false"/>.
/// When the disposing parameter is <see langword="true"/>, this method releases all resources held by any managed objects that the StreamReader object references.This method invokes the <see cref="Dispose"/> method of each referenced object.
/// </remarks>
protected override void Dispose(bool disposing)
{
if (_stream != null)
{
if (disposing)
{
_stream.Close();
}
_stream = null;
_buffer = null;
_curBufPos = 0;
_curBufLen = 0;
}
_disposed = true;
}
/// <summary>
/// Returns the next available character but does not consume it.
/// </summary>
/// <returns>An integer representing the next character to be read, or -1 if there are no characters to be read or if the stream does not support seeking.</returns>
/// <exception cref="IOException">An I/O error occurs.</exception>
/// <remarks>
/// The <see cref="Peek"/> method returns an integer value in order to determine whether the end of the file, or another error has occurred. This allows a user to first check if the returned value is -1 before casting it to a <see cref="char"/> type.
/// This method overrides <see cref="TextReader.Peek"/>.
/// The current position of the <see cref="StreamReader"/> object is not changed by <see cref="Peek"/>.
/// </remarks>
public override int Peek()
{
int tempPos = _curBufPos;
int nextChar;
// If buffer needs refresh take into account max UTF8 bytes if the next character is UTF8 encoded
// Note: In some occasions, _curBufPos may go beyond _curBufLen-1 (for example, when trying to peek after reading the last character of the buffer), so we need to refresh the buffer in these cases too
if ((_curBufPos >= (_curBufLen - 1)) ||
((_buffer[_curBufPos + 1] & 0x80) != 0
&& (_curBufPos + 3 >= _curBufLen)))
{
// move any bytes read for this character to front of new buffer
int totRead;
for (totRead = 0; totRead < _curBufLen - _curBufPos; ++totRead)
{
_buffer[totRead] = _buffer[_curBufPos + totRead];
}
// get the new buffer
try
{
// retry read until response timeout expires
while (_stream.Length > 0 && totRead < _buffer.Length)
{
int len = (int)(_buffer.Length - totRead);
if (len > _stream.Length)
{
len = (int)_stream.Length;
}
len = _stream.Read(_buffer, totRead, len);
if (len <= 0)
{
break;
}
totRead += len;
}
}
catch (Exception e)
{
throw new IOException("Stream.Read", e);
}
tempPos = 0;
_curBufPos = 0;
_curBufLen = totRead;
}
// get the next character and reset _curBufPos
nextChar = Read();
_curBufPos = tempPos;
return nextChar;
}
/// <summary>
/// Reads the next character from the input stream and advances the character position by one character.
/// </summary>
/// <returns>The next character from the input stream represented as an <see cref="int"/> object, or -1 if no more characters are available.</returns>
/// <remarks>
/// This method overrides <see cref="TextReader.Read"/>.
/// This method returns an integer so that it can return -1 if the end of the stream has been reached. If you manipulate the position of the underlying stream after reading data into the buffer, the position of the underlying stream might not match the position of the internal buffer.To reset the internal buffer, call the DiscardBufferedData method; however, this method slows performance and should be called only when absolutely necessary.
/// </remarks>
public override int Read()
{
int byteUsed, charUsed;
bool completed = false;
while (true)
{
_decoder.Convert(
_buffer,
_curBufPos,
_curBufLen - _curBufPos,
_singleCharBuff,
0,
1,
false,
out byteUsed,
out charUsed,
out _);
_curBufPos += byteUsed;
if (charUsed == 1)
{
// done here
break;
}
else
{
// get more data to feed the decider and try again.
// try to fill the m_buffer.
// FillBufferAndReset purges processed data in front of buffer. Thus we can use up to full _buffer.Length
int readCount = _buffer.Length;
// Put it to the maximum of available data and readCount
readCount = readCount > (int)_stream.Length ? (int)_stream.Length : readCount;
if (readCount == 0)
{
readCount = 1;
}
// If there is no data, then return -1
if (FillBufferAndReset(readCount) == 0)
{
return -1;
}
}
}
return _singleCharBuff[0];
}
/// <summary>
/// Reads a specified maximum of characters from the current stream into a buffer, beginning at the specified index.
/// </summary>
/// <param name="buffer">When this method returns, contains the specified character array with the values between <paramref name="index"/> and (<paramref name="index"/> + <paramref name="count"/> - 1) replaced by the characters read from the current source.</param>
/// <param name="index">The index of <paramref name="buffer"/> at which to begin writing.</param>
/// <param name="count">The maximum number of characters to read.</param>
/// <returns>
/// The number of characters that have been read, or 0 if at the end of the stream and no data was read. The number will be less than or equal to the <paramref name="count"/> parameter, depending on whether the data is available within the stream.
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="buffer"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> or <paramref name="count"/> is negative.</exception>
/// <exception cref="ArgumentException">The buffer length minus <paramref name="index"/> is less than <paramref name="count"/>.</exception>
/// <exception cref="ObjectDisposedException">An I/O error occurs, such as the stream is closed.</exception>
/// <remarks>
/// This method overrides TextReader.Read.
/// This method returns an integer so that it can return 0 if the end of the stream has been reached.
/// When using the Read method, it is more efficient to use a buffer that is the same size as the internal buffer of the stream, where the internal buffer is set to your desired block size, and to always read less than the block size.If the size of the internal buffer was unspecified when the stream was constructed, its default size is 4 kilobytes(4096 bytes). If you manipulate the position of the underlying stream after reading data into the buffer, the position of the underlying stream might not match the position of the internal buffer.To reset the internal buffer, call the DiscardBufferedData method; however, this method slows performance and should be called only when absolutely necessary.
/// This method returns after either the number of characters specified by the count parameter are read, or the end of the file is reached. <see cref="ReadBlock"/> is a blocking version of <see cref="Read"/>.
/// </remarks>
public override int Read(
char[] buffer,
int index,
int count)
{
if (buffer == null)
{
throw new ArgumentNullException();
}
if (index < 0)
{
throw new ArgumentOutOfRangeException();
}
if (count < 0)
{
throw new ArgumentOutOfRangeException();
}
if (buffer.Length - index < count)
{
throw new ArgumentException();
}
if (_disposed)
{
throw new ObjectDisposedException();
}
int byteUsed, charUsed = 0;
if (_curBufLen == 0)
{
_ = FillBufferAndReset(count);
}
int offset = 0;
while (true)
{
_decoder.Convert(
_buffer,
_curBufPos,
_curBufLen - _curBufPos,
buffer,
offset,
count,
false,
out byteUsed,
out charUsed,
out _);
count -= charUsed;
_curBufPos += byteUsed;
offset += charUsed;
if (count == 0 || (FillBufferAndReset(count) == 0))
{
break;
}
}
return charUsed;
}
/// <summary>
/// Reads a line of characters from the current stream and returns the data as a string.
/// </summary>
/// <returns>The next line from the input stream, or <see langword="null"/> if the end of the input stream is reached.</returns>
/// <exception cref="Exception"></exception>
public override string ReadLine()
{
int bufLen = c_BufferSize;
char[] readLineBuff = new char[bufLen];
int growSize = c_BufferSize;
int curPos = 0;
int newChar;
// Look for \r\n
while ((newChar = Read()) != -1)
{
// Grow the line buffer if needed
if (curPos == bufLen)
{
if (bufLen + growSize > c_MaxReadLineLen)
{
throw new Exception();
}
char[] tempBuf = new char[bufLen + growSize];
Array.Copy(readLineBuff, 0, tempBuf, 0, bufLen);
readLineBuff = tempBuf;
bufLen += growSize;
}
// store the new character
readLineBuff[curPos] = (char)newChar;
if (readLineBuff[curPos] == '\n')
{
return new string(readLineBuff, 0, curPos);
}
// check for \r and \r\n
if (readLineBuff[curPos] == '\r')
{
// If the next character is \n eat it
if (Peek() == '\n')
{
_ = Read();
}
return new string(readLineBuff, 0, curPos);
}
// move to the next byte
++curPos;
}
// reached end of stream. Send line up
if (curPos == 0)
{
return null;
}
return new string(readLineBuff, 0, curPos);
}
/// <summary>
/// Reads all characters from the current position to the end of the stream.
/// </summary>
/// <returns>The rest of the stream as a string, from the current position to the end. If the current position is at the end of the stream, returns an empty string ("").</returns>
/// <remarks>
/// This method overrides TextReader.ReadToEnd.
/// ReadToEnd works best when you need to read all the input from the current position to the end of the stream.If more control is needed over how many characters are read from the stream, use the Read(Char[], Int32, Int32) method overload, which generally results in better performance.
/// ReadToEnd assumes that the stream knows when it has reached an end.For interactive protocols in which the server sends data only when you ask for it and does not close the connection, ReadToEnd might block indefinitely because it does not reach an end, and should be avoided.
/// Note that when using the Read method, it is more efficient to use a buffer that is the same size as the internal buffer of the stream.If the size of the buffer was unspecified when the stream was constructed, its default size is 4 kilobytes (4096 bytes).
/// If the current method throws an OutOfMemoryException, the reader's position in the underlying Stream object is advanced by the number of characters the method was able to read, but the characters already read into the internal ReadLine buffer are discarded. If you manipulate the position of the underlying stream after reading data into the buffer, the position of the underlying stream might not match the position of the internal buffer. To reset the internal buffer, call the DiscardBufferedData method; however, this method slows performance and should be called only when absolutely necessary.
/// </remarks>
public override string ReadToEnd()
{
char[] result = null;
if (_stream.CanSeek)
{
result = ReadSeekableStream();
}
else
{
result = ReadNonSeekableStream();
}
return new string(result);
}
private char[] ReadSeekableStream()
{
char[] chars = new char[(int)_stream.Length];
_ = Read(chars, 0, chars.Length);
return chars;
}
private char[] ReadNonSeekableStream()
{
ArrayList buffers = new();
int read;
int totalRead = 0;
char[] lastBuffer = null;
bool done = false;
do
{
char[] chars = new char[c_BufferSize];
read = Read(chars, 0, chars.Length);
totalRead += read;
if (read < c_BufferSize) // we are done
{
if (read > 0) // copy last scraps
{
char[] newChars = new char[read];
Array.Copy(chars, newChars, read);
lastBuffer = newChars;
}
done = true;
}
else
{
lastBuffer = chars;
}
buffers.Add(lastBuffer);
}
while (!done);
if (buffers.Count > 1)
{
char[] text = new char[totalRead];
int len = 0;
for (int i = 0; i < buffers.Count; ++i)
{
char[] buffer = (char[])buffers[i];
buffer.CopyTo(text, len);
len += buffer.Length;
}
return text;
}
else
{
return (char[])buffers[0];
}
}
private int FillBufferAndReset(int count)
{
if (_curBufPos != 0) Reset();
int totalRead = 0;
try
{
while (count > 0 && _curBufLen < _buffer.Length)
{
int spaceLeft = _buffer.Length - _curBufLen;
if (count > spaceLeft) count = spaceLeft;
int read = _stream.Read(_buffer, _curBufLen, count);
if (read == 0) break;
totalRead += read;
_curBufLen += read;
count -= read;
}
}
catch (Exception e)
{
throw new IOException("Stream.Read", e);
}
return totalRead;
}
private void Reset()
{
int bytesAvailable = _curBufLen - _curBufPos;
// here we trust that the copy in place doe not overwrites data
Array.Copy(_buffer, _curBufPos, _buffer, 0, bytesAvailable);
_curBufPos = 0;
_curBufLen = bytesAvailable;
}
}
}

Просмотреть файл

@ -0,0 +1,223 @@
//
// Copyright (c) .NET Foundation and Contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
using System.Text;
namespace System.IO
{
/// <summary>
/// Implements a <see cref="TextWriter"/> for writing characters to a stream in a particular encoding.
/// </summary>
public class StreamWriter : TextWriter
{
private const string c_NewLine = "\r\n";
private const int c_BufferSize = 0xFFF;
private Stream _stream;
private bool _disposed;
private byte[] _buffer;
private int _curBufPos;
/// <summary>
/// Gets the underlying stream that interfaces with a backing store.
/// </summary>
/// <value>The stream this <see cref="StreamWriter"/> is writing to.</value>
public virtual Stream BaseStream => _stream;
/// <summary>
/// Gets the <see cref="Encoding"/> in which the output is written.
/// </summary>
/// <value>The Encoding specified in the constructor for the current instance, or <see cref="UTF8Encoding"/> if an encoding was not specified.</value>
public override Encoding Encoding => Encoding.UTF8;
/// <summary>
/// Initializes a new instance of the <see cref="StreamWriter"/> class for the specified stream by using UTF-8 encoding and the default buffer size.
/// </summary>
/// <param name="stream">The stream to write to.</param>
/// <exception cref="ArgumentNullException"><paramref name="stream"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentException"><paramref name="stream"/> is not writable.</exception>
public StreamWriter(Stream stream)
{
if (stream == null)
{
throw new ArgumentNullException();
}
if (!stream.CanWrite)
{
throw new ArgumentException();
}
_stream = stream;
_buffer = new byte[c_BufferSize];
_curBufPos = 0;
_disposed = false;
}
/// <summary>
/// Closes the current <see cref="StreamWriter"/> object and the underlying stream.
/// </summary>
/// <remarks>
/// This method overrides <see cref="Stream.Close"/>.
/// This implementation of <see cref="Close"/> calls the <see cref="Dispose"/> method passing a true value.
/// You must call <see cref="Close"/> to ensure that all data is correctly written out to the underlying stream.Following a call to <see cref="Close"/>, any operations on the <see cref="StreamWriter"/> might raise exceptions. If there is insufficient space on the disk, calling <see cref="Close"/> will raise an exception.
/// Flushing the stream will not flush its underlying encoder unless you explicitly call <see cref="Flush"/> or <see cref="Close"/>.
/// </remarks>
public override void Close()
{
Dispose();
}
/// <summary>
/// Causes any buffered data to be written to the underlying stream, releases the unmanaged resources used by the StreamWriter, and optionally the managed resources.
/// </summary>
/// <param name="disposing"><see langword="true"/> to release both managed and unmanaged resources; <see langword="false"/> to release only unmanaged resources.</param>
/// <remarks>
/// When the disposing parameter is <see langword="true"/>, this method releases all resources held by any managed objects that this StreamWriter references. This method invokes the <see cref="Dispose"/> method of each referenced object.
/// </remarks>
protected override void Dispose(bool disposing)
{
if (_stream != null)
{
if (disposing)
{
try
{
if (_stream.CanWrite)
{
Flush();
}
}
catch { }
try
{
_stream.Close();
}
catch { }
}
_stream = null;
_buffer = null;
_curBufPos = 0;
}
_disposed = true;
}
/// <summary>
/// Clears all buffers for the current writer and causes any buffered data to be written to the underlying stream.
/// </summary>
/// <exception cref="ObjectDisposedException">The current writer is closed.</exception>
/// <exception cref="IOException">An I/O error has occurred.</exception>
/// <remarks>
/// This method overrides TextWriter.Flush.
/// Flushing the stream will not flush its underlying encoder unless you explicitly call Flush or <see cref="Close"/>.
/// </remarks>
public override void Flush()
{
if (_disposed)
{
throw new ObjectDisposedException();
}
if (_curBufPos > 0)
{
try
{
_stream.Write(_buffer, 0, _curBufPos);
}
catch (Exception e)
{
throw new IOException("StreamWriter Flush. ", e);
}
_curBufPos = 0;
}
}
/// <summary>
/// Writes a character to the stream.
/// </summary>
/// <param name="value"></param>
/// <remarks>
/// This method overrides <see cref="TextWriter.Write"/>.
/// The specified character is written to the underlying stream unless the end of the stream is reached prematurely.
/// </remarks>
public override void Write(char value)
{
byte[] buffer = Encoding.GetBytes(value.ToString());
WriteBytes(buffer, 0, buffer.Length);
}
/// <inheritdoc/>
public override void WriteLine()
{
byte[] tempBuf = Encoding.GetBytes(c_NewLine);
WriteBytes(tempBuf, 0, tempBuf.Length);
return;
}
/// <summary>
/// Writes a string to the stream, followed by a line terminator.
/// </summary>
/// <remarks>
/// This overload is equivalent to the <see cref="TextWriter.Write"/> overload.
/// The line terminator is defined by the CoreNewLine field.
/// This method does not search the specified string for individual newline characters(hexadecimal 0x000a) and replace them with NewLine.
/// </remarks>
public override void WriteLine(string value)
{
byte[] tempBuf = Encoding.GetBytes(value + c_NewLine);
WriteBytes(tempBuf, 0, tempBuf.Length);
return;
}
internal void WriteBytes(
byte[] buffer,
int index,
int count)
{
if (_disposed)
{
throw new ObjectDisposedException();
}
// if this write will overrun the buffer flush the current buffer to stream and
// write remaining bytes directly to stream.
if (_curBufPos + count >= c_BufferSize)
{
// Flush the current buffer to the stream and write new bytes
// directly to stream.
try
{
_stream.Write(_buffer, 0, _curBufPos);
_curBufPos = 0;
_stream.Write(buffer, index, count);
return;
}
catch (Exception e)
{
throw new IOException("StreamWriter WriteBytes.", e);
}
}
// else add bytes to the internal buffer
Array.Copy(buffer, index, _buffer, _curBufPos, count);
_curBufPos += count;
return;
}
}
}

Просмотреть файл

@ -0,0 +1,68 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup Label="Globals">
<NanoFrameworkProjectSystemPath>$(MSBuildExtensionsPath)\nanoFramework\v1.0\</NanoFrameworkProjectSystemPath>
</PropertyGroup>
<Import Project="$(NanoFrameworkProjectSystemPath)NFProjectSystem.Default.props" Condition="Exists('$(NanoFrameworkProjectSystemPath)NFProjectSystem.Default.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectTypeGuids>{11A8DD76-328B-46DF-9F39-F559912D0360};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<ProjectGuid>213d1b2e-23e6-4e3e-a5de-ab993a1b6175</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<FileAlignment>512</FileAlignment>
<RootNamespace>System.IO.Streams</RootNamespace>
<AssemblyName>System.IO.Streams</AssemblyName>
<TargetFrameworkVersion>v1.0</TargetFrameworkVersion>
<NF_IsCoreLibrary>True</NF_IsCoreLibrary>
<DocumentationFile>bin\$(Configuration)\System.IO.Streams.xml</DocumentationFile>
</PropertyGroup>
<PropertyGroup>
<SignAssembly>true</SignAssembly>
</PropertyGroup>
<PropertyGroup>
<AssemblyOriginatorKeyFile>key.snk</AssemblyOriginatorKeyFile>
</PropertyGroup>
<PropertyGroup>
<DelaySign>false</DelaySign>
</PropertyGroup>
<ItemGroup>
<NFMDP_PE_ExcludeClassByName Include="ThisAssembly">
<InProject>false</InProject>
</NFMDP_PE_ExcludeClassByName>
</ItemGroup>
<Import Project="$(NanoFrameworkProjectSystemPath)NFProjectSystem.props" Condition="Exists('$(NanoFrameworkProjectSystemPath)NFProjectSystem.props')" />
<ItemGroup>
<Compile Include="MemoryStream.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="StreamReader.cs" />
<Compile Include="StreamWriter.cs" />
<Compile Include="TextReader.cs" />
<Compile Include="TextWriter.cs" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<Reference Include="mscorlib">
<HintPath>..\packages\nanoFramework.CoreLibrary.1.12.0-preview.5\lib\mscorlib.dll</HintPath>
</Reference>
<Reference Include="nanoFramework.System.Text">
<HintPath>..\packages\nanoFramework.System.Text.1.1.3-preview.13\lib\nanoFramework.System.Text.dll</HintPath>
</Reference>
</ItemGroup>
<Import Project="$(NanoFrameworkProjectSystemPath)NFProjectSystem.CSharp.targets" Condition="Exists('$(NanoFrameworkProjectSystemPath)NFProjectSystem.CSharp.targets')" />
<ProjectExtensions>
<ProjectCapabilities>
<ProjectConfigurationsDeclaredAsItems />
</ProjectCapabilities>
</ProjectExtensions>
<Import Project="..\packages\Nerdbank.GitVersioning.3.4.255\build\Nerdbank.GitVersioning.targets" Condition="Exists('..\packages\Nerdbank.GitVersioning.3.4.255\build\Nerdbank.GitVersioning.targets')" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105.The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\packages\Nerdbank.GitVersioning.3.4.255\build\Nerdbank.GitVersioning.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Nerdbank.GitVersioning.3.4.255\build\Nerdbank.GitVersioning.targets'))" />
</Target>
</Project>

Просмотреть файл

@ -0,0 +1,164 @@
//
// Copyright (c) .NET Foundation and Contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
namespace System.IO
{
/// <summary>
/// Represents a reader that can read a sequential series of characters.
/// </summary>
/// <remarks>
/// <see cref="TextReader"/> is the abstract base class of StreamReader and StringReader, which read characters from streams and strings, respectively. Use these derived classes to open a text file for reading a specified range of characters, or to create a reader based on an existing stream.
/// </remarks>
[Serializable()]
public abstract class TextReader : MarshalByRefObject, IDisposable
{
/// <summary>
/// Initializes a new instance of the <see cref="TextReader"/> class.
/// </summary>
/// <remarks>
/// Use this constructor for derived classes.
/// </remarks>
protected TextReader() { }
/// <summary>
/// Closes the <see cref="TextReader"/> and releases any system resources associated with the <see cref="TextReader"/>.
/// </summary>
/// <remarks>
/// This implementation of <see cref="Close"/> calls the <see cref="TextReader.Dispose"/>(Boolean) method and passes it a true value.
/// </remarks>
public virtual void Close()
{
Dispose();
}
/// <summary>
/// Releases all resources used by the <see cref="TextReader"/> object.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases the unmanaged resources used by the <see cref="TextReader"/> and optionally releases the managed resources.
/// </summary>
/// <param name="disposing"><see langword="true"/> to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
/// <remarks>
/// This method is called by the public <see cref="Dispose"/> method and the Finalize method. By default, this method specifies the disposing parameter as <see langword="true"/>. Finalize specifies the disposing parameter as false.
/// When the disposing parameter is true, this method releases all resources held by any managed objects that this TextReader references. This method invokes the <see cref="Dispose"/> method of each referenced object.
/// </remarks>
protected virtual void Dispose(bool disposing)
{
}
/// <summary>
/// Reads the next character without changing the state of the reader or the character source. Returns the next available character without actually reading it from the reader.
/// </summary>
/// <returns>An integer representing the next character to be read, or -1 if no more characters are available or the reader does not support seeking.</returns>
/// <remarks>
/// <para>
/// The <see cref="Peek"/> method returns an integer value in order to determine whether the end of the file, or another error has occurred. This allows a user to first check if the returned value is -1 before casting it to a Char type.
/// </para>
/// <para>
/// The current position of the <see cref="TextReader"/> is not changed by this operation.The returned value is -1 if no more characters are available.The default implementation returns -1.
/// </para>
/// <para>The TextReader class is an abstract class. Therefore, you do not instantiate it in your code.For an example of using the Peek method, see the StreamReader.Peek method.
/// </para>
/// </remarks>
public virtual int Peek()
{
return -1;
}
/// <summary>
/// Reads the next character from the text reader and advances the character position by one character.
/// </summary>
/// <returns>The next character from the text reader, or -1 if no more characters are available. The default implementation returns -1.</returns>
/// <remarks>
/// The <see cref="TextReader"/> class is an abstract class. Therefore, you do not instantiate it in your code. For an example of using the Read method, see the StreamReader.Read method.
/// </remarks>
public virtual int Read()
{
return -1;
}
/// <summary>
/// Reads a specified maximum number of characters from the current reader and writes the data to a buffer, beginning at the specified index.
/// </summary>
/// <param name="buffer">When this method returns, contains the specified character array with the values between <paramref name="index"/> and (<paramref name="index"/> + <paramref name="count"/> - 1) replaced by the characters read from the current source.</param>
/// <param name="index">The position in <paramref name="buffer"/> at which to begin writing.</param>
/// <param name="count">The maximum number of characters to read. If the end of the reader is reached before the specified number of characters is read into the buffer, the method returns.</param>
/// <returns>The number of characters that have been read. The number will be less than or equal to <paramref name="count"/>, depending on whether the data is available within the reader. This method returns 0 (zero) if it is called when no more characters are left to read.</returns>
/// <remarks>
/// <para>
/// This method returns after either count characters are read or the end of the file is reached. <see cref="ReadBlock"/> is a blocking version of this method.
/// </para>
/// <para>
/// The <see cref="TextReader"/> class is an abstract class. Therefore, you do not instantiate it in your code.For an example of using the <see cref="Read"/> method, see the StreamReader.Read method.
/// </para>
/// </remarks>
public virtual int Read(char[] buffer, int index, int count)
{
return -1;
}
/// <summary>
/// Reads a specified maximum number of characters from the current text reader and writes the data to a buffer, beginning at the specified index.
/// </summary>
/// <param name="buffer">When this method returns, this parameter contains the specified character array with the values between <paramref name="index"/> and (<paramref name="index"/> + <paramref name="count"/> -1) replaced by the characters read from the current source.</param>
/// <param name="index">The position in <paramref name="buffer"/> at which to begin writing.</param>
/// <param name="count">The maximum number of characters to read.</param>
/// <returns>The number of characters that have been read. The number will be less than or equal to <paramref name="count"/>, depending on whether all input characters have been read.</returns>
/// <remarks>
/// <para>
/// The position of the underlying text reader is advanced by the number of characters that were read into buffer.
/// </para>
/// <para>
/// The method blocks until either count characters are read, or all characters have been read.This is a blocking version of <see cref="Read"/>.
/// </para>
/// </remarks>
public virtual int ReadBlock(char[] buffer, int index, int count)
{
int i, n = 0;
do
{
n += (i = Read(buffer, index + n, count - n));
} while (i > 0 && n < count);
return n;
}
/// <summary>
/// Reads a line of characters from the text reader and returns the data as a string.
/// </summary>
/// <returns>The next line from the reader, or <see langword="null"/> if all characters have been read.</returns>
/// <remarks>
/// A line is defined as a sequence of characters followed by a carriage return (0x000d), a line feed (0x000a), a carriage return followed by a line feed, Environment.NewLine, or the end-of-stream marker. The string that is returned does not contain the terminating carriage return or line feed. The return value is null if the end of the input stream has been reached.
/// If the method throws an OutOfMemoryException exception, the reader's position in the underlying Stream is advanced by the number of characters the method was able to read, but the characters that were already read into the internal ReadLine buffer are discarded. Because the position of the reader in the stream cannot be changed, the characters that were already read are unrecoverable and can be accessed only by reinitializing the TextReader object. If the initial position within the stream is unknown or the stream does not support seeking, the underlying Stream also needs to be reinitialized.
/// To avoid such a situation and produce robust code you should use the Read method and store the read characters in a preallocated buffer.
/// The TextReader class is an abstract class. Therefore, you do not instantiate it in your code.For an example of using the ReadLine method, see the StreamReader.ReadLine method.
/// </remarks>
public virtual string ReadLine()
{
return null;
}
/// <summary>
/// Reads all characters from the current position to the end of the text reader and returns them as one string.
/// </summary>
/// <returns>A string that contains all characters from the current position to the end of the text reader.</returns>
/// <remarks>
/// If the method throws an <see cref="OutOfMemoryException"/> exception, the reader's position in the underlying Stream is advanced by the number of characters the method was able to read, but the characters that were already read into the internal ReadToEnd buffer are discarded. Because the position of the reader in the stream cannot be changed, the characters that were already read are unrecoverable and can be accessed only by reinitializing the TextReader. If the initial position within the stream is unknown or the stream does not support seeking, the underlying Stream also needs to be reinitialized.
/// To avoid such a situation and produce robust code you should use the Read method and store the read characters in a preallocated buffer.
/// The <see cref="TextReader"/> class is an abstract class. Therefore, you do not instantiate it in your code.For an example of using the ReadToEnd method, see the StreamReader.ReadToEnd method.</remarks>
public virtual string ReadToEnd()
{
return null;
}
}
}

Просмотреть файл

@ -0,0 +1,377 @@
//
// Copyright (c) .NET Foundation and Contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
using System.Text;
namespace System.IO
{
/// <summary>
/// Represents a writer that can write a sequential series of characters. This class is abstract.
/// </summary>
[Serializable]
public abstract class TextWriter : MarshalByRefObject, IDisposable
{
private const string _InitialNewLine = "\r\n";
/// <summary>
/// Stores the newline characters used for this <see cref="TextWriter"/>.
/// </summary>
protected char[] CoreNewLine = new char[] { '\r', '\n' };
/// <summary>
/// When overridden in a derived class, returns the character encoding in which the output is written.
/// </summary>
public abstract Encoding Encoding { get; }
/// <summary>
/// Gets or sets the line terminator string used by the current <see cref="TextWriter"/>.
/// </summary>
public virtual string NewLine
{
get
{
return new string(CoreNewLine);
}
set
{
if (value == null)
{
value = _InitialNewLine;
}
CoreNewLine = value.ToCharArray();
}
}
/// <summary>
/// Closes the current writer and releases any system resources associated with the writer.
/// </summary>
public virtual void Close()
{
Dispose();
}
/// <summary>
/// Releases the unmanaged resources used by the <see cref="TextWriter"/> and optionally releases the managed resources.
/// </summary>
/// <param name="disposing"><see langword="true"/> to release both managed and unmanaged resources; <see langword="false"/> to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
}
/// <summary>
/// Releases all resources used by the <see cref="TextWriter"/> object.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Clears all buffers for the current writer and causes any buffered data to be written to the underlying device.
/// </summary>
/// <remarks>
/// <para>
/// This default method does nothing, but derived classes can override the method to provide the appropriate functionality.
/// </para>
/// <para>Flushing the stream will not flush its underlying encoder unless you explicitly call <see cref="Flush"/> or <see cref="Close"/>. Setting AutoFlush to <see langword="true"/> means that data will be flushed from the buffer to the stream, but the encoder state will not be flushed. This allows the encoder to keep its state (partial characters) so that it can encode the next block of characters correctly. This scenario affects UTF8 and UTF7 where certain characters can only be encoded after the encoder receives the adjacent character or characters.
/// </para>
/// </remarks>
public virtual void Flush()
{
}
/// <summary>
/// Writes a character to the text stream.
/// </summary>
/// <param name="value">The character to write to the text stream.</param>
public virtual void Write(char value)
{
}
/// <summary>
/// Writes a character array to the text stream.
/// </summary>
/// <param name="buffer">The character array to write to the text stream.</param>
public virtual void Write(char[] buffer)
{
if (buffer != null)
{
Write(buffer, 0, buffer.Length);
}
}
/// <summary>
/// Writes a subarray of characters to the text stream.
/// </summary>
/// <param name="buffer">The character array to write data from.</param>
/// <param name="index">The character position in the buffer at which to start retrieving data.</param>
/// <param name="count">The number of characters to write.</param>
/// <exception cref="ArgumentNullException">The <paramref name="buffer"/> parameter is <see langword="null"/>.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> or <paramref name="count"/> is negative.</exception>
/// <exception cref="ArgumentException">The <paramref name="buffer"/> length minus <paramref name="index"/> is less than <paramref name="count"/>.</exception>
public virtual void Write(char[] buffer, int index, int count)
{
if (buffer == null)
{
throw new ArgumentNullException();
}
if (index < 0)
{
throw new ArgumentOutOfRangeException();
}
if (count < 0)
{
throw new ArgumentOutOfRangeException();
}
if (buffer.Length - index < count)
{
throw new ArgumentException();
}
for (int i = 0; i < count; i++)
{
Write(buffer[index + i]);
}
}
/// <summary>
/// Writes the text representation of a <see cref="bool"/> value to the text stream.
/// </summary>
/// <param name="value">The <see cref="bool"/> value to write.</param>
public virtual void Write(bool value)
{
Write(value);
}
/// <summary>
/// Writes the text representation of a 4-byte signed integer to the text stream.
/// </summary>
/// <param name="value">The 4-byte signed integer to write.</param>
public virtual void Write(int value)
{
Write(value.ToString());
}
/// <summary>
/// Writes the text representation of a 4-byte unsigned integer to the text stream.
/// </summary>
/// <param name="value">The 4-byte unsigned integer to write.</param>
[System.CLSCompliant(false)]
public virtual void Write(uint value)
{
Write(value.ToString());
}
/// <summary>
/// Writes the text representation of an 8-byte signed integer to the text stream.
/// </summary>
/// <param name="value">The 8-byte signed integer to write.</param>
public virtual void Write(long value)
{
Write(value.ToString());
}
/// <summary>
/// Writes the text representation of an 8-byte unsigned integer to the text stream.
/// </summary>
/// <param name="value">The 8-byte unsigned integer to write.</param>
[System.CLSCompliant(false)]
public virtual void Write(ulong value)
{
Write(value.ToString());
}
/// <summary>
/// Writes the text representation of a 4-byte floating-point value to the text stream.
/// </summary>
/// <param name="value">The 4-byte floating-point value to write.</param>
public virtual void Write(float value)
{
Write(value.ToString());
}
/// <summary>
/// Writes the text representation of an 8-byte floating-point value to the text stream.
/// </summary>
/// <param name="value">The 8-byte floating-point value to write.</param>
public virtual void Write(double value)
{
Write(value.ToString());
}
/// <summary>
/// Writes a string to the text stream.
/// </summary>
/// <param name="value">The string to write.</param>
public virtual void Write(string value)
{
if (value != null)
{
Write(value.ToCharArray());
}
}
/// <summary>
/// Writes the text representation of an object to the text stream by calling the <see cref="ToString"/> method on that object.
/// </summary>
/// <param name="value">The object to write.</param>
public virtual void Write(object value)
{
if (value != null)
{
Write(value.ToString());
}
}
/// <summary>
/// Writes a line terminator to the text stream.
/// </summary>
public virtual void WriteLine()
{
Write(CoreNewLine);
}
/// <summary>
/// Writes a character to the text stream, followed by a line terminator.
/// </summary>
/// <param name="value">The character to write to the text stream.</param>
public virtual void WriteLine(char value)
{
Write(value);
WriteLine();
}
/// <summary>
/// Writes a character array to the text stream, followed by a line terminator.
/// </summary>
/// <param name="buffer">The character array to write to the text stream.</param>
public virtual void WriteLine(char[] buffer)
{
Write(buffer);
WriteLine();
}
/// <summary>
/// Writes a subarray of characters to the text stream, followed by a line terminator.
/// </summary>
/// <param name="buffer">The character array to write data from.</param>
/// <param name="index">The character position in the buffer at which to start retrieving data.</param>
/// <param name="count">The number of characters to write.</param>
/// <exception cref="ArgumentNullException">The <paramref name="buffer"/> parameter is <see langword="null"/>.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> or <paramref name="count"/> is negative.</exception>
/// <exception cref="ArgumentException">The <paramref name="buffer"/> length minus <paramref name="index"/> is less than <paramref name="count"/>.</exception>
public virtual void WriteLine(char[] buffer, int index, int count)
{
Write(buffer, index, count);
WriteLine();
}
/// <summary>
/// Writes the text representation of a <see cref="bool"/> value to the text stream, followed by a line terminator.
/// </summary>
/// <param name="value">The <see cref="bool"/> value to write.</param>
public virtual void WriteLine(bool value)
{
Write(value);
WriteLine();
}
/// <summary>
/// Writes the text representation of a 4-byte signed integer to the text stream, followed by a line terminator.
/// </summary>
/// <param name="value">The 4-byte signed integer to write.</param>
public virtual void WriteLine(int value)
{
Write(value);
WriteLine();
}
/// <summary>
/// Writes the text representation of a 4-byte unsigned integer to the text stream, followed by a line terminator.
/// </summary>
/// <param name="value">The 4-byte unsigned integer to write.</param>
[System.CLSCompliant(false)]
public virtual void WriteLine(uint value)
{
Write(value);
WriteLine();
}
/// <summary>
/// Writes the text representation of an 8-byte signed integer to the text stream, followed by a line terminator.
/// </summary>
/// <param name="value">The 8-byte signed integer to write.</param>
public virtual void WriteLine(long value)
{
Write(value);
WriteLine();
}
/// <summary>
/// Writes the text representation of an 8-byte unsigned integer to the text stream, followed by a line terminator.
/// </summary>
/// <param name="value">The 8-byte unsigned integer to write.</param>
[System.CLSCompliant(false)]
public virtual void WriteLine(ulong value)
{
Write(value);
WriteLine();
}
/// <summary>
/// Writes the text representation of a 4-byte floating-point value to the text stream, followed by a line terminator.
/// </summary>
/// <param name="value">The 4-byte floating-point value to write.</param>
public virtual void WriteLine(float value)
{
Write(value);
WriteLine();
}
/// <summary>
/// Writes the text representation of an 8-byte floating-point value to the text stream, followed by a line terminator.
/// </summary>
/// <param name="value">The 8-byte floating-point value to write.</param>
public virtual void WriteLine(double value)
{
Write(value);
WriteLine();
}
/// <summary>
/// Writes a string to the text stream, followed by a line terminator.
/// </summary>
/// <param name="value">The string to write.</param>
public virtual void WriteLine(string value)
{
Write(value);
WriteLine();
}
/// <summary>
/// Writes the text representation of an object to the text stream by calling the <see cref="ToString"/> method on that object, followed by a line terminator.
/// </summary>
/// <param name="value">The object to write.</param>
public virtual void WriteLine(object value)
{
if (value == null)
{
WriteLine();
}
else
{
WriteLine(value.ToString());
}
}
}
}

Двоичные данные
System.IO.Streams/key.snk Normal file

Двоичный файл не отображается.

Просмотреть файл

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="nanoFramework.CoreLibrary" version="1.12.0-preview.5" targetFramework="netnanoframework10" />
<package id="nanoFramework.System.Text" version="1.1.3-preview.13" targetFramework="netnanoframework10" />
<package id="Nerdbank.GitVersioning" version="3.4.255" developmentDependency="true" targetFramework="netnanoframework10" />
</packages>

Просмотреть файл

@ -0,0 +1,55 @@
//
// Copyright (c) .NET Foundation and Contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
using nanoFramework.TestFramework;
using System;
using System.IO;
namespace Sytem.IO.MemoryStreamUnitTests
{
[TestClass]
public class CanRead
{
[TestMethod]
public void CanRead_Default_Ctor()
{
try
{
OutputHelper.WriteLine("Verify CanRead is true for default Ctor");
using (MemoryStream fs = new MemoryStream())
{
Assert.True(fs.CanRead, "Expected CanRead == true, but got CanRead == false");
}
}
catch (Exception ex)
{
OutputHelper.WriteLine($"Unexpected exception {ex}");
}
}
[TestMethod]
public void CanRead_Byte_Ctor()
{
try
{
OutputHelper.WriteLine("Verify CanRead is true for Byte[] Ctor");
byte[] buffer = new byte[1024];
using (MemoryStream fs = new MemoryStream(buffer))
{
Assert.True(fs.CanRead, "Expected CanRead == true, but got CanRead == false");
}
}
catch (Exception ex)
{
OutputHelper.WriteLine($"Unexpected exception {ex}");
}
}
}
}

Просмотреть файл

@ -0,0 +1,54 @@
//
// Copyright (c) .NET Foundation and Contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
using nanoFramework.TestFramework;
using System;
using System.IO;
namespace Sytem.IO.MemoryStreamUnitTests
{
[TestClass]
public class CanSeek
{
[TestMethod]
public void CanSeek_Default_Ctor()
{
try
{
OutputHelper.WriteLine("Verify CanSeek is true for default Ctor");
using (MemoryStream fs = new MemoryStream())
{
Assert.True(fs.CanSeek, "Expected CanSeek == true, but got CanSeek == false");
}
}
catch (Exception ex)
{
OutputHelper.WriteLine($"Unexpected exception {ex}");
}
}
[TestMethod]
public void CanSeek_Byte_Ctor()
{
try
{
OutputHelper.WriteLine("Verify CanSeek is true for Byte[] Ctor");
byte[] buffer = new byte[1024];
using (MemoryStream fs = new MemoryStream(buffer))
{
Assert.True(fs.CanSeek, "Expected CanSeek == true, but got CanSeek == false");
}
}
catch (Exception ex)
{
OutputHelper.WriteLine($"Unexpected exception {ex}");
}
}
}
}

Просмотреть файл

@ -0,0 +1,55 @@
//
// Copyright (c) .NET Foundation and Contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
using nanoFramework.TestFramework;
using System;
using System.IO;
namespace Sytem.IO.MemoryStreamUnitTests
{
[TestClass]
public class CanWrite
{
[TestMethod]
public void CanWrite_Default_Ctor()
{
try
{
OutputHelper.WriteLine("Verify CanWrite is true for default Ctor");
using (MemoryStream fs = new MemoryStream())
{
Assert.True(fs.CanWrite, "Expected CanWrite == true, but got CanWrite == false");
}
}
catch (Exception ex)
{
OutputHelper.WriteLine($"Unexpected exception {ex}");
}
}
[TestMethod]
public void CanWrite_Byte_Ctor()
{
try
{
OutputHelper.WriteLine("Verify CanWrite is true for Byte[] Ctor");
byte[] buffer = new byte[1024];
using (MemoryStream fs = new MemoryStream(buffer))
{
Assert.True(fs.CanWrite, "Expected CanWrite == true, but got CanWrite == false");
}
}
catch (Exception ex)
{
OutputHelper.WriteLine($"Unexpected exception {ex}");
}
}
}
}

Просмотреть файл

@ -0,0 +1,43 @@
//
// Copyright (c) .NET Foundation and Contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
using nanoFramework.TestFramework;
using System;
using System.IO;
namespace Sytem.IO.MemoryStreamUnitTests
{
[TestClass]
public class Close
{
[TestMethod]
public void VerifyClose()
{
try
{
MemoryStream ms = new MemoryStream();
ms.WriteByte(0);
OutputHelper.WriteLine("Close stream");
ms.Close();
Assert.Throws(typeof(ObjectDisposedException),
() =>
{
OutputHelper.WriteLine("Verify actually closed by writing to it");
ms.WriteByte(0);
},
"Expected ObjectDisposedException");
}
catch (Exception ex)
{
OutputHelper.WriteLine($"Unexpected exception {ex}");
}
}
}
}

Просмотреть файл

@ -0,0 +1,37 @@
//
// Copyright (c) .NET Foundation and Contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
using nanoFramework.TestFramework;
using System;
using System.IO;
namespace Sytem.IO.MemoryStreamUnitTests
{
[TestClass]
public class Flush
{
[TestMethod]
public void VerifyFlush()
{
try
{
using (MemoryStream ms = new MemoryStream())
{
byte[] data = MemoryStreamHelper.GetRandomBytes(5000);
ms.Write(data, 0, data.Length);
ms.Flush();
Assert.Equal(ms.Length, 5000, $"Expected 5000 bytes, but got {ms.Length}");
}
}
catch (Exception ex)
{
OutputHelper.WriteLine($"Unexpected exception {ex}");
}
}
}
}

Просмотреть файл

@ -0,0 +1,113 @@
//
// Copyright (c) .NET Foundation and Contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
using nanoFramework.TestFramework;
using System;
using System.IO;
namespace Sytem.IO.MemoryStreamUnitTests
{
[TestClass]
public class Length
{
#region Helper methods
private bool TestLength(MemoryStream ms, long expectedLength)
{
if (ms.Length != expectedLength)
{
OutputHelper.WriteLine("Expected length " + expectedLength + " but got, " + ms.Length);
return false;
}
return true;
}
private bool TestPosition(MemoryStream ms, long expectedPosition)
{
if (ms.Position != expectedPosition)
{
OutputHelper.WriteLine("Expected position " + expectedPosition + " but got, " + ms.Position);
return false;
}
return true;
}
#endregion Helper methods
#region Test Cases
[TestMethod]
public void ObjectDisposed()
{
try
{
MemoryStream ms = new MemoryStream();
ms.Close();
long length = 0;
Assert.Throws(typeof(ObjectDisposedException),
() =>
{
length = ms.Length;
},
$"Expected ObjectDisposedException, but got length {length}");
}
catch (Exception ex)
{
OutputHelper.WriteLine($"Unexpected exception {ex}");
}
}
[TestMethod]
public void LengthTests()
{
try
{
using (MemoryStream ms = new MemoryStream())
{
OutputHelper.WriteLine("Set initial length to 50, and position to 50");
ms.SetLength(50);
ms.Position = 50;
Assert.True(TestLength(ms, 50));
OutputHelper.WriteLine("Write 'foo bar'");
StreamWriter sw = new StreamWriter(ms);
sw.Write("foo bar");
sw.Flush();
Assert.True(TestLength(ms, 57));
OutputHelper.WriteLine("Shorten Length to 30");
ms.SetLength(30);
Assert.True(TestLength(ms, 30));
OutputHelper.WriteLine("Verify position was adjusted");
Assert.True(TestPosition(ms, 30));
OutputHelper.WriteLine("Extend length to 100");
ms.SetLength(100);
Assert.True(TestLength(ms, 100));
}
OutputHelper.WriteLine("Verify memorystream is 0 bytes after close");
using (MemoryStream ms = new MemoryStream())
{
Assert.True(TestLength(ms, 0));
}
}
catch (Exception ex)
{
OutputHelper.WriteLine($"Unexpected exception {ex}");
}
}
#endregion Test Cases
}
}

Просмотреть файл

@ -0,0 +1,113 @@
//
// Copyright (c) .NET Foundation and Contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
using nanoFramework.TestFramework;
using System;
using System.IO;
namespace Sytem.IO.MemoryStreamUnitTests
{
public class MemoryStreamHelper
{
public static bool WriteReadEmpty(Stream ms)
{
bool result = true;
if (ms.Position != 0)
{
result = false;
OutputHelper.WriteLine("Expected postion 0, but got " + ms.Position);
}
if (ms.Length != 0)
{
result = false;
OutputHelper.WriteLine("Expected length 0, but got " + ms.Length);
}
return WriteReadVerify(ms) & result;
}
public static bool WriteReadVerify(Stream ms)
{
bool result = Write(ms, 300);
// Flush writes
ms.Flush();
OutputHelper.WriteLine("Seek to start and Read");
ms.Seek(0, SeekOrigin.Begin);
result &= VerifyRead(ms);
return result;
}
public static bool Write(Stream ms, int length)
{
bool result = true;
long startLength = ms.Length;
// we can only write 0-255, so mod the
// length to figure out next data value
long data = startLength % 256;
OutputHelper.WriteLine("Seek to end");
ms.Seek(0, SeekOrigin.End);
OutputHelper.WriteLine("Write to file");
for (long i = startLength; i < startLength + length; i++)
{
ms.WriteByte((byte)data++);
// if we hit max byte, reset
if (data > 255)
{
data = 0;
}
}
return result;
}
public static bool VerifyRead(Stream ms)
{
bool result = true;
OutputHelper.WriteLine("Verify " + ms.Length + " bytes of data in file");
// we can only read 0-255, so mod the
// position to figure out next data value
int nextbyte = (int)ms.Position % 256;
for (int i = 0; i < ms.Length; i++)
{
int readByte = ms.ReadByte();
if (readByte != nextbyte)
{
result = false;
OutputHelper.WriteLine("Byte in position " + i + " has wrong value: " + readByte);
}
// Reset if wraps past 255
if (++nextbyte > 255)
{
nextbyte = 0;
}
}
return result;
}
public static byte[] GetRandomBytes(int length)
{
byte[] byteArr = new byte[length];
Random s_random = new Random();
s_random.NextBytes(byteArr);
return byteArr;
}
}
}

Просмотреть файл

@ -0,0 +1,84 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup Label="Globals">
<NanoFrameworkProjectSystemPath>$(MSBuildExtensionsPath)\nanoFramework\v1.0\</NanoFrameworkProjectSystemPath>
</PropertyGroup>
<Import Project="$(NanoFrameworkProjectSystemPath)NFProjectSystem.Default.props" Condition="Exists('$(NanoFrameworkProjectSystemPath)NFProjectSystem.Default.props')" />
<ItemGroup>
<ProjectCapability Include="TestContainer" />
</ItemGroup>
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectTypeGuids>{11A8DD76-328B-46DF-9F39-F559912D0360};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<ProjectGuid>acfdaca6-8c62-412d-b0b9-3059601a3d9c</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<FileAlignment>512</FileAlignment>
<RootNamespace>MemoryStreamUnitTests</RootNamespace>
<AssemblyName>NFUnitTest</AssemblyName>
<IsCodedUITest>False</IsCodedUITest>
<IsTestProject>true</IsTestProject>
<TestProjectType>UnitTest</TestProjectType>
<TargetFrameworkVersion>v1.0</TargetFrameworkVersion>
</PropertyGroup>
<Import Project="$(NanoFrameworkProjectSystemPath)NFProjectSystem.props" Condition="Exists('$(NanoFrameworkProjectSystemPath)NFProjectSystem.props')" />
<PropertyGroup>
<RunSettingsFilePath>$(MSBuildProjectDirectory)\nano.runsettings</RunSettingsFilePath>
</PropertyGroup>
<ItemGroup>
<Compile Include="WriteByte.cs" />
<Compile Include="Write.cs" />
<Compile Include="ToArray.cs" />
<Compile Include="SetLength.cs" />
<Compile Include="Seek.cs" />
<Compile Include="ReadByte.cs" />
<Compile Include="Read.cs" />
<Compile Include="Position.cs" />
<Compile Include="MemoryStreamHelper.cs" />
<Compile Include="Length.cs" />
<Compile Include="Flush.cs" />
<Compile Include="Close.cs" />
<Compile Include="CanWrite.cs" />
<Compile Include="CanSeek.cs" />
<Compile Include="WriteTo.cs" />
<Compile Include="CanRead.cs" />
<Compile Include="MemoryStream_Ctor.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<Reference Include="mscorlib">
<HintPath>..\..\packages\nanoFramework.CoreLibrary.1.12.0-preview.5\lib\mscorlib.dll</HintPath>
</Reference>
<Reference Include="nanoFramework.System.Text">
<HintPath>..\..\packages\nanoFramework.System.Text.1.1.3-preview.13\lib\nanoFramework.System.Text.dll</HintPath>
</Reference>
<Reference Include="nanoFramework.TestFramework">
<HintPath>..\..\packages\nanoFramework.TestFramework.1.0.175\lib\nanoFramework.TestFramework.dll</HintPath>
</Reference>
<Reference Include="nanoFramework.UnitTestLauncher">
<HintPath>..\..\packages\nanoFramework.TestFramework.1.0.175\lib\nanoFramework.UnitTestLauncher.exe</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<None Include="nano.runsettings" />
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\System.IO.Streams\System.IO.Streams.nfproj" />
</ItemGroup>
<Import Project="$(NanoFrameworkProjectSystemPath)NFProjectSystem.CSharp.targets" Condition="Exists('$(NanoFrameworkProjectSystemPath)NFProjectSystem.CSharp.targets')" />
<!-- MANUAL UPDATE HERE -->
<Import Project="..\..\packages\nanoFramework.TestFramework.1.0.175\build\nanoFramework.TestFramework.targets" Condition="Exists('..\..\packages\nanoFramework.TestFramework.1.0.175\build\nanoFramework.TestFramework.targets')" />
<ProjectExtensions>
<ProjectCapabilities>
<ProjectConfigurationsDeclaredAsItems />
</ProjectCapabilities>
</ProjectExtensions>
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<WarningText>Update the Import path in nfproj to the correct nanoFramework.TestFramework NuGet package folder.</WarningText>
</PropertyGroup>
<Warning Condition="!Exists('..\..\packages\nanoFramework.TestFramework.1.0.175\build\nanoFramework.TestFramework.targets')" Text="'$(WarningText)'" />
</Target>
</Project>

Просмотреть файл

@ -0,0 +1,147 @@
//
// Copyright (c) .NET Foundation and Contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
using nanoFramework.TestFramework;
using System;
using System.IO;
namespace Sytem.IO.MemoryStreamUnitTests
{
[TestClass]
public class MemoryStream_Ctor
{
#region Test Cases
[TestMethod]
public void InvalidArguments()
{
Assert.Throws(
typeof(ArgumentNullException), () =>
{
OutputHelper.WriteLine("null buffer");
using (MemoryStream fs = new MemoryStream(null)) { }
OutputHelper.WriteLine("Expected ArgumentNullException");
},
"Unexpected exception");
}
[TestMethod]
public void Valid_Default_Ctor()
{
try
{
using (MemoryStream ms = new MemoryStream())
{
Assert.True(ValidateMemoryStream(ms, 0), "Failed to ValidateMemoryStream");
}
}
catch (Exception ex)
{
OutputHelper.WriteLine($"Unexpected exception: {ex}");
}
}
[TestMethod]
public void Variable_Buffer_Ctor()
{
try
{
OutputHelper.WriteLine("Verify buffer constructors length 0-100");
for (int i = 0; i < 100; i++)
{
byte[] buffer = new byte[i];
using (MemoryStream ms = new MemoryStream(buffer))
{
Assert.True(ValidateMemoryStream(ms, i), "Failed to ValidateMemoryStream");
OutputHelper.WriteLine("Try to extend beyond buffer length");
Assert.Throws(typeof(NotSupportedException),
() =>
{
ms.SetLength(i + 1);
OutputHelper.WriteLine("Expected NotSupportedException");
},
"Failed to throw NotSupportedException");
OutputHelper.WriteLine("Truncate to 0");
for (int j = buffer.Length; j >= 0; j--)
{
ms.SetLength(j);
}
}
}
OutputHelper.WriteLine("Verify 10k buffer constructor");
byte[] largeBuffer = new byte[10000];
using (MemoryStream ms = new MemoryStream(largeBuffer))
{
Assert.True(ValidateMemoryStream(ms, largeBuffer.Length), "Failed to ValidateMemoryStream");
}
}
catch (Exception ex)
{
OutputHelper.WriteLine($"Unexpected exception: {ex}");
}
}
#endregion Test Cases
#region Helper methods
private bool ValidateMemoryStream(
MemoryStream ms,
int ExpectedLength)
{
bool success = true;
OutputHelper.WriteLine("Check Length");
if (ms.Length != ExpectedLength)
{
success = false;
OutputHelper.WriteLine($"Expected Length 0, but got Length {ms.Length}");
}
OutputHelper.WriteLine("Check CanSeek");
if (!ms.CanSeek)
{
success = false;
OutputHelper.WriteLine("Expected CanSeek to be true, but was false");
}
OutputHelper.WriteLine("Check CanRead");
if (!ms.CanRead)
{
success = false;
OutputHelper.WriteLine("Expected CanRead to be true, but was false");
}
OutputHelper.WriteLine("Check CanWrite");
if (!ms.CanWrite)
{
success = false;
OutputHelper.WriteLine("Expected CanWrite to be true, but was false");
}
if (ms.Position != 0)
{
success = false;
OutputHelper.WriteLine("Expected Position to be 0, but was " + ms.Position);
}
return success;
}
#endregion Helper methods
}
}

Просмотреть файл

@ -0,0 +1,158 @@
//
// Copyright (c) .NET Foundation and Contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
using nanoFramework.TestFramework;
using System;
using System.IO;
namespace Sytem.IO.MemoryStreamUnitTests
{
[TestClass]
public class Position
{
#region Helper methods
private bool GetSetPosition(MemoryStream ms, int TestLength)
{
bool success = true;
OutputHelper.WriteLine("Move forwards");
for (int i = 0; i < TestLength; i++)
{
ms.Position = i;
if (ms.Position != i)
{
success = false;
OutputHelper.WriteLine("Expected position " + i + " but got position " + ms.Position);
}
}
OutputHelper.WriteLine("Move backwards");
for (int i = TestLength - 1; i >= 0; i--)
{
ms.Position = i;
if (ms.Position != i)
{
success = false;
OutputHelper.WriteLine("Expected position " + i + " but got position " + ms.Position);
}
}
return success;
}
#endregion Helper methods
#region Test Cases
[TestMethod]
public void ObjectDisposed()
{
MemoryStream ms = new MemoryStream();
ms.Close();
try
{
try
{
long position = ms.Position;
OutputHelper.WriteLine("Expected ObjectDisposedException, but got position " + position);
}
catch (ObjectDisposedException) { /*Pass Case */ }
try
{
ms.Position = 0;
OutputHelper.WriteLine("Expected ObjectDisposedException, but set position");
}
catch (ObjectDisposedException) { /*Pass Case */ }
}
catch (Exception ex)
{
OutputHelper.WriteLine("Unexpected exception: " + ex.Message);
}
}
[TestMethod]
public void InvalidRange()
{
try
{
byte[] buffer = new byte[100];
using (MemoryStream ms = new MemoryStream(buffer))
{
OutputHelper.WriteLine("Try -1 postion");
Assert.Throws(typeof(ArgumentOutOfRangeException),
() =>
{
ms.Position = -1;
},
"Expected ArgumentOutOfRangeException");
OutputHelper.WriteLine("Try Long.MinValue postion");
Assert.Throws(typeof(ArgumentOutOfRangeException),
() =>
{
ms.Position = long.MinValue;
},
"Expected ArgumentOutOfRangeException");
}
}
catch (Exception ex)
{
OutputHelper.WriteLine($"Unexpected exception {ex}");
}
}
[TestMethod]
public void GetSetStaticBuffer()
{
try
{
byte[] buffer = new byte[1000];
OutputHelper.WriteLine("Get/Set Position with static buffer");
using (MemoryStream ms = new MemoryStream(buffer))
{
Assert.True(GetSetPosition(ms, buffer.Length));
}
}
catch (Exception ex)
{
OutputHelper.WriteLine($"Unexpected exception {ex}");
}
}
[TestMethod]
public void GetSetDynamicBuffer()
{
try
{
OutputHelper.WriteLine("Get/Set Position with dynamic buffer");
using (MemoryStream ms = new MemoryStream())
{
Assert.True(GetSetPosition(ms, 1000));
}
}
catch (Exception ex)
{
OutputHelper.WriteLine($"Unexpected exception {ex}");
}
}
#endregion Test Cases
}
}

Просмотреть файл

@ -0,0 +1,31 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyCopyright("Copyright (c) 2021 nanoFramework contributors")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

Просмотреть файл

@ -0,0 +1,197 @@
//
// Copyright (c) .NET Foundation and Contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
using nanoFramework.TestFramework;
using System;
using System.IO;
using System.Text;
namespace Sytem.IO.MemoryStreamUnitTests
{
[TestClass]
public class Read
{
#region Local Helper methods
private bool TestRead(MemoryStream ms, int length)
{
return TestRead(ms, length, length, length);
}
private bool TestRead(MemoryStream ms, int BufferLength, int BytesToRead, int BytesExpected)
{
bool result = true;
int nextbyte = (int)ms.Position % 256;
byte[] byteBuffer = new byte[BufferLength];
int bytesRead = ms.Read(byteBuffer, 0, BytesToRead);
if (bytesRead != BytesExpected)
{
result = false;
OutputHelper.WriteLine($"Expected {BytesToRead} bytes, but got {bytesRead} bytes");
}
for (int i = 0; i < bytesRead; i++)
{
if (byteBuffer[i] != nextbyte)
{
result = false;
OutputHelper.WriteLine($"Byte in position {i} has wrong value: {byteBuffer[i]}");
}
// Reset if wraps past 255
if (++nextbyte > 255)
{
nextbyte = 0;
}
}
return result;
}
#endregion Local Helper methods
#region Test Cases
[TestMethod]
public void InvalidCases()
{
try
{
using (MemoryStream ms = new MemoryStream())
{
OutputHelper.WriteLine("null Buffer");
int read = 0;
Assert.Throws(typeof(NotSupportedException),
() =>
{
read = ms.Read(null, 0, 0);
},
$"Expected ArgumentNullException, but read {read} bytes");
OutputHelper.WriteLine("negative offset");
Assert.Throws(typeof(ArgumentOutOfRangeException),
() =>
{
read = ms.Read(new byte[] { 1 }, -1, 0);
},
$"Expected ArgumentOutOfRangeException, but read {read} bytes");
OutputHelper.WriteLine("negative count");
Assert.Throws(typeof(ArgumentOutOfRangeException),
() =>
{
read = ms.Read(new byte[] { 1 }, 0, -1);
},
$"Expected ArgumentOutOfRangeException, but read {read} bytes");
OutputHelper.WriteLine("offset exceeds buffer size");
Assert.Throws(typeof(ArgumentException),
() =>
{
read = ms.Read(new byte[] { 1 }, 2, 0);
},
$"Expected ArgumentException, but read {read} bytes");
OutputHelper.WriteLine("count exceeds buffer size");
Assert.Throws(typeof(ArgumentException),
() =>
{
read = ms.Read(new byte[] { 1 }, 0, 2);
},
$"Expected ArgumentException, but read {read} bytes");
}
MemoryStream ms2 = new MemoryStream();
MemoryStreamHelper.Write(ms2, 100);
ms2.Seek(0, SeekOrigin.Begin);
ms2.Close();
OutputHelper.WriteLine("Read from closed stream");
int readBytes = 0;
Assert.Throws(typeof(ObjectDisposedException),
() =>
{
readBytes = ms2.Read(new byte[] { 50 }, 0, 50);
},
"Expected ObjectDisposedException, but read " + readBytes + " bytes");
}
catch (Exception ex)
{
OutputHelper.WriteLine($"Unexpected exception {ex}");
}
}
[TestMethod]
public void VanillaRead()
{
try
{
using (MemoryStream ms = new MemoryStream())
{
// Write to stream then reset to beginning
MemoryStreamHelper.Write(ms, 1000);
ms.Seek(0, SeekOrigin.Begin);
OutputHelper.WriteLine("Read 256 bytes of data");
Assert.True(TestRead(ms, 256));
OutputHelper.WriteLine("Request less bytes then buffer");
Assert.True(TestRead(ms, 256, 100, 100));
// 1000 - 256 - 100 = 644
OutputHelper.WriteLine("Request more bytes then file");
Assert.True(TestRead(ms, 1000, 1000, 644));
OutputHelper.WriteLine("Request bytes after EOF");
Assert.True(TestRead(ms, 100, 100, 0));
OutputHelper.WriteLine("Rewind and read entire file in one buffer larger then file");
ms.Seek(0, SeekOrigin.Begin);
Assert.True(TestRead(ms, 1001, 1001, 1000));
OutputHelper.WriteLine("Rewind and read from middle");
ms.Position = 500;
Assert.True(TestRead(ms, 256));
OutputHelper.WriteLine("Read position after EOS");
ms.Position = ms.Length + 10;
Assert.True(TestRead(ms, 100, 100, 0));
OutputHelper.WriteLine("Verify Read validation with UTF8 string");
ms.SetLength(0);
string test = "nanoFramework Test";
ms.Write(Encoding.UTF8.GetBytes(test), 0, test.Length);
ms.Flush();
ms.Seek(0, SeekOrigin.Begin);
byte[] readbuff = new byte[20];
ms.Read(readbuff, 0, readbuff.Length);
string testResult = new string(Encoding.UTF8.GetChars(readbuff));
Assert.Equal(test, testResult, $"Exepected: {test}, but got: {testResult}");
}
}
catch (Exception ex)
{
OutputHelper.WriteLine($"Unexpected exception {ex}");
}
}
#endregion Test Cases
}
}

Просмотреть файл

@ -0,0 +1,79 @@
//
// Copyright (c) .NET Foundation and Contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
using nanoFramework.TestFramework;
using System;
using System.IO;
namespace Sytem.IO.MemoryStreamUnitTests
{
[TestClass]
public class ReadByte
{
#region Test Cases
[TestMethod]
public void InvalidCases()
{
try
{
MemoryStream ms2 = new MemoryStream();
MemoryStreamHelper.Write(ms2, 100);
ms2.Seek(0, SeekOrigin.Begin);
ms2.Close();
OutputHelper.WriteLine("Read from closed stream");
int readBytes = 0;
Assert.Throws(typeof(ObjectDisposedException),
() =>
{
readBytes = ms2.ReadByte();
},
$"Expected ObjectDisposedException, but read {readBytes} bytes");
}
catch (Exception ex)
{
OutputHelper.WriteLine($"Unexpected exception {ex}");
}
}
[TestMethod]
public void VanillaCases()
{
try
{
using (MemoryStream ms = new MemoryStream())
{
MemoryStreamHelper.Write(ms, 256);
ms.Position = 0;
OutputHelper.WriteLine("ReadBytes and verify");
for (int i = 0; i < 256; i++)
{
int b = ms.ReadByte();
Assert.Equal(b, i, $"Expected {i} but got {b}");
}
OutputHelper.WriteLine("Bytes past EOS should return -1");
int rb = ms.ReadByte();
Assert.Equal(rb, -1, $"Expected -1 but got {rb}");
}
}
catch (Exception ex)
{
OutputHelper.WriteLine($"Unexpected exception {ex}");
}
}
#endregion Test Cases
}
}

Просмотреть файл

@ -0,0 +1,200 @@
//
// Copyright (c) .NET Foundation and Contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
using nanoFramework.TestFramework;
using System;
using System.IO;
namespace Sytem.IO.MemoryStreamUnitTests
{
[TestClass]
public class Seek
{
#region Helper methods
private bool TestSeek(MemoryStream ms, long offset, SeekOrigin origin, long expectedPosition)
{
bool result = true;
long seek = ms.Seek(offset, origin);
if (seek != ms.Position && seek != expectedPosition)
{
result = false;
OutputHelper.WriteLine("Unexpected seek results!");
OutputHelper.WriteLine("Expected position: " + expectedPosition);
OutputHelper.WriteLine("Seek result: " + seek);
OutputHelper.WriteLine("fs.Position: " + ms.Position);
}
return result;
}
private bool TestExtend(MemoryStream ms, long offset, SeekOrigin origin, long expectedPosition, long expectedLength)
{
bool result = TestSeek(ms, offset, origin, expectedLength);
ms.WriteByte(1);
if (ms.Length != expectedLength)
{
result = false;
OutputHelper.WriteLine("Expected seek past end to change length to " + expectedLength + ", but its " + ms.Length);
}
return result;
}
#endregion Helper methods
#region Test Cases
[TestMethod]
public void InvalidCases()
{
MemoryStream fs = new MemoryStream();
MemoryStreamHelper.Write(fs, 1000);
long seek;
try
{
Assert.Throws(typeof(IOException),
() =>
{
OutputHelper.WriteLine("Seek -1 from Begin");
seek = fs.Seek(-1, SeekOrigin.Begin);
},
$"Expected IOException, but got position");
Assert.Throws(typeof(IOException),
() =>
{
OutputHelper.WriteLine("Seek -1001 from Current - at end from write");
seek = fs.Seek(-1001, SeekOrigin.Current);
},
"Expected IOException, but got position ");
Assert.Throws(typeof(IOException),
() =>
{
OutputHelper.WriteLine("Seek -1001 from End");
seek = fs.Seek(-1001, SeekOrigin.End);
},
"Expected IOException, but got position ");
Assert.Throws(typeof(ArgumentException),
() =>
{
OutputHelper.WriteLine("Seek invalid -1 origin");
seek = fs.Seek(1, (SeekOrigin)(-1));
},
"Expected ArgumentException, but got position");
Assert.Throws(typeof(ArgumentException),
() =>
{
OutputHelper.WriteLine("Seek invalid 10 origin");
seek = fs.Seek(1, (SeekOrigin)10);
},
"Expected ArgumentException, but got position");
Assert.Throws(typeof(ObjectDisposedException),
() =>
{
OutputHelper.WriteLine("Seek with closed stream");
fs.Close();
seek = fs.Seek(0, SeekOrigin.Begin);
},
"Expected ObjectDisposedException, but got position");
Assert.Throws(typeof(ObjectDisposedException),
() =>
{
OutputHelper.WriteLine("Seek with disposed stream");
fs.Dispose();
seek = fs.Seek(0, SeekOrigin.End);
},
"Expected ObjectDisposedException, but got position");
}
catch (Exception ex)
{
OutputHelper.WriteLine("Unexpected exception: " + ex.Message);
}
finally
{
if (fs != null)
{
fs.Dispose();
}
}
}
[TestMethod]
public void ValidCases()
{
try
{
using (MemoryStream fs = new MemoryStream())
{
MemoryStreamHelper.Write(fs, 1000);
OutputHelper.WriteLine("Seek to beginning");
Assert.True(TestSeek(fs, 0, SeekOrigin.Begin, 0));
OutputHelper.WriteLine("Seek forward offset from begging");
Assert.True(TestSeek(fs, 10, SeekOrigin.Begin, 0));
OutputHelper.WriteLine("Seek backwards offset from current");
Assert.True(TestSeek(fs, -5, SeekOrigin.Current, 5));
OutputHelper.WriteLine("Seek forwards offset from current");
Assert.True(TestSeek(fs, 20, SeekOrigin.Current, 25));
OutputHelper.WriteLine("Seek to end");
Assert.True(TestSeek(fs, 0, SeekOrigin.End, 1000));
OutputHelper.WriteLine("Seek backwards offset from end");
Assert.True(TestSeek(fs, -35, SeekOrigin.End, 965));
OutputHelper.WriteLine("Seek past end relative to End");
Assert.True(TestExtend(fs, 1, SeekOrigin.End, 1001, 1002));
OutputHelper.WriteLine("Seek past end relative to Begin");
Assert.True(TestExtend(fs, 1002, SeekOrigin.Begin, 1002, 1003));
OutputHelper.WriteLine("Seek past end relative to Current");
Assert.True(TestSeek(fs, 995, SeekOrigin.Begin, 995));
Assert.True(TestExtend(fs, 10, SeekOrigin.Current, 1005, 1006));
// 1000 --123456
// verify 011001
OutputHelper.WriteLine("Verify proper bytes written at end (zero'd bytes from seek beyond end)");
byte[] buff = new byte[6];
byte[] verify = new byte[] { 0, 1, 1, 0, 0, 1 };
fs.Seek(-6, SeekOrigin.End);
fs.Read(buff, 0, buff.Length);
for (int i = 0; i < buff.Length; i++)
{
Assert.Equal(buff[i], verify[i], $"Position {i}:{buff[i]} != {verify[i]}");
}
}
}
catch (Exception ex)
{
OutputHelper.WriteLine("Unexpected exception: " + ex.Message);
}
}
#endregion Test Cases
}
}

Просмотреть файл

@ -0,0 +1,152 @@
//
// Copyright (c) .NET Foundation and Contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
using nanoFramework.TestFramework;
using System;
using System.IO;
namespace Sytem.IO.MemoryStreamUnitTests
{
[TestClass]
public class SetLength
{
#region Helper methods
private bool TestLength(MemoryStream ms, long expectedLength)
{
if (ms.Length != expectedLength)
{
OutputHelper.WriteLine("Expected length " + expectedLength + " but got, " + ms.Length);
return false;
}
return true;
}
private bool TestPosition(MemoryStream ms, long expectedPosition)
{
if (ms.Position != expectedPosition)
{
OutputHelper.WriteLine("Expected position " + expectedPosition + " but got, " + ms.Position);
return false;
}
return true;
}
#endregion Helper methods
#region Test Cases
[TestMethod]
public void ObjectDisposed()
{
MemoryStream ms = new MemoryStream();
ms.Close();
try
{
try
{
long length = ms.Length;
OutputHelper.WriteLine("Expected ObjectDisposedException, but got length " + length);
}
catch (ObjectDisposedException) { /*Pass Case */ }
}
catch (Exception ex)
{
OutputHelper.WriteLine("Unexpected exception: " + ex.Message);
}
}
[TestMethod]
public void LengthTests()
{
try
{
using (MemoryStream ms = new MemoryStream())
{
OutputHelper.WriteLine("Set initial length to 50, and position to 50");
ms.SetLength(50);
ms.Position = 50;
Assert.True(TestLength(ms, 50));
OutputHelper.WriteLine("Write 'foo bar'");
StreamWriter sw = new StreamWriter(ms);
sw.Write("foo bar");
sw.Flush();
Assert.True(TestLength(ms, 57));
OutputHelper.WriteLine("Shorten Length to 30");
ms.SetLength(30);
Assert.True(TestLength(ms, 30));
OutputHelper.WriteLine("Verify position was adjusted");
Assert.True(TestPosition(ms, 30));
OutputHelper.WriteLine("Extend length to 100");
ms.SetLength(100);
Assert.True(TestLength(ms, 100));
}
}
catch (Exception ex)
{
OutputHelper.WriteLine("Unexpected exception: " + ex.Message);
}
}
[TestMethod]
public void InvalidSetLength()
{
try
{
using (MemoryStream ms = new MemoryStream())
{
Assert.Throws(typeof(ArgumentOutOfRangeException),
() =>
{
OutputHelper.WriteLine("-1");
ms.SetLength(-1);
},
"Expected ArgumentOutOfRangeException, but set length");
Assert.Throws(typeof(ArgumentOutOfRangeException),
() =>
{
OutputHelper.WriteLine("-10000");
ms.SetLength(-10000);
},
"Expected ArgumentOutOfRangeException, but set length");
Assert.Throws(typeof(ArgumentOutOfRangeException),
() =>
{
OutputHelper.WriteLine("long.MinValue");
ms.SetLength(long.MinValue);
},
"Expected ArgumentOutOfRangeException, but set length");
Assert.Throws(typeof(ArgumentOutOfRangeException),
() =>
{
OutputHelper.WriteLine("long.MaxValue");
ms.SetLength(long.MaxValue);
},
"Expected IOException, but set length");
}
}
catch (Exception ex)
{
OutputHelper.WriteLine("Unexpected exception: " + ex.Message);
}
}
#endregion Test Cases
}
}

Просмотреть файл

@ -0,0 +1,129 @@
//
// Copyright (c) .NET Foundation and Contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
using nanoFramework.TestFramework;
using System;
using System.IO;
namespace Sytem.IO.MemoryStreamUnitTests
{
[TestClass]
public class ToArray
{
#region Helper methods
private bool VerifyArray(byte[] data, int expected)
{
bool result = true;
OutputHelper.WriteLine("Verify Length");
if (data.Length != expected)
{
result = false;
OutputHelper.WriteLine("Expected " + expected + " bytes, but got " + data.Length);
}
OutputHelper.WriteLine("Verify pattern in array");
int nextbyte = 0;
for (int i = 0; i < data.Length; i++)
{
if (data[i] != nextbyte)
{
result = false;
OutputHelper.WriteLine("Byte in position " + i + " has wrong value: " + data[i]);
}
// Reset if wraps past 255
if (++nextbyte > 255)
{
nextbyte = 0;
}
}
return result;
}
#endregion Helper methods
#region Test Cases
[TestMethod]
public void Ctor_ToArray()
{
try
{
OutputHelper.WriteLine("Dynamic Stream");
using (MemoryStream ms = new MemoryStream())
{
byte[] stream = ms.ToArray();
Assert.Equal(stream.Length, 0, $"Expected length 0, but got length {stream.Length}");
}
OutputHelper.WriteLine("Static Stream");
using (MemoryStream ms = new MemoryStream(new byte[512]))
{
byte[] stream = ms.ToArray();
Assert.Equal(stream.Length, 512, $"Expected length 512, but got length {stream.Length}");
}
}
catch (Exception ex)
{
OutputHelper.WriteLine($"Unexpected exception {ex}");
}
}
[TestMethod]
public void VerifyValues()
{
try
{
OutputHelper.WriteLine("Verify Data");
using (MemoryStream ms = new MemoryStream())
{
OutputHelper.WriteLine("Write 1000 bytes in specific pattern");
MemoryStreamHelper.Write(ms, 1000);
byte[] stream = ms.ToArray();
Assert.True(VerifyArray(stream, 1000));
}
}
catch (Exception ex)
{
OutputHelper.WriteLine($"Unexpected exception {ex}");
}
}
[TestMethod]
public void ChangeLengths()
{
try
{
OutputHelper.WriteLine("Verify array is still valid after truncation (copy array)");
using (MemoryStream ms = new MemoryStream())
{
MemoryStreamHelper.Write(ms, 1000);
ms.SetLength(200);
ms.Flush();
byte[] stream = ms.ToArray();
Assert.True(VerifyArray(stream, 200));
}
}
catch (Exception ex)
{
OutputHelper.WriteLine($"Unexpected exception {ex}");
}
}
#endregion Test Cases
}
}

Просмотреть файл

@ -0,0 +1,390 @@
//
// Copyright (c) .NET Foundation and Contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
using nanoFramework.TestFramework;
using System;
using System.IO;
using System.Text;
namespace Sytem.IO.MemoryStreamUnitTests
{
[TestClass]
public class Write
{
#region Local Helper methods
private bool TestWrite(MemoryStream ms, int length)
{
return TestWrite(ms, length, length, 0);
}
private bool TestWrite(MemoryStream ms, int length, long ExpectedLength)
{
return TestWrite(ms, length, length, 0, ExpectedLength);
}
private bool TestWrite(MemoryStream ms, int BufferLength, int BytesToWrite, int Offset)
{
return TestWrite(ms, BufferLength, BytesToWrite, Offset, ms.Position + BytesToWrite);
}
private bool TestWrite(MemoryStream ms, int BufferLength, int BytesToWrite, int Offset, long ExpectedLength)
{
bool result = true;
long startLength = ms.Position;
long nextbyte = startLength % 256;
byte[] byteBuffer = new byte[BufferLength];
for (int i = Offset; i < (Offset + BytesToWrite); i++)
{
byteBuffer[i] = (byte)nextbyte;
// Reset if wraps past 255
if (++nextbyte > 255)
{
nextbyte = 0;
}
}
ms.Write(byteBuffer, Offset, BytesToWrite);
ms.Flush();
if (ExpectedLength < ms.Length)
{
result = false;
OutputHelper.WriteLine($"Expected final length of {ExpectedLength} bytes, but got {ms.Length} bytes");
}
return result;
}
#endregion Local Helper methods
#region Test Cases
[TestMethod]
public void InvalidCases()
{
MemoryStream fs = new MemoryStream();
byte[] writebuff = new byte[1024];
try
{
Assert.Throws(typeof(ArgumentNullException),
() =>
{
OutputHelper.WriteLine("Write to null buffer");
fs.Write(null, 0, writebuff.Length);
},
"Expected ArgumentNullException"
);
Assert.Throws(typeof(ArgumentOutOfRangeException),
() =>
{
OutputHelper.WriteLine("Write to negative offset");
fs.Write(writebuff, -1, writebuff.Length);
}
, "Expected ArgumentOutOfRangeException"
);
Assert.Throws(typeof(ArgumentException),
() =>
{
OutputHelper.WriteLine("Write to out of range offset");
fs.Write(writebuff, writebuff.Length + 1, writebuff.Length);
}
,
"Expected ArgumentException"
);
Assert.Throws(typeof(ArgumentOutOfRangeException),
() =>
{
OutputHelper.WriteLine("Write negative count");
fs.Write(writebuff, 0, -1);
}
,
"Expected ArgumentOutOfRangeException");
Assert.Throws(typeof(ArgumentException),
() =>
{
OutputHelper.WriteLine("Write count larger then buffer");
fs.Write(writebuff, 0, writebuff.Length + 1);
}
,
"Expected ArgumentException");
Assert.Throws(typeof(ObjectDisposedException),
() =>
{
OutputHelper.WriteLine("Write closed stream");
fs.Close();
fs.Write(writebuff, 0, writebuff.Length);
}
,
"Expected ObjectDisposedException");
Assert.Throws(typeof(ObjectDisposedException),
() =>
{
OutputHelper.WriteLine("Write disposed stream");
fs = new MemoryStream();
fs.Dispose();
fs.Write(writebuff, 0, writebuff.Length);
}
,
"Expected ObjectDisposedException");
}
catch (Exception ex)
{
OutputHelper.WriteLine("Unexpected exception: " + ex.Message);
}
finally
{
if (fs != null)
{
fs.Dispose();
}
}
}
[TestMethod]
public void VanillaWrite_Dynamic_Ctor()
{
try
{
using (MemoryStream ms = new MemoryStream())
{
OutputHelper.WriteLine("Write 256 bytes of data");
Assert.True(TestWrite(ms, 256));
OutputHelper.WriteLine("Write middle of buffer");
Assert.True(TestWrite(ms, 256, 100, 100));
// 1000 - 256 - 100 = 644
OutputHelper.WriteLine("Write start of buffer");
Assert.True(TestWrite(ms, 1000, 644, 0));
OutputHelper.WriteLine("Write end of buffer");
Assert.True(TestWrite(ms, 1000, 900, 100));
OutputHelper.WriteLine("Rewind and verify all bytes written");
ms.Seek(0, SeekOrigin.Begin);
Assert.True(MemoryStreamHelper.VerifyRead(ms));
OutputHelper.WriteLine("Verify Read validation with UTF8 string");
ms.SetLength(0);
string test = "MFFramework Test";
ms.Write(Encoding.UTF8.GetBytes(test), 0, test.Length);
ms.Flush();
ms.Seek(0, SeekOrigin.Begin);
byte[] readbuff = new byte[20];
ms.Read(readbuff, 0, readbuff.Length);
string testResult = new string(Encoding.UTF8.GetChars(readbuff));
Assert.Equal(test, testResult, $"Exepected: {test}, but got: {testResult}");
}
}
catch (Exception ex)
{
OutputHelper.WriteLine("Unexpected exception: " + ex.Message);
}
}
[TestMethod]
public void VanillaWrite_Static_Ctor()
{
try
{
byte[] buffer = new byte[1024];
using (MemoryStream ms = new MemoryStream(buffer))
{
OutputHelper.WriteLine("Write 256 bytes of data");
Assert.True(TestWrite(ms, 256, 1024));
OutputHelper.WriteLine("Write middle of buffer");
Assert.True(TestWrite(ms, 256, 100, 100, 1024));
// 1000 - 256 - 100 = 644
OutputHelper.WriteLine("Write start of buffer");
Assert.True(TestWrite(ms, 1000, 644, 0, 1024));
OutputHelper.WriteLine("Write past end of buffer");
Assert.Throws(typeof(NotSupportedException),
() =>
{
TestWrite(ms, 50, 1024);
},
"Expected NotSupportedException");
OutputHelper.WriteLine("Verify failed Write did not move position");
Assert.Equal(ms.Position, 1000, $"Expected position to be 1000, but it is {ms.Position}");
OutputHelper.WriteLine("Write final 24 bytes of static buffer");
Assert.True(TestWrite(ms, 24));
OutputHelper.WriteLine("Rewind and verify all bytes written");
ms.Seek(0, SeekOrigin.Begin);
Assert.True(MemoryStreamHelper.VerifyRead(ms));
OutputHelper.WriteLine("Verify Read validation with UTF8 string");
ms.SetLength(0);
string test = "nanoFramework Test";
ms.Write(Encoding.UTF8.GetBytes(test), 0, test.Length);
ms.Flush();
ms.Seek(0, SeekOrigin.Begin);
byte[] readbuff = new byte[20];
ms.Read(readbuff, 0, readbuff.Length);
string testResult = new string(Encoding.UTF8.GetChars(readbuff));
Assert.Equal(test, testResult, $"Exepected: {test}, but got: {testResult}");
}
}
catch (Exception ex)
{
OutputHelper.WriteLine("Unexpected exception: " + ex.Message);
}
}
[TestMethod]
public void ShiftBuffer()
{
try
{
int bufSize;
for (int i = 1; i < 10; i++)
{
bufSize = i;
MemoryStream ms = new MemoryStream();
for (int j = 0; j < bufSize; ++j)
{
ms.WriteByte((byte)j);
}
// Move everything forward by 1 byte
ms.Seek(0, SeekOrigin.Begin);
byte[] buf = ms.ToArray();
ms.Write(buf, 1, bufSize - 1);
ms.Seek(0, SeekOrigin.Begin);
//we'll read till one before the last since these should be shifted by 1
for (int j = 0; j < ms.Length - 1; ++j)
{
int bit = ms.ReadByte();
Assert.Equal(bit, j + 1, $"Err_8324t! Check #458551, Returned: {bit}, Expected: {j + 1}");
}
//last bit should be the same
Assert.Equal(ms.ReadByte(), i - 1, "Err_32947gs! Last bit is not correct Check VSWhdibey #458551");
}
//Buffer sizes of 9 (10 here since we shift by 1) and above doesn't have the above 'optimization' problem
for (int i = 10; i < 64; i++)
{
bufSize = i;
MemoryStream ms = new MemoryStream();
for (int j = 0; j < bufSize; ++j)
{
ms.WriteByte((byte)j);
}
// Move everything forward by 1 byte
ms.Seek(0, SeekOrigin.Begin);
byte[] buf = ms.ToArray();
ms.Write(buf, 1, bufSize - 1);
ms.Seek(0, SeekOrigin.Begin);
for (int j = 0; j < ms.Length; ++j)
{
int bit = ms.ReadByte();
if (j != ms.Length - 1)
{
Assert.Equal(bit, j + 1, $"Err_235radg_{i}! Check VSWhdibey #458551, Returned: {bit}, Expected: {j + 1}");
}
else
{
Assert.Equal(bit, j, $"Err_235radg_{i}! Check VSWhdibey #458551, Returned: {bit}, Expected:{j + 1}");
}
}
}
}
catch (Exception ex)
{
OutputHelper.WriteLine("Unexpected exception: " + ex.Message);
}
}
[TestMethod]
public void BoundaryCheck()
{
try
{
for (int i = 250; i < 260; i++)
{
using (MemoryStream ms = new MemoryStream())
{
TestWrite(ms, i);
ms.Position = 0;
Assert.True(MemoryStreamHelper.VerifyRead(ms));
OutputHelper.WriteLine("Position: " + ms.Position);
OutputHelper.WriteLine("Length: " + ms.Length);
Assert.True(
(i != ms.Position | i != ms.Length),
$"Expected Position and Length to be {i}");
}
}
}
catch (Exception ex)
{
OutputHelper.WriteLine("Unexpected exception: " + ex.Message);
}
}
#endregion Test Cases
}
}

Просмотреть файл

@ -0,0 +1,204 @@
//
// Copyright (c) .NET Foundation and Contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
using nanoFramework.TestFramework;
using System;
using System.IO;
namespace Sytem.IO.MemoryStreamUnitTests
{
[TestClass]
public class WriteByte
{
#region Helper methods
private bool TestWrite(MemoryStream ms, int BytesToWrite)
{
return TestWrite(ms, BytesToWrite, ms.Position + BytesToWrite);
}
private bool TestWrite(MemoryStream ms, int BytesToWrite, long ExpectedLength)
{
bool result = true;
long startLength = ms.Position;
long nextbyte = startLength % 256;
for (int i = 0; i < BytesToWrite; i++)
{
ms.WriteByte((byte)nextbyte);
// Reset if wraps past 255
if (++nextbyte > 255)
nextbyte = 0;
}
ms.Flush();
if (ExpectedLength < ms.Length)
{
result = false;
OutputHelper.WriteLine($"Expected final length of {ExpectedLength} bytes, but got {ms.Length} bytes");
}
return result;
}
#endregion Helper methods
#region Test Cases
[TestMethod]
public void ExtendBuffer()
{
try
{
using (MemoryStream ms = new MemoryStream())
{
OutputHelper.WriteLine("Set Position past end of stream");
// Internal buffer is initialized to 256, if this changes, this test is no longer valid.
// Exposing capcity would have made this test easier/dynamic.
ms.Position = 300;
ms.WriteByte(123);
Assert.Equal(ms.Length, 301, $"Expected length 301, got length {ms.Length}");
ms.Position = 300;
int read = ms.ReadByte();
Assert.Equal(read, 123, $"Expected value 123, but got value {read}");
}
}
catch (Exception ex)
{
OutputHelper.WriteLine($"Unexpected exception {ex}");
}
}
[TestMethod]
public void InvalidRange()
{
try
{
byte[] buffer = new byte[100];
using (MemoryStream ms = new MemoryStream(buffer))
{
OutputHelper.WriteLine("Set Position past end of static stream");
ms.Position = buffer.Length + 1;
Assert.Throws(typeof(NotSupportedException),
() =>
{
ms.WriteByte(1);
},
"Expected NotSupportedException");
}
}
catch (Exception ex)
{
OutputHelper.WriteLine($"Unexpected exception {ex}");
}
}
[TestMethod]
public void VanillaWrite()
{
try
{
OutputHelper.WriteLine("Static Buffer");
byte[] buffer = new byte[100];
using (MemoryStream ms = new MemoryStream(buffer))
{
OutputHelper.WriteLine("Write 50 bytes of data");
Assert.True(TestWrite(ms, 50, 100));
OutputHelper.WriteLine("Write final 50 bytes of data");
Assert.True(TestWrite(ms, 50, 100));
OutputHelper.WriteLine("Any more bytes written should throw");
Assert.Throws(typeof(NotSupportedException),
() =>
{
ms.WriteByte(50);
},
"Expected NotSupportedException");
OutputHelper.WriteLine("Rewind and verify all bytes written");
ms.Seek(0, SeekOrigin.Begin);
Assert.True(MemoryStreamHelper.VerifyRead(ms));
}
OutputHelper.WriteLine("Dynamic Buffer");
using (MemoryStream ms = new MemoryStream())
{
OutputHelper.WriteLine("Write 100 bytes of data");
Assert.True(TestWrite(ms, 100));
OutputHelper.WriteLine("Extend internal buffer, write 160");
Assert.True(TestWrite(ms, 160));
OutputHelper.WriteLine("Double extend internal buffer, write 644");
Assert.True(TestWrite(ms, 644));
OutputHelper.WriteLine("write another 1100");
Assert.True(TestWrite(ms, 1100));
OutputHelper.WriteLine("Rewind and verify all bytes written");
ms.Seek(0, SeekOrigin.Begin);
Assert.True(MemoryStreamHelper.VerifyRead(ms));
}
}
catch (Exception ex)
{
OutputHelper.WriteLine($"Unexpected exception {ex}");
}
}
[TestMethod]
public void BoundaryCheck()
{
try
{
for (int i = 250; i < 260; i++)
{
using (MemoryStream ms = new MemoryStream())
{
MemoryStreamHelper.Write(ms, i);
ms.Position = 0;
Assert.True(MemoryStreamHelper.VerifyRead(ms));
OutputHelper.WriteLine("Position: " + ms.Position);
OutputHelper.WriteLine("Length: " + ms.Length);
Assert.True(
(i != ms.Position | i != ms.Length),
$"Expected Position and Length to be {i}");
}
}
}
catch (Exception ex)
{
OutputHelper.WriteLine("Unexpected exception: " + ex.Message);
}
}
#endregion Test Cases
}
}

Просмотреть файл

@ -0,0 +1,106 @@
//
// Copyright (c) .NET Foundation and Contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
using nanoFramework.TestFramework;
using System;
using System.IO;
namespace Sytem.IO.MemoryStreamUnitTests
{
[TestClass]
public class WriteTo
{
#region Test Cases
[TestMethod]
public void InvalidArgs()
{
try
{
using (MemoryStream ms = new MemoryStream())
{
OutputHelper.WriteLine("Initialize stream");
MemoryStreamHelper.Write(ms, 1000);
Assert.Throws(typeof(ArgumentNullException), () =>
{
OutputHelper.WriteLine("null stream");
ms.WriteTo(null);
},
"Expected ArgumentNullException"
);
Assert.Throws(typeof(ObjectDisposedException),
() =>
{
OutputHelper.WriteLine("Target Stream closed");
MemoryStream mst = new MemoryStream();
mst.Close();
ms.WriteTo(mst);
},
"Expected ObjectDisposedException"
);
OutputHelper.WriteLine("Current Stream closed");
ms.Close();
Assert.Throws(typeof(ObjectDisposedException),
() =>
{
using (MemoryStream mst = new MemoryStream())
{
ms.WriteTo(mst);
OutputHelper.WriteLine("Expected ObjectDisposedException");
}
},
"Expected ObjectDisposedException");
}
}
catch (Exception ex)
{
OutputHelper.WriteLine($"Unexpected exception {ex}");
}
}
[TestMethod]
public void WriteTo_MemoryStream()
{
try
{
using (MemoryStream ms = new MemoryStream())
{
OutputHelper.WriteLine("Initialize stream with 1234 bytes");
MemoryStreamHelper.Write(ms, 1234);
using (MemoryStream ms2 = new MemoryStream())
{
OutputHelper.WriteLine("WriteTo MemoryStream");
ms.WriteTo(ms2);
OutputHelper.WriteLine("Verify 2nd MemoryStream");
Assert.Equal(ms2.Length, 1234, $"Expected 1234 bytes, but got: {ms2.Length}");
ms2.Position = 0;
Assert.True(MemoryStreamHelper.VerifyRead(ms2));
}
}
}
catch (Exception ex)
{
OutputHelper.WriteLine($"Unexpected exception {ex}");
}
}
#endregion Test Cases
}
}

Просмотреть файл

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="utf-8"?>
<RunSettings>
<!-- Configurations that affect the Test Framework -->
<RunConfiguration>
<MaxCpuCount>1</MaxCpuCount>
<ResultsDirectory>.\TestResults</ResultsDirectory><!-- Path relative to solution directory -->
<TestSessionTimeout>120000</TestSessionTimeout><!-- Milliseconds -->
<TargetFrameworkVersion>Framework40</TargetFrameworkVersion>
</RunConfiguration>
<nanoFrameworkAdapter>
<Logging>None</Logging>
<IsRealHardware>False</IsRealHardware>
</nanoFrameworkAdapter>
</RunSettings>

Просмотреть файл

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="nanoFramework.CoreLibrary" version="1.12.0-preview.5" targetFramework="netnanoframework10" />
<package id="nanoFramework.System.Text" version="1.1.3-preview.13" targetFramework="netnanoframework10" />
<package id="nanoFramework.TestFramework" version="1.0.175" targetFramework="netnanoframework10" developmentDependency="true" />
</packages>

Двоичные данные
assets/nf-logo.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 9.0 KiB

21
assets/readme.txt Normal file
Просмотреть файл

@ -0,0 +1,21 @@
_____ _
_ __ __ _ _ __ ___ | ___| __ __ _ _ __ ___ _____ _____ _ __| | __
| '_ \ / _` | '_ \ / _ \| |_ | '__/ _` | '_ ` _ \ / _ \ \ /\ / / _ \| '__| |/ /
| | | | (_| | | | | (_) | _|| | | (_| | | | | | | __/\ V V / (_) | | | <
|_| |_|\__,_|_| |_|\___/|_| |_| \__,_|_| |_| |_|\___| \_/\_/ \___/|_| |_|\_\
===================================================================================
API docs: https://docs.nanoframework.net/api/System.IO.Ports
Browse our samples repository: https://github.com/nanoframework/System.IO.Ports
Check our documentation online: https://docs.nanoframework.net
Join our lively Discord community: https://discord.gg/gCyBu8T
Report issues: https://github.com/nanoframework/Home/issues
Follow us on Twitter: https://twitter.com/nanoframework
Follow our YouTube channel: https://www.youtube.com/c/nanoFramework

64
azure-pipelines.yml Normal file
Просмотреть файл

@ -0,0 +1,64 @@
# Copyright (c) .NET Foundation and Contributors
# See LICENSE file in the project root for full license information.
trigger:
branches:
include:
- main
- develop
- release-*
paths:
exclude:
- .github_changelog_generator
- .gitignore
- CHANGELOG.md
- CODE_OF_CONDUCT.md
- LICENSE.md
- README.md
- NuGet.Config
- assets/*
- config/*
- .github/*
tags:
include:
- v*
# PR always trigger build
pr:
autoCancel: true
# add nf-tools repo to resources (for Azure Pipelines templates)
resources:
repositories:
- repository: templates
type: github
name: nanoframework/nf-tools
endpoint: nanoframework
pool:
vmImage: 'windows-latest'
variables:
DOTNET_NOLOGO: true
solution: 'nanoFramework.System.IO.Streams.sln'
buildPlatform: 'Any CPU'
buildConfiguration: 'Release'
nugetPackageName: 'nanoFramework.System.IO.Streams'
steps:
# step from template @ nf-tools repo
# all build, update and publish steps
- template: azure-pipelines-templates/class-lib-build.yml@templates
parameters:
sonarCloudProject: 'nanoframework_System.IO.Streams'
runUnitTests: true
unitTestRunsettings: '$(System.DefaultWorkingDirectory)\UnitTests\MemoryStreamUnitTests\nano.runsettings'
# step from template @ nf-tools repo
# report error
- template: azure-pipelines-templates/discord-webhook-task.yml@templates
parameters:
status: 'failure'
webhookUrl: '$(DiscordWebhook)'
message: ''

14
config/SignClient.json Normal file
Просмотреть файл

@ -0,0 +1,14 @@
{
"SignClient": {
"AzureAd": {
"AADInstance": "https://login.microsoftonline.com/",
"ClientId": "c248d68a-ba6f-4aa9-8a68-71fe872063f8",
"TenantId": "16076fdc-fcc1-4a15-b1ca-32c9a255900e"
},
"Service": {
"Url": "https://codesign.dotnetfoundation.org/",
"ResourceId": "https://SignService/3c30251f-36f3-490b-a955-520addb85001"
}
}
}

1
config/filelist.txt Normal file
Просмотреть файл

@ -0,0 +1 @@
**/System.IO.Streams

Просмотреть файл

@ -0,0 +1,36 @@
<?xml version="1.0" encoding="utf-8"?>
<package xmlns="http://schemas.microsoft.com/packaging/2012/06/nuspec.xsd">
<metadata>
<id>nanoFramework.System.IO.Streams</id>
<version>$version$</version>
<title>nanoFramework.System.IO.Streams</title>
<authors>nanoframework</authors>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
<license type="file">LICENSE.md</license>
<releaseNotes>
</releaseNotes>
<readme>docs\README.md</readme>
<developmentDependency>false</developmentDependency>
<projectUrl>https://github.com/nanoframework/System.IO.Streams</projectUrl>
<icon>images\nf-logo.png</icon>
<repository type="git" url="https://github.com/nanoframework/System.IO.Streams" commit="$commit$" />
<copyright>Copyright (c) .NET Foundation and Contributors</copyright>
<description>This package includes the System.IO.Streams assembly for .NET nanoFramework C# projects.</description>
<tags>nanoFramework C# csharp netmf netnf </tags>
<dependencies>
<dependency id="nanoFramework.CoreLibrary" version="1.12.0-preview.5" />
<dependency id="nanoFramework.System.Text" version="1.1.3-preview.13" />
</dependencies>
</metadata>
<files>
<file src="System.IO.Streams\bin\Release\System.IO.Streams.dll" target="lib\System.IO.Streams.dll" />
<file src="System.IO.Streams\bin\Release\System.IO.Streams.pdb" target="lib\System.IO.Streams.pdb" />
<file src="System.IO.Streams\bin\Release\System.IO.Streams.pdbx" target="lib\System.IO.Streams.pdbx" />
<file src="System.IO.Streams\bin\Release\System.IO.Streams.pe" target="lib\System.IO.Streams.pe" />
<file src="System.IO.Streams\bin\Release\System.IO.Streams.xml" target="lib\System.IO.Streams.xml" />
<file src="assets\readme.txt" target="" />
<file src="README.md" target="docs\" />
<file src="assets\nf-logo.png" target="images" />
<file src="LICENSE.md" target="" />
</files>
</package>

Просмотреть файл

@ -0,0 +1,47 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.0.32112.339
MinimumVisualStudioVersion = 10.0.40219.1
Project("{11A8DD76-328B-46DF-9F39-F559912D0360}") = "System.IO.Streams", "System.IO.Streams\System.IO.Streams.nfproj", "{213D1B2E-23E6-4E3E-A5DE-AB993A1B6175}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "UnitTests", "UnitTests", "{98AC1D27-BE89-4980-82F1-474339A259E3}"
EndProject
Project("{11A8DD76-328B-46DF-9F39-F559912D0360}") = "MemoryStreamUnitTests", "UnitTests\MemoryStreamUnitTests\MemoryStreamUnitTests.nfproj", "{ACFDACA6-8C62-412D-B0B9-3059601A3D9C}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{DAA42459-BABD-422B-9EAB-D98EECCFDDF4}"
ProjectSection(SolutionItems) = preProject
nanoFramework.System.IO.Streams.nuspec = nanoFramework.System.IO.Streams.nuspec
NuGet.Config = NuGet.Config
version.json = version.json
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{213D1B2E-23E6-4E3E-A5DE-AB993A1B6175}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{213D1B2E-23E6-4E3E-A5DE-AB993A1B6175}.Debug|Any CPU.Build.0 = Debug|Any CPU
{213D1B2E-23E6-4E3E-A5DE-AB993A1B6175}.Debug|Any CPU.Deploy.0 = Debug|Any CPU
{213D1B2E-23E6-4E3E-A5DE-AB993A1B6175}.Release|Any CPU.ActiveCfg = Release|Any CPU
{213D1B2E-23E6-4E3E-A5DE-AB993A1B6175}.Release|Any CPU.Build.0 = Release|Any CPU
{213D1B2E-23E6-4E3E-A5DE-AB993A1B6175}.Release|Any CPU.Deploy.0 = Release|Any CPU
{ACFDACA6-8C62-412D-B0B9-3059601A3D9C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{ACFDACA6-8C62-412D-B0B9-3059601A3D9C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{ACFDACA6-8C62-412D-B0B9-3059601A3D9C}.Debug|Any CPU.Deploy.0 = Debug|Any CPU
{ACFDACA6-8C62-412D-B0B9-3059601A3D9C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{ACFDACA6-8C62-412D-B0B9-3059601A3D9C}.Release|Any CPU.Build.0 = Release|Any CPU
{ACFDACA6-8C62-412D-B0B9-3059601A3D9C}.Release|Any CPU.Deploy.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{ACFDACA6-8C62-412D-B0B9-3059601A3D9C} = {98AC1D27-BE89-4980-82F1-474339A259E3}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {AFF41EE6-F960-49D7-94D4-F87BEC8E2F77}
EndGlobalSection
EndGlobal

74
template.vssettings Normal file
Просмотреть файл

@ -0,0 +1,74 @@
<UserSettings>
<ApplicationIdentity version="12.0"/>
<ToolsOptions>
<ToolsOptionsCategory name="TextEditor" RegisteredName="TextEditor">
<ToolsOptionsSubCategory name="AllLanguages" RegisteredName="AllLanguages" PackageName="Text Management Package"/>
<ToolsOptionsSubCategory name="CSharp" RegisteredName="CSharp" PackageName="Text Management Package">
<PropertyValue name="TabSize">4</PropertyValue>
<PropertyValue name="InsertTabs">false</PropertyValue>
<PropertyValue name="IndentSize">4</PropertyValue>
<PropertyValue name="BraceCompletion">true</PropertyValue>
</ToolsOptionsSubCategory>
<ToolsOptionsSubCategory name="CSharp-Specific" RegisteredName="CSharp-Specific" PackageName="Visual C# Language Service Package">
<PropertyValue name="NewLines_QueryExpression_EachClause">1</PropertyValue>
<PropertyValue name="Space_Normalize">0</PropertyValue>
<PropertyValue name="Space_AroundBinaryOperator">1</PropertyValue>
<PropertyValue name="Formatting_TriggerOnPaste">1</PropertyValue>
<PropertyValue name="NewLines_Braces_Method">1</PropertyValue>
<PropertyValue name="Indent_CaseLabels">1</PropertyValue>
<PropertyValue name="Formatting_TriggerOnBlockCompletion">1</PropertyValue>
<PropertyValue name="CodeDefinitionWindow_DocumentationComment_IndentOffset">2</PropertyValue>
<PropertyValue name="NewLines_Braces_ControlFlow">1</PropertyValue>
<PropertyValue name="NewLines_Braces_AnonymousMethod">0</PropertyValue>
<PropertyValue name="Space_WithinOtherParentheses">0</PropertyValue>
<PropertyValue name="Wrapping_KeepStatementsOnSingleLine">1</PropertyValue>
<PropertyValue name="Space_AfterBasesColon">1</PropertyValue>
<PropertyValue name="Indent_Braces">0</PropertyValue>
<PropertyValue name="Wrapping_IgnoreSpacesAroundVariableDeclaration">0</PropertyValue>
<PropertyValue name="Space_WithinMethodCallParentheses">0</PropertyValue>
<PropertyValue name="Space_AfterCast">0</PropertyValue>
<PropertyValue name="NewLines_Braces_CollectionInitializer">0</PropertyValue>
<PropertyValue name="NewLines_AnonymousTypeInitializer_EachMember">1</PropertyValue>
<PropertyValue name="NewLines_Keywords_Catch">1</PropertyValue>
<PropertyValue name="NewLines_Braces_ObjectInitializer">0</PropertyValue>
<PropertyValue name="NewLines_Braces_ArrayInitializer">0</PropertyValue>
<PropertyValue name="Space_WithinExpressionParentheses">0</PropertyValue>
<PropertyValue name="Space_InControlFlowConstruct">1</PropertyValue>
<PropertyValue name="Formatting_TriggerOnStatementCompletion">0</PropertyValue>
<PropertyValue name="NewLines_Keywords_Finally">1</PropertyValue>
<PropertyValue name="Space_BetweenEmptyMethodDeclarationParentheses">0</PropertyValue>
<PropertyValue name="Indent_UnindentLabels">0</PropertyValue>
<PropertyValue name="NewLines_ObjectInitializer_EachMember">1</PropertyValue>
<PropertyValue name="NewLines_Keywords_Else">1</PropertyValue>
<PropertyValue name="Space_WithinMethodDeclarationParentheses">0</PropertyValue>
<PropertyValue name="Space_BetweenEmptyMethodCallParentheses">0</PropertyValue>
<PropertyValue name="Space_BeforeSemicolonsInForStatement">0</PropertyValue>
<PropertyValue name="Space_BeforeComma">0</PropertyValue>
<PropertyValue name="Space_AfterMethodCallName">0</PropertyValue>
<PropertyValue name="Space_AfterComma">1</PropertyValue>
<PropertyValue name="Wrapping_IgnoreSpacesAroundBinaryOperators">0</PropertyValue>
<PropertyValue name="Space_BeforeBasesColon">1</PropertyValue>
<PropertyValue name="Space_AfterMethodDeclarationName">0</PropertyValue>
<PropertyValue name="Space_AfterDot">0</PropertyValue>
<PropertyValue name="NewLines_Braces_Type">1</PropertyValue>
<PropertyValue name="Space_AfterLambdaArrow">1</PropertyValue>
<PropertyValue name="NewLines_Braces_LambdaExpressionBody">0</PropertyValue>
<PropertyValue name="Space_WithinSquares">0</PropertyValue>
<PropertyValue name="Space_BeforeLambdaArrow">1</PropertyValue>
<PropertyValue name="NewLines_Braces_AnonymousTypeInitializer">0</PropertyValue>
<PropertyValue name="Space_WithinCastParentheses">0</PropertyValue>
<PropertyValue name="Space_AfterSemicolonsInForStatement">1</PropertyValue>
<PropertyValue name="Indent_CaseContents">0</PropertyValue>
<PropertyValue name="Indent_FlushLabelsLeft">1</PropertyValue>
<PropertyValue name="Wrapping_PreserveSingleLine">1</PropertyValue>
<PropertyValue name="Space_BetweenEmptySquares">0</PropertyValue>
<PropertyValue name="Space_BeforeOpenSquare">0</PropertyValue>
<PropertyValue name="Space_BeforeDot">0</PropertyValue>
<PropertyValue name="Indent_BlockContents">1</PropertyValue>
<PropertyValue name="SortUsings_PlaceSystemFirst">1</PropertyValue>
<PropertyValue name="SortUsings">1</PropertyValue>
<PropertyValue name="RemoveUnusedUsings">1</PropertyValue>
</ToolsOptionsSubCategory>
</ToolsOptionsCategory>
</ToolsOptions>
</UserSettings>

24
version.json Normal file
Просмотреть файл

@ -0,0 +1,24 @@
{
"$schema": "https://raw.githubusercontent.com/dotnet/Nerdbank.GitVersioning/master/src/NerdBank.GitVersioning/version.schema.json",
"version": "1.0.0-preview.{height}",
"assemblyVersion": {
"precision": "revision"
},
"semVer1NumericIdentifierPadding": 3,
"nuGetPackageVersion": {
"semVer": 2.0
},
"publicReleaseRefSpec": [
"^refs/heads/develop$",
"^refs/heads/main$",
"^refs/heads/v\\d+(?:\\.\\d+)?$"
],
"cloudBuild": {
"setAllVariables": true
},
"release": {
"branchName": "release-v{version}",
"versionIncrement": "build",
"firstUnstableTag": "preview"
}
}