summaryrefslogtreecommitdiff
path: root/src/mscorlib/src/System/IO
diff options
context:
space:
mode:
authorJiyoung Yun <jy910.yun@samsung.com>2017-04-13 05:17:19 (GMT)
committerJiyoung Yun <jy910.yun@samsung.com>2017-04-13 05:17:19 (GMT)
commita56e30c8d33048216567753d9d3fefc2152af8ac (patch)
tree7e5d979695fc4a431740982eb1cfecc2898b23a5 /src/mscorlib/src/System/IO
parent4b11dc566a5bbfa1378d6266525c281b028abcc8 (diff)
downloadcoreclr-a56e30c8d33048216567753d9d3fefc2152af8ac.zip
coreclr-a56e30c8d33048216567753d9d3fefc2152af8ac.tar.gz
coreclr-a56e30c8d33048216567753d9d3fefc2152af8ac.tar.bz2
Imported Upstream version 2.0.0.11353upstream/2.0.0.11353
Diffstat (limited to 'src/mscorlib/src/System/IO')
-rw-r--r--src/mscorlib/src/System/IO/BinaryReader.cs347
-rw-r--r--src/mscorlib/src/System/IO/BinaryWriter.cs211
-rw-r--r--src/mscorlib/src/System/IO/Directory.cs28
-rw-r--r--src/mscorlib/src/System/IO/DirectoryNotFoundException.cs45
-rw-r--r--src/mscorlib/src/System/IO/DriveNotFoundException.cs29
-rw-r--r--src/mscorlib/src/System/IO/EndOfStreamException.cs42
-rw-r--r--src/mscorlib/src/System/IO/File.cs81
-rw-r--r--src/mscorlib/src/System/IO/FileAccess.cs41
-rw-r--r--src/mscorlib/src/System/IO/FileLoadException.CoreCLR.cs43
-rw-r--r--src/mscorlib/src/System/IO/FileLoadException.cs175
-rw-r--r--src/mscorlib/src/System/IO/FileMode.cs53
-rw-r--r--src/mscorlib/src/System/IO/FileNotFoundException.CoreCLR.cs20
-rw-r--r--src/mscorlib/src/System/IO/FileNotFoundException.cs157
-rw-r--r--src/mscorlib/src/System/IO/FileOptions.cs46
-rw-r--r--src/mscorlib/src/System/IO/FileShare.cs59
-rw-r--r--src/mscorlib/src/System/IO/IOException.cs46
-rw-r--r--src/mscorlib/src/System/IO/MemoryStream.cs393
-rw-r--r--src/mscorlib/src/System/IO/PathTooLongException.cs43
-rw-r--r--src/mscorlib/src/System/IO/PinnedBufferMemoryStream.cs17
-rw-r--r--src/mscorlib/src/System/IO/SearchOption.cs5
-rw-r--r--src/mscorlib/src/System/IO/SeekOrigin.cs31
-rw-r--r--src/mscorlib/src/System/IO/Stream.cs355
-rw-r--r--src/mscorlib/src/System/IO/StreamHelpers.CopyValidation.cs46
-rw-r--r--src/mscorlib/src/System/IO/StreamReader.cs249
-rw-r--r--src/mscorlib/src/System/IO/TextReader.cs32
-rw-r--r--src/mscorlib/src/System/IO/UnmanagedMemoryAccessor.cs1132
-rw-r--r--src/mscorlib/src/System/IO/UnmanagedMemoryStream.cs481
-rw-r--r--src/mscorlib/src/System/IO/UnmanagedMemoryStreamWrapper.cs153
-rw-r--r--src/mscorlib/src/System/IO/__Error.cs196
-rw-r--r--src/mscorlib/src/System/IO/__HResults.cs7
30 files changed, 2018 insertions, 2545 deletions
diff --git a/src/mscorlib/src/System/IO/BinaryReader.cs b/src/mscorlib/src/System/IO/BinaryReader.cs
index d973860..54358d6 100644
--- a/src/mscorlib/src/System/IO/BinaryReader.cs
+++ b/src/mscorlib/src/System/IO/BinaryReader.cs
@@ -13,54 +13,60 @@
**
**
============================================================*/
-namespace System.IO {
- using System;
- using System.Runtime;
- using System.Text;
- using System.Globalization;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
- using System.Security;
+using System;
+using System.Runtime;
+using System.Text;
+using System.Globalization;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+using System.Security;
+namespace System.IO
+{
public class BinaryReader : IDisposable
{
private const int MaxCharBytesSize = 128;
- private Stream m_stream;
- private byte[] m_buffer;
- private Decoder m_decoder;
- private byte[] m_charBytes;
- private char[] m_singleChar;
- private char[] m_charBuffer;
- private int m_maxCharsSize; // From MaxCharBytesSize & Encoding
+ private Stream m_stream;
+ private byte[] m_buffer;
+ private Decoder m_decoder;
+ private byte[] m_charBytes;
+ private char[] m_singleChar;
+ private char[] m_charBuffer;
+ private int m_maxCharsSize; // From MaxCharBytesSize & Encoding
// Performance optimization for Read() w/ Unicode. Speeds us up by ~40%
- private bool m_2BytesPerChar;
- private bool m_isMemoryStream; // "do we sit on MemoryStream?" for Read/ReadInt32 perf
- private bool m_leaveOpen;
+ private bool m_2BytesPerChar;
+ private bool m_isMemoryStream; // "do we sit on MemoryStream?" for Read/ReadInt32 perf
+ private bool m_leaveOpen;
- public BinaryReader(Stream input) : this(input, Encoding.UTF8, false) {
+ public BinaryReader(Stream input) : this(input, Encoding.UTF8, false)
+ {
}
- public BinaryReader(Stream input, Encoding encoding) : this(input, encoding, false) {
+ public BinaryReader(Stream input, Encoding encoding) : this(input, encoding, false)
+ {
}
- public BinaryReader(Stream input, Encoding encoding, bool leaveOpen) {
- if (input==null) {
+ public BinaryReader(Stream input, Encoding encoding, bool leaveOpen)
+ {
+ if (input == null)
+ {
throw new ArgumentNullException(nameof(input));
}
- if (encoding==null) {
+ if (encoding == null)
+ {
throw new ArgumentNullException(nameof(encoding));
}
if (!input.CanRead)
- throw new ArgumentException(Environment.GetResourceString("Argument_StreamNotReadable"));
+ throw new ArgumentException(SR.Argument_StreamNotReadable);
Contract.EndContractBlock();
m_stream = input;
m_decoder = encoding.GetDecoder();
m_maxCharsSize = encoding.GetMaxCharCount(MaxCharBytesSize);
int minBufferSize = encoding.GetMaxByteCount(1); // max bytes per one char
- if (minBufferSize < 16)
+ if (minBufferSize < 16)
minBufferSize = 16;
m_buffer = new byte[minBufferSize];
// m_charBuffer and m_charBytes will be left null.
@@ -73,21 +79,26 @@ namespace System.IO {
m_isMemoryStream = (m_stream.GetType() == typeof(MemoryStream));
m_leaveOpen = leaveOpen;
- Debug.Assert(m_decoder!=null, "[BinaryReader.ctor]m_decoder!=null");
+ Debug.Assert(m_decoder != null, "[BinaryReader.ctor]m_decoder!=null");
}
- public virtual Stream BaseStream {
- get {
+ public virtual Stream BaseStream
+ {
+ get
+ {
return m_stream;
}
}
- public virtual void Close() {
+ public virtual void Close()
+ {
Dispose(true);
}
- protected virtual void Dispose(bool disposing) {
- if (disposing) {
+ protected virtual void Dispose(bool disposing)
+ {
+ if (disposing)
+ {
Stream copyOfStream = m_stream;
m_stream = null;
if (copyOfStream != null && !m_leaveOpen)
@@ -106,10 +117,11 @@ namespace System.IO {
Dispose(true);
}
- public virtual int PeekChar() {
+ public virtual int PeekChar()
+ {
Contract.Ensures(Contract.Result<int>() >= -1);
- if (m_stream==null) __Error.FileNotOpen();
+ if (m_stream == null) __Error.FileNotOpen();
if (!m_stream.CanSeek)
return -1;
@@ -118,59 +130,70 @@ namespace System.IO {
m_stream.Position = origPos;
return ch;
}
-
- public virtual int Read() {
+
+ public virtual int Read()
+ {
Contract.Ensures(Contract.Result<int>() >= -1);
- if (m_stream==null) {
+ if (m_stream == null)
+ {
__Error.FileNotOpen();
}
return InternalReadOneChar();
}
- public virtual bool ReadBoolean(){
+ public virtual bool ReadBoolean()
+ {
FillBuffer(1);
- return (m_buffer[0]!=0);
+ return (m_buffer[0] != 0);
}
- public virtual byte ReadByte() {
+ public virtual byte ReadByte()
+ {
// Inlined to avoid some method call overhead with FillBuffer.
- if (m_stream==null) __Error.FileNotOpen();
+ if (m_stream == null) __Error.FileNotOpen();
int b = m_stream.ReadByte();
if (b == -1)
__Error.EndOfFile();
- return (byte) b;
+ return (byte)b;
}
[CLSCompliant(false)]
- public virtual sbyte ReadSByte() {
+ public virtual sbyte ReadSByte()
+ {
FillBuffer(1);
return (sbyte)(m_buffer[0]);
}
- public virtual char ReadChar() {
+ public virtual char ReadChar()
+ {
int value = Read();
- if (value==-1) {
+ if (value == -1)
+ {
__Error.EndOfFile();
}
return (char)value;
}
- public virtual short ReadInt16() {
+ public virtual short ReadInt16()
+ {
FillBuffer(2);
return (short)(m_buffer[0] | m_buffer[1] << 8);
}
[CLSCompliant(false)]
- public virtual ushort ReadUInt16(){
+ public virtual ushort ReadUInt16()
+ {
FillBuffer(2);
return (ushort)(m_buffer[0] | m_buffer[1] << 8);
}
- public virtual int ReadInt32() {
- if (m_isMemoryStream) {
- if (m_stream==null) __Error.FileNotOpen();
+ public virtual int ReadInt32()
+ {
+ if (m_isMemoryStream)
+ {
+ if (m_stream == null) __Error.FileNotOpen();
// read directly from MemoryStream buffer
MemoryStream mStream = m_stream as MemoryStream;
Debug.Assert(mStream != null, "m_stream as MemoryStream != null");
@@ -185,22 +208,25 @@ namespace System.IO {
}
[CLSCompliant(false)]
- public virtual uint ReadUInt32() {
+ public virtual uint ReadUInt32()
+ {
FillBuffer(4);
return (uint)(m_buffer[0] | m_buffer[1] << 8 | m_buffer[2] << 16 | m_buffer[3] << 24);
}
- public virtual long ReadInt64() {
+ public virtual long ReadInt64()
+ {
FillBuffer(8);
uint lo = (uint)(m_buffer[0] | m_buffer[1] << 8 |
m_buffer[2] << 16 | m_buffer[3] << 24);
uint hi = (uint)(m_buffer[4] | m_buffer[5] << 8 |
m_buffer[6] << 16 | m_buffer[7] << 24);
- return (long) ((ulong)hi) << 32 | lo;
+ return (long)((ulong)hi) << 32 | lo;
}
[CLSCompliant(false)]
- public virtual ulong ReadUInt64() {
+ public virtual ulong ReadUInt64()
+ {
FillBuffer(8);
uint lo = (uint)(m_buffer[0] | m_buffer[1] << 8 |
m_buffer[2] << 16 | m_buffer[3] << 24);
@@ -209,13 +235,15 @@ namespace System.IO {
return ((ulong)hi) << 32 | lo;
}
- public virtual unsafe float ReadSingle() {
+ public virtual unsafe float ReadSingle()
+ {
FillBuffer(4);
uint tmpBuffer = (uint)(m_buffer[0] | m_buffer[1] << 8 | m_buffer[2] << 16 | m_buffer[3] << 24);
return *((float*)&tmpBuffer);
}
- public virtual unsafe double ReadDouble() {
+ public virtual unsafe double ReadDouble()
+ {
FillBuffer(8);
uint lo = (uint)(m_buffer[0] | m_buffer[1] << 8 |
m_buffer[2] << 16 | m_buffer[3] << 24);
@@ -226,18 +254,22 @@ namespace System.IO {
return *((double*)&tmpBuffer);
}
- public virtual decimal ReadDecimal() {
+ public virtual decimal ReadDecimal()
+ {
FillBuffer(16);
- try {
+ try
+ {
return Decimal.ToDecimal(m_buffer);
}
- catch (ArgumentException e) {
+ catch (ArgumentException e)
+ {
// ReadDecimal cannot leak out ArgumentException
- throw new IOException(Environment.GetResourceString("Arg_DecBitCtor"), e);
+ throw new IOException(SR.Arg_DecBitCtor, e);
}
}
- public virtual String ReadString() {
+ public virtual String ReadString()
+ {
Contract.Ensures(Contract.Result<String>() != null);
if (m_stream == null)
@@ -251,29 +283,34 @@ namespace System.IO {
// Length of the string in bytes, not chars
stringLength = Read7BitEncodedInt();
- if (stringLength<0) {
- throw new IOException(Environment.GetResourceString("IO.IO_InvalidStringLen_Len", stringLength));
+ if (stringLength < 0)
+ {
+ throw new IOException(SR.Format(SR.IO_InvalidStringLen_Len, stringLength));
}
- if (stringLength==0) {
+ if (stringLength == 0)
+ {
return String.Empty;
}
- if (m_charBytes==null) {
- m_charBytes = new byte[MaxCharBytesSize];
+ if (m_charBytes == null)
+ {
+ m_charBytes = new byte[MaxCharBytesSize];
}
-
- if (m_charBuffer == null) {
+
+ if (m_charBuffer == null)
+ {
m_charBuffer = new char[m_maxCharsSize];
}
-
- StringBuilder sb = null;
+
+ StringBuilder sb = null;
do
{
- readLength = ((stringLength - currPos)>MaxCharBytesSize)?MaxCharBytesSize:(stringLength - currPos);
+ readLength = ((stringLength - currPos) > MaxCharBytesSize) ? MaxCharBytesSize : (stringLength - currPos);
n = m_stream.Read(m_charBytes, 0, readLength);
- if (n==0) {
+ if (n == 0)
+ {
__Error.EndOfFile();
}
@@ -285,38 +322,43 @@ namespace System.IO {
if (sb == null)
sb = StringBuilderCache.Acquire(stringLength); // Actual string length in chars may be smaller.
sb.Append(m_charBuffer, 0, charsRead);
- currPos +=n;
-
- } while (currPos<stringLength);
+ currPos += n;
+ } while (currPos < stringLength);
return StringBuilderCache.GetStringAndRelease(sb);
}
- public virtual int Read(char[] buffer, int index, int count) {
- if (buffer==null) {
- throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
+ public virtual int Read(char[] buffer, int index, int count)
+ {
+ if (buffer == null)
+ {
+ throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
}
- if (index < 0) {
- throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ if (index < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
}
- if (count < 0) {
- throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ if (count < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
}
- if (buffer.Length - index < count) {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
+ if (buffer.Length - index < count)
+ {
+ throw new ArgumentException(SR.Argument_InvalidOffLen);
}
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.Ensures(Contract.Result<int>() <= count);
Contract.EndContractBlock();
- if (m_stream==null)
+ if (m_stream == null)
__Error.FileNotOpen();
// SafeCritical: index and count have already been verified to be a valid range for the buffer
return InternalReadChars(buffer, index, count);
}
- private int InternalReadChars(char[] buffer, int index, int count) {
+ private int InternalReadChars(char[] buffer, int index, int count)
+ {
Contract.Requires(buffer != null);
Contract.Requires(index >= 0 && count >= 0);
Debug.Assert(m_stream != null);
@@ -324,11 +366,13 @@ namespace System.IO {
int numBytes = 0;
int charsRemaining = count;
- if (m_charBytes==null) {
+ if (m_charBytes == null)
+ {
m_charBytes = new byte[MaxCharBytesSize];
}
- while (charsRemaining > 0) {
+ while (charsRemaining > 0)
+ {
int charsRead = 0;
// We really want to know what the minimum number of bytes per char
// is for our encoding. Otherwise for UnicodeEncoding we'd have to
@@ -337,7 +381,8 @@ namespace System.IO {
// special case for DecoderNLS subclasses when there is a hanging byte from the previous loop
DecoderNLS decoder = m_decoder as DecoderNLS;
- if (decoder != null && decoder.HasState && numBytes > 1) {
+ if (decoder != null && decoder.HasState && numBytes > 1)
+ {
numBytes -= 1;
}
@@ -360,10 +405,11 @@ namespace System.IO {
else
{
numBytes = m_stream.Read(m_charBytes, 0, numBytes);
- byteBuffer = m_charBytes;
+ byteBuffer = m_charBytes;
}
- if (numBytes == 0) {
+ if (numBytes == 0)
+ {
return (count - charsRemaining);
}
@@ -390,7 +436,7 @@ namespace System.IO {
}
charsRemaining -= charsRead;
- index+=charsRead;
+ index += charsRead;
}
// this should never fail
@@ -401,7 +447,8 @@ namespace System.IO {
return (count - charsRemaining);
}
- private int InternalReadOneChar() {
+ private int InternalReadOneChar()
+ {
// I know having a separate InternalReadOneChar method seems a little
// redundant, but this makes a scenario like the security parser code
// 20% faster, in addition to the optimizations for UnicodeEncoding I
@@ -409,18 +456,21 @@ namespace System.IO {
int charsRead = 0;
int numBytes = 0;
long posSav = posSav = 0;
-
+
if (m_stream.CanSeek)
posSav = m_stream.Position;
- if (m_charBytes==null) {
+ if (m_charBytes == null)
+ {
m_charBytes = new byte[MaxCharBytesSize];
}
- if (m_singleChar==null) {
+ if (m_singleChar == null)
+ {
m_singleChar = new char[1];
}
- while (charsRead == 0) {
+ while (charsRead == 0)
+ {
// We really want to know what the minimum number of bytes per char
// is for our encoding. Otherwise for UnicodeEncoding we'd have to
// do ~1+log(n) reads to read n characters.
@@ -428,25 +478,27 @@ namespace System.IO {
numBytes = m_2BytesPerChar ? 2 : 1;
int r = m_stream.ReadByte();
- m_charBytes[0] = (byte) r;
+ m_charBytes[0] = (byte)r;
if (r == -1)
numBytes = 0;
- if (numBytes == 2) {
+ if (numBytes == 2)
+ {
r = m_stream.ReadByte();
- m_charBytes[1] = (byte) r;
+ m_charBytes[1] = (byte)r;
if (r == -1)
numBytes = 1;
}
- if (numBytes==0) {
+ if (numBytes == 0)
+ {
// Console.WriteLine("Found no bytes. We're outta here.");
return -1;
}
Debug.Assert(numBytes == 1 || numBytes == 2, "BinaryReader::InternalReadOneChar assumes it's reading one or 2 bytes only.");
- try {
-
+ try
+ {
charsRead = m_decoder.GetChars(m_charBytes, 0, numBytes, m_singleChar, 0);
}
catch
@@ -468,65 +520,74 @@ namespace System.IO {
return m_singleChar[0];
}
- public virtual char[] ReadChars(int count) {
- if (count<0) {
- throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ public virtual char[] ReadChars(int count)
+ {
+ if (count < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
}
Contract.Ensures(Contract.Result<char[]>() != null);
Contract.Ensures(Contract.Result<char[]>().Length <= count);
Contract.EndContractBlock();
- if (m_stream == null) {
+ if (m_stream == null)
+ {
__Error.FileNotOpen();
}
- if (count == 0) {
- return EmptyArray<Char>.Value;
+ if (count == 0)
+ {
+ return Array.Empty<Char>();
}
// SafeCritical: we own the chars buffer, and therefore can guarantee that the index and count are valid
char[] chars = new char[count];
int n = InternalReadChars(chars, 0, count);
- if (n!=count) {
+ if (n != count)
+ {
char[] copy = new char[n];
- Buffer.InternalBlockCopy(chars, 0, copy, 0, 2*n); // sizeof(char)
+ Buffer.InternalBlockCopy(chars, 0, copy, 0, 2 * n); // sizeof(char)
chars = copy;
}
return chars;
}
- public virtual int Read(byte[] buffer, int index, int count) {
- if (buffer==null)
- throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
+ public virtual int Read(byte[] buffer, int index, int count)
+ {
+ if (buffer == null)
+ throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (index < 0)
- throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
- throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - index < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
+ throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.Ensures(Contract.Result<int>() <= count);
Contract.EndContractBlock();
- if (m_stream==null) __Error.FileNotOpen();
+ if (m_stream == null) __Error.FileNotOpen();
return m_stream.Read(buffer, index, count);
}
- public virtual byte[] ReadBytes(int count) {
- if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ public virtual byte[] ReadBytes(int count)
+ {
+ if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.Ensures(Contract.Result<byte[]>() != null);
Contract.Ensures(Contract.Result<byte[]>().Length <= Contract.OldValue(count));
Contract.EndContractBlock();
- if (m_stream==null) __Error.FileNotOpen();
+ if (m_stream == null) __Error.FileNotOpen();
- if (count == 0) {
- return EmptyArray<Byte>.Value;
+ if (count == 0)
+ {
+ return Array.Empty<Byte>();
}
byte[] result = new byte[count];
int numRead = 0;
- do {
+ do
+ {
int n = m_stream.Read(result, numRead, count);
if (n == 0)
break;
@@ -534,7 +595,8 @@ namespace System.IO {
count -= n;
} while (count > 0);
- if (numRead != result.Length) {
+ if (numRead != result.Length)
+ {
// Trim array. This should happen on EOF & possibly net streams.
byte[] copy = new byte[numRead];
Buffer.InternalBlockCopy(result, 0, copy, 0, numRead);
@@ -544,46 +606,53 @@ namespace System.IO {
return result;
}
- protected virtual void FillBuffer(int numBytes) {
- if (m_buffer != null && (numBytes < 0 || numBytes > m_buffer.Length)) {
- throw new ArgumentOutOfRangeException(nameof(numBytes), Environment.GetResourceString("ArgumentOutOfRange_BinaryReaderFillBuffer"));
+ protected virtual void FillBuffer(int numBytes)
+ {
+ if (m_buffer != null && (numBytes < 0 || numBytes > m_buffer.Length))
+ {
+ throw new ArgumentOutOfRangeException(nameof(numBytes), SR.ArgumentOutOfRange_BinaryReaderFillBuffer);
}
- int bytesRead=0;
+ int bytesRead = 0;
int n = 0;
- if (m_stream==null) __Error.FileNotOpen();
+ if (m_stream == null) __Error.FileNotOpen();
// Need to find a good threshold for calling ReadByte() repeatedly
// vs. calling Read(byte[], int, int) for both buffered & unbuffered
// streams.
- if (numBytes==1) {
+ if (numBytes == 1)
+ {
n = m_stream.ReadByte();
- if (n==-1)
+ if (n == -1)
__Error.EndOfFile();
m_buffer[0] = (byte)n;
return;
}
- do {
- n = m_stream.Read(m_buffer, bytesRead, numBytes-bytesRead);
- if (n==0) {
+ do
+ {
+ n = m_stream.Read(m_buffer, bytesRead, numBytes - bytesRead);
+ if (n == 0)
+ {
__Error.EndOfFile();
}
- bytesRead+=n;
- } while (bytesRead<numBytes);
+ bytesRead += n;
+ } while (bytesRead < numBytes);
}
- internal protected int Read7BitEncodedInt() {
+ internal protected int Read7BitEncodedInt()
+ {
// Read out an Int32 7 bits at a time. The high bit
// of the byte when on means to continue reading more bytes.
int count = 0;
int shift = 0;
byte b;
- do {
+ do
+ {
// Check for a corrupted stream. Read a max of 5 bytes.
// In a future version, add a DataFormatException.
if (shift == 5 * 7) // 5 bytes max per Int32, shift += 7
- throw new FormatException(Environment.GetResourceString("Format_Bad7BitInt32"));
+ throw new FormatException(SR.Format_Bad7BitInt32);
// ReadByte handles end of stream cases for us.
b = ReadByte();
diff --git a/src/mscorlib/src/System/IO/BinaryWriter.cs b/src/mscorlib/src/System/IO/BinaryWriter.cs
index b6c5625..3d9839f 100644
--- a/src/mscorlib/src/System/IO/BinaryWriter.cs
+++ b/src/mscorlib/src/System/IO/BinaryWriter.cs
@@ -13,6 +13,7 @@
**
**
===========================================================*/
+
using System;
using System.Runtime;
using System.Runtime.Serialization;
@@ -20,7 +21,8 @@ using System.Text;
using System.Diagnostics;
using System.Diagnostics.Contracts;
-namespace System.IO {
+namespace System.IO
+{
// This abstract base class represents a writer that can write
// primitives to an arbitrary stream. A subclass can override methods to
// give unique encodings.
@@ -29,7 +31,7 @@ namespace System.IO {
public class BinaryWriter : IDisposable
{
public static readonly BinaryWriter Null = new BinaryWriter();
-
+
protected Stream OutStream;
private byte[] _buffer; // temp space for writing primitives to.
private Encoding _encoding;
@@ -42,7 +44,7 @@ namespace System.IO {
private byte[] _largeByteBuffer; // temp space for writing chars.
private int _maxChars; // max # of chars we can put in _largeByteBuffer
// Size should be around the max number of chars/string * Encoding's max bytes/char
- private const int LargeByteBufferSize = 256;
+ private const int LargeByteBufferSize = 256;
// Protected default constructor that sets the output stream
// to a null stream (a bit bucket).
@@ -53,7 +55,7 @@ namespace System.IO {
_encoding = EncodingCache.UTF8NoBOM;
_encoder = _encoding.GetEncoder();
}
-
+
public BinaryWriter(Stream output) : this(output, EncodingCache.UTF8NoBOM, false)
{
}
@@ -64,21 +66,21 @@ namespace System.IO {
public BinaryWriter(Stream output, Encoding encoding, bool leaveOpen)
{
- if (output==null)
+ if (output == null)
throw new ArgumentNullException(nameof(output));
- if (encoding==null)
+ if (encoding == null)
throw new ArgumentNullException(nameof(encoding));
if (!output.CanWrite)
- throw new ArgumentException(Environment.GetResourceString("Argument_StreamNotWritable"));
+ throw new ArgumentException(SR.Argument_StreamNotWritable);
Contract.EndContractBlock();
-
+
OutStream = output;
_buffer = new byte[16];
_encoding = encoding;
_encoder = _encoding.GetEncoder();
_leaveOpen = leaveOpen;
}
-
+
// Closes this writer and releases any system resources associated with the
// writer. Following a call to Close, any operations on the writer
// may raise exceptions.
@@ -89,7 +91,8 @@ namespace System.IO {
protected virtual void Dispose(bool disposing)
{
- if (disposing) {
+ if (disposing)
+ {
if (_leaveOpen)
OutStream.Flush();
else
@@ -101,54 +104,57 @@ namespace System.IO {
{
Dispose(true);
}
-
+
/*
* Returns the stream associate with the writer. It flushes all pending
* writes before returning. All subclasses should override Flush to
* ensure that all buffered data is sent to the stream.
*/
- public virtual Stream BaseStream {
- get {
+ public virtual Stream BaseStream
+ {
+ get
+ {
Flush();
return OutStream;
}
}
-
+
// Clears all buffers for this writer and causes any buffered data to be
// written to the underlying device.
- public virtual void Flush()
+ public virtual void Flush()
{
OutStream.Flush();
}
-
+
public virtual long Seek(int offset, SeekOrigin origin)
{
return OutStream.Seek(offset, origin);
}
-
+
// Writes a boolean to this stream. A single byte is written to the stream
// with the value 0 representing false or the value 1 representing true.
//
- public virtual void Write(bool value) {
- _buffer[0] = (byte) (value ? 1 : 0);
+ public virtual void Write(bool value)
+ {
+ _buffer[0] = (byte)(value ? 1 : 0);
OutStream.Write(_buffer, 0, 1);
}
-
+
// Writes a byte to this stream. The current position of the stream is
// advanced by one.
//
- public virtual void Write(byte value)
+ public virtual void Write(byte value)
{
OutStream.WriteByte(value);
}
-
+
// Writes a signed byte to this stream. The current position of the stream
// is advanced by one.
//
[CLSCompliant(false)]
- public virtual void Write(sbyte value)
+ public virtual void Write(sbyte value)
{
- OutStream.WriteByte((byte) value);
+ OutStream.WriteByte((byte)value);
}
// Writes a byte array to this stream.
@@ -156,46 +162,50 @@ namespace System.IO {
// This default implementation calls the Write(Object, int, int)
// method to write the byte array.
//
- public virtual void Write(byte[] buffer) {
+ public virtual void Write(byte[] buffer)
+ {
if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
Contract.EndContractBlock();
OutStream.Write(buffer, 0, buffer.Length);
}
-
+
// Writes a section of a byte array to this stream.
//
// This default implementation calls the Write(Object, int, int)
// method to write the byte array.
//
- public virtual void Write(byte[] buffer, int index, int count) {
+ public virtual void Write(byte[] buffer, int index, int count)
+ {
OutStream.Write(buffer, index, count);
}
-
-
+
+
// Writes a character to this stream. The current position of the stream is
// advanced by two.
// Note this method cannot handle surrogates properly in UTF-8.
//
- public unsafe virtual void Write(char ch) {
+ public unsafe virtual void Write(char ch)
+ {
if (Char.IsSurrogate(ch))
- throw new ArgumentException(Environment.GetResourceString("Arg_SurrogatesNotAllowedAsSingleChar"));
+ throw new ArgumentException(SR.Arg_SurrogatesNotAllowedAsSingleChar);
Contract.EndContractBlock();
Debug.Assert(_encoding.GetMaxByteCount(1) <= 16, "_encoding.GetMaxByteCount(1) <= 16)");
int numBytes = 0;
- fixed(byte * pBytes = &_buffer[0]) {
+ fixed (byte* pBytes = &_buffer[0])
+ {
numBytes = _encoder.GetBytes(&ch, 1, pBytes, _buffer.Length, flush: true);
}
OutStream.Write(_buffer, 0, numBytes);
}
-
+
// Writes a character array to this stream.
//
// This default implementation calls the Write(Object, int, int)
// method to write the character array.
//
- public virtual void Write(char[] chars)
+ public virtual void Write(char[] chars)
{
if (chars == null)
throw new ArgumentNullException(nameof(chars));
@@ -204,49 +214,49 @@ namespace System.IO {
byte[] bytes = _encoding.GetBytes(chars, 0, chars.Length);
OutStream.Write(bytes, 0, bytes.Length);
}
-
+
// Writes a section of a character array to this stream.
//
// This default implementation calls the Write(Object, int, int)
// method to write the character array.
//
- public virtual void Write(char[] chars, int index, int count)
+ public virtual void Write(char[] chars, int index, int count)
{
byte[] bytes = _encoding.GetBytes(chars, index, count);
OutStream.Write(bytes, 0, bytes.Length);
}
-
-
+
+
// Writes a double to this stream. The current position of the stream is
// advanced by eight.
//
public unsafe virtual void Write(double value)
{
- ulong TmpValue = *(ulong *)&value;
- _buffer[0] = (byte) TmpValue;
- _buffer[1] = (byte) (TmpValue >> 8);
- _buffer[2] = (byte) (TmpValue >> 16);
- _buffer[3] = (byte) (TmpValue >> 24);
- _buffer[4] = (byte) (TmpValue >> 32);
- _buffer[5] = (byte) (TmpValue >> 40);
- _buffer[6] = (byte) (TmpValue >> 48);
- _buffer[7] = (byte) (TmpValue >> 56);
+ ulong TmpValue = *(ulong*)&value;
+ _buffer[0] = (byte)TmpValue;
+ _buffer[1] = (byte)(TmpValue >> 8);
+ _buffer[2] = (byte)(TmpValue >> 16);
+ _buffer[3] = (byte)(TmpValue >> 24);
+ _buffer[4] = (byte)(TmpValue >> 32);
+ _buffer[5] = (byte)(TmpValue >> 40);
+ _buffer[6] = (byte)(TmpValue >> 48);
+ _buffer[7] = (byte)(TmpValue >> 56);
OutStream.Write(_buffer, 0, 8);
}
public virtual void Write(decimal value)
{
- Decimal.GetBytes(value,_buffer);
+ Decimal.GetBytes(value, _buffer);
OutStream.Write(_buffer, 0, 16);
}
-
+
// Writes a two-byte signed integer to this stream. The current position of
// the stream is advanced by two.
//
public virtual void Write(short value)
{
- _buffer[0] = (byte) value;
- _buffer[1] = (byte) (value >> 8);
+ _buffer[0] = (byte)value;
+ _buffer[1] = (byte)(value >> 8);
OutStream.Write(_buffer, 0, 2);
}
@@ -256,20 +266,20 @@ namespace System.IO {
[CLSCompliant(false)]
public virtual void Write(ushort value)
{
- _buffer[0] = (byte) value;
- _buffer[1] = (byte) (value >> 8);
+ _buffer[0] = (byte)value;
+ _buffer[1] = (byte)(value >> 8);
OutStream.Write(_buffer, 0, 2);
}
-
+
// Writes a four-byte signed integer to this stream. The current position
// of the stream is advanced by four.
//
public virtual void Write(int value)
{
- _buffer[0] = (byte) value;
- _buffer[1] = (byte) (value >> 8);
- _buffer[2] = (byte) (value >> 16);
- _buffer[3] = (byte) (value >> 24);
+ _buffer[0] = (byte)value;
+ _buffer[1] = (byte)(value >> 8);
+ _buffer[2] = (byte)(value >> 16);
+ _buffer[3] = (byte)(value >> 24);
OutStream.Write(_buffer, 0, 4);
}
@@ -279,26 +289,26 @@ namespace System.IO {
[CLSCompliant(false)]
public virtual void Write(uint value)
{
- _buffer[0] = (byte) value;
- _buffer[1] = (byte) (value >> 8);
- _buffer[2] = (byte) (value >> 16);
- _buffer[3] = (byte) (value >> 24);
+ _buffer[0] = (byte)value;
+ _buffer[1] = (byte)(value >> 8);
+ _buffer[2] = (byte)(value >> 16);
+ _buffer[3] = (byte)(value >> 24);
OutStream.Write(_buffer, 0, 4);
}
-
+
// Writes an eight-byte signed integer to this stream. The current position
// of the stream is advanced by eight.
//
public virtual void Write(long value)
{
- _buffer[0] = (byte) value;
- _buffer[1] = (byte) (value >> 8);
- _buffer[2] = (byte) (value >> 16);
- _buffer[3] = (byte) (value >> 24);
- _buffer[4] = (byte) (value >> 32);
- _buffer[5] = (byte) (value >> 40);
- _buffer[6] = (byte) (value >> 48);
- _buffer[7] = (byte) (value >> 56);
+ _buffer[0] = (byte)value;
+ _buffer[1] = (byte)(value >> 8);
+ _buffer[2] = (byte)(value >> 16);
+ _buffer[3] = (byte)(value >> 24);
+ _buffer[4] = (byte)(value >> 32);
+ _buffer[5] = (byte)(value >> 40);
+ _buffer[6] = (byte)(value >> 48);
+ _buffer[7] = (byte)(value >> 56);
OutStream.Write(_buffer, 0, 8);
}
@@ -308,46 +318,47 @@ namespace System.IO {
[CLSCompliant(false)]
public virtual void Write(ulong value)
{
- _buffer[0] = (byte) value;
- _buffer[1] = (byte) (value >> 8);
- _buffer[2] = (byte) (value >> 16);
- _buffer[3] = (byte) (value >> 24);
- _buffer[4] = (byte) (value >> 32);
- _buffer[5] = (byte) (value >> 40);
- _buffer[6] = (byte) (value >> 48);
- _buffer[7] = (byte) (value >> 56);
+ _buffer[0] = (byte)value;
+ _buffer[1] = (byte)(value >> 8);
+ _buffer[2] = (byte)(value >> 16);
+ _buffer[3] = (byte)(value >> 24);
+ _buffer[4] = (byte)(value >> 32);
+ _buffer[5] = (byte)(value >> 40);
+ _buffer[6] = (byte)(value >> 48);
+ _buffer[7] = (byte)(value >> 56);
OutStream.Write(_buffer, 0, 8);
}
-
+
// Writes a float to this stream. The current position of the stream is
// advanced by four.
//
public unsafe virtual void Write(float value)
{
- uint TmpValue = *(uint *)&value;
- _buffer[0] = (byte) TmpValue;
- _buffer[1] = (byte) (TmpValue >> 8);
- _buffer[2] = (byte) (TmpValue >> 16);
- _buffer[3] = (byte) (TmpValue >> 24);
+ uint TmpValue = *(uint*)&value;
+ _buffer[0] = (byte)TmpValue;
+ _buffer[1] = (byte)(TmpValue >> 8);
+ _buffer[2] = (byte)(TmpValue >> 16);
+ _buffer[3] = (byte)(TmpValue >> 24);
OutStream.Write(_buffer, 0, 4);
}
-
-
+
+
// Writes a length-prefixed string to this stream in the BinaryWriter's
// current Encoding. This method first writes the length of the string as
// a four-byte unsigned integer, and then writes that many characters
// to the stream.
//
- public unsafe virtual void Write(String value)
+ public unsafe virtual void Write(String value)
{
- if (value==null)
+ if (value == null)
throw new ArgumentNullException(nameof(value));
Contract.EndContractBlock();
int len = _encoding.GetByteCount(value);
Write7BitEncodedInt(len);
- if (_largeByteBuffer == null) {
+ if (_largeByteBuffer == null)
+ {
_largeByteBuffer = new byte[LargeByteBufferSize];
_maxChars = _largeByteBuffer.Length / _encoding.GetMaxByteCount(1);
}
@@ -358,7 +369,8 @@ namespace System.IO {
_encoding.GetBytes(value, 0, value.Length, _largeByteBuffer, 0);
OutStream.Write(_largeByteBuffer, 0, len);
}
- else {
+ else
+ {
// Aggressively try to not allocate memory in this loop for
// runtime performance reasons. Use an Encoder to write out
// the string correctly (handling surrogates crossing buffer
@@ -368,7 +380,8 @@ namespace System.IO {
#if _DEBUG
int totalBytes = 0;
#endif
- while (numLeft > 0) {
+ while (numLeft > 0)
+ {
// Figure out how many chars to process this round.
int charCount = (numLeft > _maxChars) ? _maxChars : numLeft;
int byteLen;
@@ -389,7 +402,7 @@ namespace System.IO {
}
#if _DEBUG
totalBytes += byteLen;
- Debug.Assert (totalBytes <= len && byteLen <= _largeByteBuffer.Length, "BinaryWriter::Write(String) - More bytes encoded than expected!");
+ Debug.Assert(totalBytes <= len && byteLen <= _largeByteBuffer.Length, "BinaryWriter::Write(String) - More bytes encoded than expected!");
#endif
OutStream.Write(_largeByteBuffer, 0, byteLen);
charStart += charCount;
@@ -400,13 +413,15 @@ namespace System.IO {
#endif
}
}
-
- protected void Write7BitEncodedInt(int value) {
+
+ protected void Write7BitEncodedInt(int value)
+ {
// Write out an int 7 bits at a time. The high bit of the byte,
// when on, tells reader to continue reading more bytes.
- uint v = (uint) value; // support negative numbers
- while (v >= 0x80) {
- Write((byte) (v | 0x80));
+ uint v = (uint)value; // support negative numbers
+ while (v >= 0x80)
+ {
+ Write((byte)(v | 0x80));
v >>= 7;
}
Write((byte)v);
diff --git a/src/mscorlib/src/System/IO/Directory.cs b/src/mscorlib/src/System/IO/Directory.cs
index 88a669a..6417207 100644
--- a/src/mscorlib/src/System/IO/Directory.cs
+++ b/src/mscorlib/src/System/IO/Directory.cs
@@ -25,8 +25,8 @@ using System.Diagnostics.Contracts;
namespace System.IO
{
- internal static class Directory {
-
+ internal static class Directory
+ {
// Private class that holds search data that is passed around
// in the heap based stack recursion
internal sealed class SearchData
@@ -55,7 +55,7 @@ namespace System.IO
if (searchPattern == null)
throw new ArgumentNullException(nameof(searchPattern));
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
- throw new ArgumentOutOfRangeException(nameof(searchOption), Environment.GetResourceString("ArgumentOutOfRange_Enum"));
+ throw new ArgumentOutOfRangeException(nameof(searchOption), SR.ArgumentOutOfRange_Enum);
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
Contract.EndContractBlock();
@@ -85,8 +85,9 @@ namespace System.IO
}
#endif // PLATFORM_UNIX
- internal static String InternalGetDirectoryRoot(String path) {
- if (path == null) return null;
+ internal static String InternalGetDirectoryRoot(String path)
+ {
+ if (path == null) return null;
return path.Substring(0, PathInternal.GetRootLength(path));
}
@@ -116,10 +117,10 @@ namespace System.IO
buffer.Length = (int)result;
-#if !PLATFORM_UNIX
+#if PLATFORM_WINDOWS
if (buffer.Contains('~'))
return Path.GetFullPath(buffer.ToString());
-#endif
+#endif // PLATFORM_WINDOWS
return buffer.ToString();
}
@@ -131,16 +132,17 @@ namespace System.IO
public static void SetCurrentDirectory(String path)
{
- if (path==null)
+ if (path == null)
throw new ArgumentNullException(nameof(path));
- if (path.Length==0)
- throw new ArgumentException(Environment.GetResourceString("Argument_PathEmpty"));
+ if (path.Length == 0)
+ throw new ArgumentException(SR.Argument_PathEmpty);
if (path.Length >= Path.MaxPath)
- throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
+ throw new PathTooLongException(SR.IO_PathTooLong);
String fulldestDirName = Path.GetFullPath(path);
-
- if (!Win32Native.SetCurrentDirectory(fulldestDirName)) {
+
+ if (!Win32Native.SetCurrentDirectory(fulldestDirName))
+ {
// If path doesn't exist, this sets last error to 2 (File
// not Found). LEGACY: This may potentially have worked correctly
// on Win9x, maybe.
diff --git a/src/mscorlib/src/System/IO/DirectoryNotFoundException.cs b/src/mscorlib/src/System/IO/DirectoryNotFoundException.cs
deleted file mode 100644
index 21211a6..0000000
--- a/src/mscorlib/src/System/IO/DirectoryNotFoundException.cs
+++ /dev/null
@@ -1,45 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-/*============================================================
-**
-**
-**
-**
-**
-** Purpose: Exception for accessing a path that doesn't exist.
-**
-**
-===========================================================*/
-using System;
-using System.Runtime.Serialization;
-
-namespace System.IO {
- /*
- * Thrown when trying to access a directory that doesn't exist on disk.
- * From COM Interop, this exception is thrown for 2 HRESULTS:
- * the Win32 errorcode-as-HRESULT ERROR_PATH_NOT_FOUND (0x80070003)
- * and STG_E_PATHNOTFOUND (0x80030003).
- */
- [Serializable]
- public class DirectoryNotFoundException : IOException {
- public DirectoryNotFoundException()
- : base(Environment.GetResourceString("Arg_DirectoryNotFoundException")) {
- SetErrorCode(__HResults.COR_E_DIRECTORYNOTFOUND);
- }
-
- public DirectoryNotFoundException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_DIRECTORYNOTFOUND);
- }
-
- public DirectoryNotFoundException(String message, Exception innerException)
- : base(message, innerException) {
- SetErrorCode(__HResults.COR_E_DIRECTORYNOTFOUND);
- }
-
- protected DirectoryNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) {
- }
- }
-}
diff --git a/src/mscorlib/src/System/IO/DriveNotFoundException.cs b/src/mscorlib/src/System/IO/DriveNotFoundException.cs
index f0245a8..27b6f90 100644
--- a/src/mscorlib/src/System/IO/DriveNotFoundException.cs
+++ b/src/mscorlib/src/System/IO/DriveNotFoundException.cs
@@ -10,25 +10,30 @@
//
//
//============================================================
+
using System;
using System.Runtime.Serialization;
-namespace System.IO {
-
+namespace System.IO
+{
//Thrown when trying to access a drive that is not availabe.
[Serializable]
- internal class DriveNotFoundException : IOException {
- public DriveNotFoundException()
- : base(Environment.GetResourceString("Arg_DriveNotFoundException")) {
- SetErrorCode(__HResults.COR_E_DIRECTORYNOTFOUND);
+ internal class DriveNotFoundException : IOException
+ {
+ public DriveNotFoundException()
+ : base(SR.Arg_DriveNotFoundException)
+ {
+ HResult = __HResults.COR_E_DIRECTORYNOTFOUND;
}
-
- public DriveNotFoundException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_DIRECTORYNOTFOUND);
+
+ public DriveNotFoundException(String message)
+ : base(message)
+ {
+ HResult = __HResults.COR_E_DIRECTORYNOTFOUND;
}
-
- protected DriveNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) {
+
+ protected DriveNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context)
+ {
}
}
}
diff --git a/src/mscorlib/src/System/IO/EndOfStreamException.cs b/src/mscorlib/src/System/IO/EndOfStreamException.cs
deleted file mode 100644
index 558c792..0000000
--- a/src/mscorlib/src/System/IO/EndOfStreamException.cs
+++ /dev/null
@@ -1,42 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-/*============================================================
-**
-**
-**
-**
-**
-** Purpose: Exception to be thrown when reading past end-of-file.
-**
-**
-===========================================================*/
-
-using System;
-using System.Runtime.Serialization;
-
-namespace System.IO {
- [Serializable]
- public class EndOfStreamException : IOException
- {
- public EndOfStreamException()
- : base(Environment.GetResourceString("Arg_EndOfStreamException")) {
- SetErrorCode(__HResults.COR_E_ENDOFSTREAM);
- }
-
- public EndOfStreamException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_ENDOFSTREAM);
- }
-
- public EndOfStreamException(String message, Exception innerException)
- : base(message, innerException) {
- SetErrorCode(__HResults.COR_E_ENDOFSTREAM);
- }
-
- protected EndOfStreamException(SerializationInfo info, StreamingContext context) : base (info, context) {
- }
- }
-
-}
diff --git a/src/mscorlib/src/System/IO/File.cs b/src/mscorlib/src/System/IO/File.cs
index 7cc3f43..4aba148 100644
--- a/src/mscorlib/src/System/IO/File.cs
+++ b/src/mscorlib/src/System/IO/File.cs
@@ -74,27 +74,30 @@ namespace System.IO
return false;
}
- internal static bool InternalExists(String path) {
+ internal static bool InternalExists(String path)
+ {
Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
int dataInitialised = FillAttributeInfo(path, ref data, false, true);
- return (dataInitialised == 0) && (data.fileAttributes != -1)
- && ((data.fileAttributes & Win32Native.FILE_ATTRIBUTE_DIRECTORY) == 0);
+ return (dataInitialised == 0) && (data.fileAttributes != -1)
+ && ((data.fileAttributes & Win32Native.FILE_ATTRIBUTE_DIRECTORY) == 0);
}
public static byte[] ReadAllBytes(String path)
{
byte[] bytes;
- using(FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read,
- FileStream.DefaultBufferSize, FileOptions.None)) {
+ using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read,
+ FileStream.DefaultBufferSize, FileOptions.None))
+ {
// Do a blocking read
int index = 0;
long fileLength = fs.Length;
if (fileLength > Int32.MaxValue)
- throw new IOException(Environment.GetResourceString("IO.IO_FileTooLong2GB"));
- int count = (int) fileLength;
+ throw new IOException(SR.IO_FileTooLong2GB);
+ int count = (int)fileLength;
bytes = new byte[count];
- while(count > 0) {
+ while (count > 0)
+ {
int n = fs.Read(bytes, index, count);
if (n == 0)
__Error.EndOfFile();
@@ -111,7 +114,7 @@ namespace System.IO
if (path == null)
throw new ArgumentNullException(nameof(path));
if (path.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
+ throw new ArgumentException(SR.Argument_EmptyPath);
Contract.EndContractBlock();
return InternalReadAllLines(path, Encoding.UTF8);
@@ -133,7 +136,7 @@ namespace System.IO
return lines.ToArray();
}
#endif // PLATFORM_UNIX
-
+
// Returns 0 on success, otherwise a Win32 error code. Note that
// classes should use -1 as the uninitialized state for dataInitialized.
internal static int FillAttributeInfo(String path, ref Win32Native.WIN32_FILE_ATTRIBUTE_DATA data, bool tryagain, bool returnErrorOnNotFound)
@@ -142,29 +145,33 @@ namespace System.IO
if (tryagain) // someone has a handle to the file open, or other error
{
Win32Native.WIN32_FIND_DATA findData;
- findData = new Win32Native.WIN32_FIND_DATA ();
-
+ findData = new Win32Native.WIN32_FIND_DATA();
+
// Remove trialing slash since this can cause grief to FindFirstFile. You will get an invalid argument error
- String tempPath = path.TrimEnd(new char [] {Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar});
+ String tempPath = path.TrimEnd(new char[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar });
// For floppy drives, normally the OS will pop up a dialog saying
// there is no disk in drive A:, please insert one. We don't want that.
// SetErrorMode will let us disable this, but we should set the error
// mode back, since this may have wide-ranging effects.
int oldMode = Win32Native.SetErrorMode(Win32Native.SEM_FAILCRITICALERRORS);
- try {
+ try
+ {
bool error = false;
- SafeFindHandle handle = Win32Native.FindFirstFile(tempPath,findData);
- try {
- if (handle.IsInvalid) {
+ SafeFindHandle handle = Win32Native.FindFirstFile(tempPath, findData);
+ try
+ {
+ if (handle.IsInvalid)
+ {
error = true;
dataInitialised = Marshal.GetLastWin32Error();
-
+
if (dataInitialised == Win32Native.ERROR_FILE_NOT_FOUND ||
dataInitialised == Win32Native.ERROR_PATH_NOT_FOUND ||
dataInitialised == Win32Native.ERROR_NOT_READY) // floppy device not ready
{
- if (!returnErrorOnNotFound) {
+ if (!returnErrorOnNotFound)
+ {
// Return default value for backward compatibility
dataInitialised = 0;
data.fileAttributes = -1;
@@ -173,21 +180,26 @@ namespace System.IO
return dataInitialised;
}
}
- finally {
+ finally
+ {
// Close the Win32 handle
- try {
+ try
+ {
handle.Close();
}
- catch {
+ catch
+ {
// if we're already returning an error, don't throw another one.
- if (!error) {
+ if (!error)
+ {
Debug.Assert(false, "File::FillAttributeInfo - FindClose failed!");
__Error.WinIOError();
}
}
}
}
- finally {
+ finally
+ {
Win32Native.SetErrorMode(oldMode);
}
@@ -195,31 +207,36 @@ namespace System.IO
data.PopulateFrom(findData);
}
else
- {
- // For floppy drives, normally the OS will pop up a dialog saying
+ {
+ // For floppy drives, normally the OS will pop up a dialog saying
// there is no disk in drive A:, please insert one. We don't want that.
// SetErrorMode will let us disable this, but we should set the error
// mode back, since this may have wide-ranging effects.
bool success = false;
int oldMode = Win32Native.SetErrorMode(Win32Native.SEM_FAILCRITICALERRORS);
- try {
+ try
+ {
success = Win32Native.GetFileAttributesEx(path, GetFileExInfoStandard, ref data);
}
- finally {
+ finally
+ {
Win32Native.SetErrorMode(oldMode);
}
- if (!success) {
+ if (!success)
+ {
dataInitialised = Marshal.GetLastWin32Error();
if (dataInitialised != Win32Native.ERROR_FILE_NOT_FOUND &&
dataInitialised != Win32Native.ERROR_PATH_NOT_FOUND &&
dataInitialised != Win32Native.ERROR_NOT_READY) // floppy device not ready
{
- // In case someone latched onto the file. Take the perf hit only for failure
+ // In case someone latched onto the file. Take the perf hit only for failure
return FillAttributeInfo(path, ref data, true, returnErrorOnNotFound);
}
- else {
- if (!returnErrorOnNotFound) {
+ else
+ {
+ if (!returnErrorOnNotFound)
+ {
// Return default value for backward compbatibility
dataInitialised = 0;
data.fileAttributes = -1;
diff --git a/src/mscorlib/src/System/IO/FileAccess.cs b/src/mscorlib/src/System/IO/FileAccess.cs
deleted file mode 100644
index 707b58f..0000000
--- a/src/mscorlib/src/System/IO/FileAccess.cs
+++ /dev/null
@@ -1,41 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-/*============================================================
-**
-** Enum: FileAccess
-**
-**
-**
-**
-** Purpose: Enum describing whether you want read and/or write
-** permission to a file.
-**
-**
-===========================================================*/
-
-using System;
-
-namespace System.IO {
- // Contains constants for specifying the access you want for a file.
- // You can have Read, Write or ReadWrite access.
- //
-[Serializable]
-[Flags]
- public enum FileAccess
- {
- // Specifies read access to the file. Data can be read from the file and
- // the file pointer can be moved. Combine with WRITE for read-write access.
- Read = 1,
-
- // Specifies write access to the file. Data can be written to the file and
- // the file pointer can be moved. Combine with READ for read-write access.
- Write = 2,
-
- // Specifies read and write access to the file. Data can be written to the
- // file and the file pointer can be moved. Data can also be read from the
- // file.
- ReadWrite = 3,
- }
-}
diff --git a/src/mscorlib/src/System/IO/FileLoadException.CoreCLR.cs b/src/mscorlib/src/System/IO/FileLoadException.CoreCLR.cs
new file mode 100644
index 0000000..f641567
--- /dev/null
+++ b/src/mscorlib/src/System/IO/FileLoadException.CoreCLR.cs
@@ -0,0 +1,43 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Globalization;
+using System.Runtime.InteropServices;
+using System.Runtime.CompilerServices;
+using System.Security;
+
+namespace System.IO
+{
+ public partial class FileLoadException
+ {
+ // Do not delete: this is invoked from native code.
+ private FileLoadException(string fileName, string fusionLog, int hResult)
+ : base(null)
+ {
+ HResult = hResult;
+ FileName = fileName;
+ FusionLog = fusionLog;
+ _message = FormatFileLoadExceptionMessage(FileName, HResult);
+ }
+
+ internal static string FormatFileLoadExceptionMessage(string fileName, int hResult)
+ {
+ string format = null;
+ GetFileLoadExceptionMessage(hResult, JitHelpers.GetStringHandleOnStack(ref format));
+
+ string message = null;
+ GetMessageForHR(hResult, JitHelpers.GetStringHandleOnStack(ref message));
+
+ return string.Format(CultureInfo.CurrentCulture, format, fileName, message);
+ }
+
+ [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
+ [SuppressUnmanagedCodeSecurity]
+ private static extern void GetFileLoadExceptionMessage(int hResult, StringHandleOnStack retString);
+
+ [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
+ [SuppressUnmanagedCodeSecurity]
+ private static extern void GetMessageForHR(int hresult, StringHandleOnStack retString);
+ }
+}
diff --git a/src/mscorlib/src/System/IO/FileLoadException.cs b/src/mscorlib/src/System/IO/FileLoadException.cs
deleted file mode 100644
index 980d251..0000000
--- a/src/mscorlib/src/System/IO/FileLoadException.cs
+++ /dev/null
@@ -1,175 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-/*============================================================
-**
-**
-**
-**
-**
-**
-** Purpose: Exception for failure to load a file that was successfully found.
-**
-**
-===========================================================*/
-
-using System;
-using System.Globalization;
-using System.Runtime.Serialization;
-using System.Runtime.InteropServices;
-using System.Runtime.CompilerServices;
-using System.Security;
-using System.Runtime.Versioning;
-using SecurityException = System.Security.SecurityException;
-
-namespace System.IO {
-
- [Serializable]
- public class FileLoadException : IOException {
-
- private String _fileName; // the name of the file we could not load.
- private String _fusionLog; // fusion log (when applicable)
-
- public FileLoadException()
- : base(Environment.GetResourceString("IO.FileLoad")) {
- SetErrorCode(__HResults.COR_E_FILELOAD);
- }
-
- public FileLoadException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_FILELOAD);
- }
-
- public FileLoadException(String message, Exception inner)
- : base(message, inner) {
- SetErrorCode(__HResults.COR_E_FILELOAD);
- }
-
- public FileLoadException(String message, String fileName) : base(message)
- {
- SetErrorCode(__HResults.COR_E_FILELOAD);
- _fileName = fileName;
- }
-
- public FileLoadException(String message, String fileName, Exception inner)
- : base(message, inner) {
- SetErrorCode(__HResults.COR_E_FILELOAD);
- _fileName = fileName;
- }
-
- public override String Message
- {
- get {
- SetMessageField();
- return _message;
- }
- }
-
- private void SetMessageField()
- {
- if (_message == null)
- _message = FormatFileLoadExceptionMessage(_fileName, HResult);
- }
-
- public String FileName {
- get { return _fileName; }
- }
-
- public override String ToString()
- {
- String s = GetType().FullName + ": " + Message;
-
- if (_fileName != null && _fileName.Length != 0)
- s += Environment.NewLine + Environment.GetResourceString("IO.FileName_Name", _fileName);
-
- if (InnerException != null)
- s = s + " ---> " + InnerException.ToString();
-
- if (StackTrace != null)
- s += Environment.NewLine + StackTrace;
-
- try
- {
- if(FusionLog!=null)
- {
- if (s==null)
- s=" ";
- s+=Environment.NewLine;
- s+=Environment.NewLine;
- s+=FusionLog;
- }
- }
- catch(SecurityException)
- {
-
- }
-
- return s;
- }
-
- protected FileLoadException(SerializationInfo info, StreamingContext context) : base (info, context) {
- // Base class constructor will check info != null.
-
- _fileName = info.GetString("FileLoad_FileName");
-
- try
- {
- _fusionLog = info.GetString("FileLoad_FusionLog");
- }
- catch
- {
- _fusionLog = null;
- }
- }
-
- private FileLoadException(String fileName, String fusionLog,int hResult)
- : base(null)
- {
- SetErrorCode(hResult);
- _fileName = fileName;
- _fusionLog=fusionLog;
- SetMessageField();
- }
-
- public String FusionLog {
- get { return _fusionLog; }
- }
-
- public override void GetObjectData(SerializationInfo info, StreamingContext context) {
- // Serialize data for our base classes. base will verify info != null.
- base.GetObjectData(info, context);
-
- // Serialize data for this class
- info.AddValue("FileLoad_FileName", _fileName, typeof(String));
-
- try
- {
- info.AddValue("FileLoad_FusionLog", FusionLog, typeof(String));
- }
- catch (SecurityException)
- {
- }
- }
-
- internal static String FormatFileLoadExceptionMessage(String fileName,
- int hResult)
- {
- string format = null;
- GetFileLoadExceptionMessage(hResult, JitHelpers.GetStringHandleOnStack(ref format));
-
- string message = null;
- GetMessageForHR(hResult, JitHelpers.GetStringHandleOnStack(ref message));
-
- return String.Format(CultureInfo.CurrentCulture, format, fileName, message);
- }
-
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- private static extern void GetFileLoadExceptionMessage(int hResult, StringHandleOnStack retString);
-
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- private static extern void GetMessageForHR(int hresult, StringHandleOnStack retString);
- }
-}
diff --git a/src/mscorlib/src/System/IO/FileMode.cs b/src/mscorlib/src/System/IO/FileMode.cs
deleted file mode 100644
index 3972cf0..0000000
--- a/src/mscorlib/src/System/IO/FileMode.cs
+++ /dev/null
@@ -1,53 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-/*============================================================
-**
-** Enum: FileMode
-**
-**
-**
-**
-** Purpose: Enum describing whether to create a new file or
-** open an existing one.
-**
-**
-===========================================================*/
-
-using System;
-
-namespace System.IO {
- // Contains constants for specifying how the OS should open a file.
- // These will control whether you overwrite a file, open an existing
- // file, or some combination thereof.
- //
- // To append to a file, use Append (which maps to OpenOrCreate then we seek
- // to the end of the file). To truncate a file or create it if it doesn't
- // exist, use Create.
- //
- [Serializable]
- public enum FileMode
- {
- // Creates a new file. An exception is raised if the file already exists.
- CreateNew = 1,
-
- // Creates a new file. If the file already exists, it is overwritten.
- Create = 2,
-
- // Opens an existing file. An exception is raised if the file does not exist.
- Open = 3,
-
- // Opens the file if it exists. Otherwise, creates a new file.
- OpenOrCreate = 4,
-
- // Opens an existing file. Once opened, the file is truncated so that its
- // size is zero bytes. The calling process must open the file with at least
- // WRITE access. An exception is raised if the file does not exist.
- Truncate = 5,
-
- // Opens the file if it exists and seeks to the end. Otherwise,
- // creates a new file.
- Append = 6,
- }
-}
diff --git a/src/mscorlib/src/System/IO/FileNotFoundException.CoreCLR.cs b/src/mscorlib/src/System/IO/FileNotFoundException.CoreCLR.cs
new file mode 100644
index 0000000..99645f0
--- /dev/null
+++ b/src/mscorlib/src/System/IO/FileNotFoundException.CoreCLR.cs
@@ -0,0 +1,20 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+namespace System.IO
+{
+ public partial class FileNotFoundException
+ {
+ // Do not delete: this is invoked from native code.
+ private FileNotFoundException(string fileName, string fusionLog, int hResult)
+ : base(null)
+ {
+ HResult = hResult;
+ FileName = fileName;
+ FusionLog = fusionLog;
+ SetMessageField();
+ }
+ }
+}
+
diff --git a/src/mscorlib/src/System/IO/FileNotFoundException.cs b/src/mscorlib/src/System/IO/FileNotFoundException.cs
deleted file mode 100644
index ad6b538..0000000
--- a/src/mscorlib/src/System/IO/FileNotFoundException.cs
+++ /dev/null
@@ -1,157 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-/*============================================================
-**
-**
-**
-**
-**
-**
-** Purpose: Exception for accessing a file that doesn't exist.
-**
-**
-===========================================================*/
-
-using System;
-using System.Runtime.Serialization;
-using SecurityException = System.Security.SecurityException;
-using System.Globalization;
-
-namespace System.IO {
- // Thrown when trying to access a file that doesn't exist on disk.
- [Serializable]
- public class FileNotFoundException : IOException {
-
- private String _fileName; // The name of the file that isn't found.
- private String _fusionLog; // fusion log (when applicable)
-
- public FileNotFoundException()
- : base(Environment.GetResourceString("IO.FileNotFound")) {
- SetErrorCode(__HResults.COR_E_FILENOTFOUND);
- }
-
- public FileNotFoundException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_FILENOTFOUND);
- }
-
- public FileNotFoundException(String message, Exception innerException)
- : base(message, innerException) {
- SetErrorCode(__HResults.COR_E_FILENOTFOUND);
- }
-
- public FileNotFoundException(String message, String fileName) : base(message)
- {
- SetErrorCode(__HResults.COR_E_FILENOTFOUND);
- _fileName = fileName;
- }
-
- public FileNotFoundException(String message, String fileName, Exception innerException)
- : base(message, innerException) {
- SetErrorCode(__HResults.COR_E_FILENOTFOUND);
- _fileName = fileName;
- }
-
- public override String Message
- {
- get {
- SetMessageField();
- return _message;
- }
- }
-
- private void SetMessageField()
- {
- if (_message == null) {
- if ((_fileName == null) &&
- (HResult == System.__HResults.COR_E_EXCEPTION))
- _message = Environment.GetResourceString("IO.FileNotFound");
-
- else if( _fileName != null)
- _message = FileLoadException.FormatFileLoadExceptionMessage(_fileName, HResult);
- }
- }
-
- public String FileName {
- get { return _fileName; }
- }
-
- public override String ToString()
- {
- String s = GetType().FullName + ": " + Message;
-
- if (_fileName != null && _fileName.Length != 0)
- s += Environment.NewLine + Environment.GetResourceString("IO.FileName_Name", _fileName);
-
- if (InnerException != null)
- s = s + " ---> " + InnerException.ToString();
-
- if (StackTrace != null)
- s += Environment.NewLine + StackTrace;
-
- try
- {
- if(FusionLog!=null)
- {
- if (s==null)
- s=" ";
- s+=Environment.NewLine;
- s+=Environment.NewLine;
- s+=FusionLog;
- }
- }
- catch(SecurityException)
- {
-
- }
- return s;
-
- }
-
- protected FileNotFoundException(SerializationInfo info, StreamingContext context) : base (info, context) {
- // Base class constructor will check info != null.
-
- _fileName = info.GetString("FileNotFound_FileName");
- try
- {
- _fusionLog = info.GetString("FileNotFound_FusionLog");
- }
- catch
- {
- _fusionLog = null;
- }
- }
-
- private FileNotFoundException(String fileName, String fusionLog,int hResult)
- : base(null)
- {
- SetErrorCode(hResult);
- _fileName = fileName;
- _fusionLog=fusionLog;
- SetMessageField();
- }
-
- public String FusionLog {
- get { return _fusionLog; }
- }
-
- public override void GetObjectData(SerializationInfo info, StreamingContext context) {
- // Serialize data for our base classes. base will verify info != null.
- base.GetObjectData(info, context);
-
- // Serialize data for this class
- info.AddValue("FileNotFound_FileName", _fileName, typeof(String));
-
- try
- {
- info.AddValue("FileNotFound_FusionLog", FusionLog, typeof(String));
- }
- catch (SecurityException)
- {
- }
- }
- }
-}
-
diff --git a/src/mscorlib/src/System/IO/FileOptions.cs b/src/mscorlib/src/System/IO/FileOptions.cs
deleted file mode 100644
index 02bc99e..0000000
--- a/src/mscorlib/src/System/IO/FileOptions.cs
+++ /dev/null
@@ -1,46 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-/*============================================================
-**
-** Enum: FileOptions
-**
-**
-**
-**
-** Purpose: Additional options to how to create a FileStream.
-** Exposes the more obscure CreateFile functionality.
-**
-**
-===========================================================*/
-
-using System;
-using System.Runtime.InteropServices;
-
-namespace System.IO {
- // Maps to FILE_FLAG_DELETE_ON_CLOSE and similar values from winbase.h.
- // We didn't expose a number of these values because we didn't believe
- // a number of them made sense in managed code, at least not yet.
- [Serializable]
- [Flags]
- public enum FileOptions
- {
- // NOTE: any change to FileOptions enum needs to be
- // matched in the FileStream ctor for error validation
- None = 0,
- WriteThrough = unchecked((int)0x80000000),
- Asynchronous = unchecked((int)0x40000000), // FILE_FLAG_OVERLAPPED
- // NoBuffering = 0x20000000,
- RandomAccess = 0x10000000,
- DeleteOnClose = 0x04000000,
- SequentialScan = 0x08000000,
- // AllowPosix = 0x01000000, // FILE_FLAG_POSIX_SEMANTICS
- // BackupOrRestore,
- // DisallowReparsePoint = 0x00200000, // FILE_FLAG_OPEN_REPARSE_POINT
- // NoRemoteRecall = 0x00100000, // FILE_FLAG_OPEN_NO_RECALL
- // FirstPipeInstance = 0x00080000, // FILE_FLAG_FIRST_PIPE_INSTANCE
- Encrypted = 0x00004000, // FILE_ATTRIBUTE_ENCRYPTED
- }
-}
-
diff --git a/src/mscorlib/src/System/IO/FileShare.cs b/src/mscorlib/src/System/IO/FileShare.cs
deleted file mode 100644
index 8a7d1f0..0000000
--- a/src/mscorlib/src/System/IO/FileShare.cs
+++ /dev/null
@@ -1,59 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-/*============================================================
-**
-** Enum: FileShare
-**
-**
-**
-**
-** Purpose: Enum describing how to share files with other
-** processes - ie, whether two processes can simultaneously
-** read from the same file.
-**
-**
-===========================================================*/
-
-using System;
-
-namespace System.IO {
- // Contains constants for controlling file sharing options while
- // opening files. You can specify what access other processes trying
- // to open the same file concurrently can have.
- //
- // Note these values currently match the values for FILE_SHARE_READ,
- // FILE_SHARE_WRITE, and FILE_SHARE_DELETE in winnt.h
- //
-[Serializable]
-[Flags]
- public enum FileShare
- {
- // No sharing. Any request to open the file (by this process or another
- // process) will fail until the file is closed.
- None = 0,
-
- // Allows subsequent opening of the file for reading. If this flag is not
- // specified, any request to open the file for reading (by this process or
- // another process) will fail until the file is closed.
- Read = 1,
-
- // Allows subsequent opening of the file for writing. If this flag is not
- // specified, any request to open the file for writing (by this process or
- // another process) will fail until the file is closed.
- Write = 2,
-
- // Allows subsequent opening of the file for writing or reading. If this flag
- // is not specified, any request to open the file for writing or reading (by
- // this process or another process) will fail until the file is closed.
- ReadWrite = 3,
-
- // Open the file, but allow someone else to delete the file.
- Delete = 4,
-
- // Whether the file handle should be inheritable by child processes.
- // Note this is not directly supported like this by Win32.
- Inheritable = 0x10,
- }
-}
diff --git a/src/mscorlib/src/System/IO/IOException.cs b/src/mscorlib/src/System/IO/IOException.cs
index ab61281..2628f7b 100644
--- a/src/mscorlib/src/System/IO/IOException.cs
+++ b/src/mscorlib/src/System/IO/IOException.cs
@@ -16,8 +16,8 @@
using System;
using System.Runtime.Serialization;
-namespace System.IO {
-
+namespace System.IO
+{
[Serializable]
public class IOException : SystemException
{
@@ -32,36 +32,42 @@ namespace System.IO {
[NonSerialized]
private String _maybeFullPath; // For debuggers on partial trust code
- public IOException()
- : base(Environment.GetResourceString("Arg_IOException")) {
- SetErrorCode(__HResults.COR_E_IO);
+ public IOException()
+ : base(SR.Arg_IOException)
+ {
+ HResult = __HResults.COR_E_IO;
}
-
- public IOException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_IO);
+
+ public IOException(String message)
+ : base(message)
+ {
+ HResult = __HResults.COR_E_IO;
}
- public IOException(String message, int hresult)
- : base(message) {
- SetErrorCode(hresult);
+ public IOException(String message, int hresult)
+ : base(message)
+ {
+ HResult = hresult;
}
// Adding this for debuggers when looking at exceptions in partial
// trust code that may not have interesting path information in
// the exception message.
- internal IOException(String message, int hresult, String maybeFullPath)
- : base(message) {
- SetErrorCode(hresult);
+ internal IOException(String message, int hresult, String maybeFullPath)
+ : base(message)
+ {
+ HResult = hresult;
_maybeFullPath = maybeFullPath;
}
-
- public IOException(String message, Exception innerException)
- : base(message, innerException) {
- SetErrorCode(__HResults.COR_E_IO);
+
+ public IOException(String message, Exception innerException)
+ : base(message, innerException)
+ {
+ HResult = __HResults.COR_E_IO;
}
- protected IOException(SerializationInfo info, StreamingContext context) : base (info, context) {
+ protected IOException(SerializationInfo info, StreamingContext context) : base(info, context)
+ {
}
}
}
diff --git a/src/mscorlib/src/System/IO/MemoryStream.cs b/src/mscorlib/src/System/IO/MemoryStream.cs
index 05aac90..3d5668d 100644
--- a/src/mscorlib/src/System/IO/MemoryStream.cs
+++ b/src/mscorlib/src/System/IO/MemoryStream.cs
@@ -24,7 +24,8 @@ using System.Diagnostics.Contracts;
using System.Threading;
using System.Threading.Tasks;
-namespace System.IO {
+namespace System.IO
+{
// A MemoryStream represents a Stream in memory (ie, it has no backing store).
// This stream may reduce the need for temporary buffers and files in
// an application.
@@ -54,17 +55,20 @@ namespace System.IO {
private const int MemStreamMaxLength = Int32.MaxValue;
- public MemoryStream()
- : this(0) {
+ public MemoryStream()
+ : this(0)
+ {
}
-
- public MemoryStream(int capacity) {
- if (capacity < 0) {
- throw new ArgumentOutOfRangeException(nameof(capacity), Environment.GetResourceString("ArgumentOutOfRange_NegativeCapacity"));
+
+ public MemoryStream(int capacity)
+ {
+ if (capacity < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_NegativeCapacity);
}
Contract.EndContractBlock();
- _buffer = capacity != 0 ? new byte[capacity] : EmptyArray<byte>.Value;
+ _buffer = capacity != 0 ? new byte[capacity] : Array.Empty<byte>();
_capacity = capacity;
_expandable = true;
_writable = true;
@@ -72,13 +76,15 @@ namespace System.IO {
_origin = 0; // Must be 0 for byte[]'s created by MemoryStream
_isOpen = true;
}
-
- public MemoryStream(byte[] buffer)
- : this(buffer, true) {
+
+ public MemoryStream(byte[] buffer)
+ : this(buffer, true)
+ {
}
-
- public MemoryStream(byte[] buffer, bool writable) {
- if (buffer == null) throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
+
+ public MemoryStream(byte[] buffer, bool writable)
+ {
+ if (buffer == null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
Contract.EndContractBlock();
_buffer = buffer;
_length = _capacity = buffer.Length;
@@ -87,26 +93,29 @@ namespace System.IO {
_origin = 0;
_isOpen = true;
}
-
- public MemoryStream(byte[] buffer, int index, int count)
- : this(buffer, index, count, true, false) {
+
+ public MemoryStream(byte[] buffer, int index, int count)
+ : this(buffer, index, count, true, false)
+ {
}
-
- public MemoryStream(byte[] buffer, int index, int count, bool writable)
- : this(buffer, index, count, writable, false) {
+
+ public MemoryStream(byte[] buffer, int index, int count, bool writable)
+ : this(buffer, index, count, writable, false)
+ {
}
-
- public MemoryStream(byte[] buffer, int index, int count, bool writable, bool publiclyVisible) {
- if (buffer==null)
- throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
+
+ public MemoryStream(byte[] buffer, int index, int count, bool writable, bool publiclyVisible)
+ {
+ if (buffer == null)
+ throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (index < 0)
- throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
- throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - index < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
+ throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock();
-
+
_buffer = buffer;
_origin = _position = index;
_length = _capacity = index + count;
@@ -115,30 +124,36 @@ namespace System.IO {
_expandable = false;
_isOpen = true;
}
-
- public override bool CanRead {
+
+ public override bool CanRead
+ {
[Pure]
get { return _isOpen; }
}
-
- public override bool CanSeek {
+
+ public override bool CanSeek
+ {
[Pure]
get { return _isOpen; }
}
-
- public override bool CanWrite {
+
+ public override bool CanWrite
+ {
[Pure]
get { return _writable; }
}
- private void EnsureWriteable() {
+ private void EnsureWriteable()
+ {
if (!CanWrite) __Error.WriteNotSupported();
}
protected override void Dispose(bool disposing)
{
- try {
- if (disposing) {
+ try
+ {
+ if (disposing)
+ {
_isOpen = false;
_writable = false;
_expandable = false;
@@ -146,18 +161,21 @@ namespace System.IO {
_lastReadTask = null;
}
}
- finally {
+ finally
+ {
// Call base.Close() to cleanup async IO resources
base.Dispose(disposing);
}
}
-
+
// returns a bool saying whether we allocated a new array.
- private bool EnsureCapacity(int value) {
+ private bool EnsureCapacity(int value)
+ {
// Check for overflow
if (value < 0)
- throw new IOException(Environment.GetResourceString("IO.IO_StreamTooLong"));
- if (value > _capacity) {
+ throw new IOException(SR.IO_StreamTooLong);
+ if (value > _capacity)
+ {
int newCapacity = value;
if (newCapacity < 256)
newCapacity = 256;
@@ -169,53 +187,58 @@ namespace System.IO {
// And we want to give the user the value that they asked for
if ((uint)(_capacity * 2) > Array.MaxByteArrayLength)
newCapacity = value > Array.MaxByteArrayLength ? value : Array.MaxByteArrayLength;
-
+
Capacity = newCapacity;
return true;
}
return false;
}
-
- public override void Flush() {
- }
- public override Task FlushAsync(CancellationToken cancellationToken) {
+ public override void Flush()
+ {
+ }
+ public override Task FlushAsync(CancellationToken cancellationToken)
+ {
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled(cancellationToken);
- try {
-
+ try
+ {
Flush();
return Task.CompletedTask;
-
- } catch(Exception ex) {
-
+ }
+ catch (Exception ex)
+ {
return Task.FromException(ex);
}
}
- public virtual byte[] GetBuffer() {
+ public virtual byte[] GetBuffer()
+ {
if (!_exposable)
- throw new UnauthorizedAccessException(Environment.GetResourceString("UnauthorizedAccess_MemStreamBuffer"));
+ throw new UnauthorizedAccessException(SR.UnauthorizedAccess_MemStreamBuffer);
return _buffer;
}
- public virtual bool TryGetBuffer(out ArraySegment<byte> buffer) {
- if (!_exposable) {
+ public virtual bool TryGetBuffer(out ArraySegment<byte> buffer)
+ {
+ if (!_exposable)
+ {
buffer = default(ArraySegment<byte>);
return false;
}
- buffer = new ArraySegment<byte>(_buffer, offset:_origin, count:(_length - _origin));
+ buffer = new ArraySegment<byte>(_buffer, offset: _origin, count: (_length - _origin));
return true;
}
// -------------- PERF: Internal functions for fast direct access of MemoryStream buffer (cf. BinaryReader for usage) ---------------
// PERF: Internal sibling of GetBuffer, always returns a buffer (cf. GetBuffer())
- internal byte[] InternalGetBuffer() {
+ internal byte[] InternalGetBuffer()
+ {
return _buffer;
}
@@ -229,27 +252,30 @@ namespace System.IO {
}
// PERF: True cursor position, we don't need _origin for direct access
- internal int InternalGetPosition() {
+ internal int InternalGetPosition()
+ {
if (!_isOpen) __Error.StreamIsClosed();
return _position;
}
// PERF: Takes out Int32 as fast as possible
- internal int InternalReadInt32() {
- if (!_isOpen)
- __Error.StreamIsClosed();
+ internal int InternalReadInt32()
+ {
+ if (!_isOpen)
+ __Error.StreamIsClosed();
- int pos = (_position += 4); // use temp to avoid a race condition
- if (pos > _length)
- {
- _position = _length;
- __Error.EndOfFile();
- }
- return (int)(_buffer[pos-4] | _buffer[pos-3] << 8 | _buffer[pos-2] << 16 | _buffer[pos-1] << 24);
+ int pos = (_position += 4); // use temp to avoid a race condition
+ if (pos > _length)
+ {
+ _position = _length;
+ __Error.EndOfFile();
+ }
+ return (int)(_buffer[pos - 4] | _buffer[pos - 3] << 8 | _buffer[pos - 2] << 16 | _buffer[pos - 1] << 24);
}
// PERF: Get actual length of bytes available for read; do sanity checks; shift position - i.e. everything except actual copying bytes
- internal int InternalEmulateRead(int count) {
+ internal int InternalEmulateRead(int count)
+ {
if (!_isOpen) __Error.StreamIsClosed();
int n = _length - _position;
@@ -260,20 +286,23 @@ namespace System.IO {
_position += n;
return n;
}
-
+
// Gets & sets the capacity (number of bytes allocated) for this stream.
// The capacity cannot be set to a value less than the current length
// of the stream.
//
- public virtual int Capacity {
- get {
+ public virtual int Capacity
+ {
+ get
+ {
if (!_isOpen) __Error.StreamIsClosed();
return _capacity - _origin;
}
- set {
+ set
+ {
// Only update the capacity if the MS is expandable and the value is different than the current capacity.
// Special behavior if the MS isn't expandable: we don't throw if value is the same as the current capacity
- if (value < Length) throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_SmallCapacity"));
+ if (value < Length) throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_SmallCapacity);
Contract.Ensures(_capacity - _origin == value);
Contract.EndContractBlock();
@@ -281,55 +310,64 @@ namespace System.IO {
if (!_expandable && (value != Capacity)) __Error.MemoryStreamNotExpandable();
// MemoryStream has this invariant: _origin > 0 => !expandable (see ctors)
- if (_expandable && value != _capacity) {
- if (value > 0) {
+ if (_expandable && value != _capacity)
+ {
+ if (value > 0)
+ {
byte[] newBuffer = new byte[value];
if (_length > 0) Buffer.InternalBlockCopy(_buffer, 0, newBuffer, 0, _length);
_buffer = newBuffer;
}
- else {
+ else
+ {
_buffer = null;
}
_capacity = value;
}
}
- }
+ }
- public override long Length {
- get {
+ public override long Length
+ {
+ get
+ {
if (!_isOpen) __Error.StreamIsClosed();
return _length - _origin;
}
}
- public override long Position {
- get {
+ public override long Position
+ {
+ get
+ {
if (!_isOpen) __Error.StreamIsClosed();
return _position - _origin;
}
- set {
+ set
+ {
if (value < 0)
- throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.Ensures(Position == value);
Contract.EndContractBlock();
if (!_isOpen) __Error.StreamIsClosed();
if (value > MemStreamMaxLength)
- throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_StreamLength"));
+ throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_StreamLength);
_position = _origin + (int)value;
}
}
- public override int Read([In, Out] byte[] buffer, int offset, int count) {
- if (buffer==null)
- throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
+ public override int Read([In, Out] byte[] buffer, int offset, int count)
+ {
+ if (buffer == null)
+ throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (offset < 0)
- throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
- throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
+ throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock();
if (!_isOpen) __Error.StreamIsClosed();
@@ -356,25 +394,25 @@ namespace System.IO {
public override Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
- if (buffer==null)
- throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
+ if (buffer == null)
+ throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (offset < 0)
- throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
- throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
+ throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock(); // contract validation copied from Read(...)
// If cancellation was requested, bail early
- if (cancellationToken.IsCancellationRequested)
+ if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled<int>(cancellationToken);
try
{
int n = Read(buffer, offset, count);
var t = _lastReadTask;
- Debug.Assert(t == null || t.Status == TaskStatus.RanToCompletion,
+ Debug.Assert(t == null || t.Status == TaskStatus.RanToCompletion,
"Expected that a stored last task completed successfully");
return (t != null && t.Result == n) ? t : (_lastReadTask = Task.FromResult<int>(n));
}
@@ -389,9 +427,10 @@ namespace System.IO {
}
- public override int ReadByte() {
+ public override int ReadByte()
+ {
if (!_isOpen) __Error.StreamIsClosed();
-
+
if (_position >= _length) return -1;
return _buffer[_position++];
@@ -412,7 +451,7 @@ namespace System.IO {
base.CopyTo(destination, bufferSize);
return;
}
-
+
int originalPosition = _position;
// Seek to the end of the MemoryStream.
@@ -427,8 +466,8 @@ namespace System.IO {
}
}
- public override Task CopyToAsync(Stream destination, Int32 bufferSize, CancellationToken cancellationToken) {
-
+ public override Task CopyToAsync(Stream destination, Int32 bufferSize, CancellationToken cancellationToken)
+ {
// This implementation offers beter performance compared to the base class version.
StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
@@ -443,7 +482,7 @@ namespace System.IO {
// If cancelled - return fast:
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled(cancellationToken);
-
+
// Avoid copying data from this buffer into a temp buffer:
// (require that InternalEmulateRead does not throw,
// otherwise it needs to be wrapped into try-catch-Task.FromException like memStrDest.Write below)
@@ -453,56 +492,62 @@ namespace System.IO {
// If destination is not a memory stream, write there asynchronously:
MemoryStream memStrDest = destination as MemoryStream;
- if (memStrDest == null)
+ if (memStrDest == null)
return destination.WriteAsync(_buffer, pos, n, cancellationToken);
-
- try {
+ try
+ {
// If destination is a MemoryStream, CopyTo synchronously:
memStrDest.Write(_buffer, pos, n);
return Task.CompletedTask;
-
- } catch(Exception ex) {
+ }
+ catch (Exception ex)
+ {
return Task.FromException(ex);
}
}
- public override long Seek(long offset, SeekOrigin loc) {
+ public override long Seek(long offset, SeekOrigin loc)
+ {
if (!_isOpen) __Error.StreamIsClosed();
if (offset > MemStreamMaxLength)
- throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_StreamLength"));
- switch(loc) {
- case SeekOrigin.Begin: {
- int tempPosition = unchecked(_origin + (int)offset);
- if (offset < 0 || tempPosition < _origin)
- throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin"));
- _position = tempPosition;
- break;
- }
- case SeekOrigin.Current: {
- int tempPosition = unchecked(_position + (int)offset);
- if (unchecked(_position + offset) < _origin || tempPosition < _origin)
- throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin"));
- _position = tempPosition;
- break;
- }
- case SeekOrigin.End: {
- int tempPosition = unchecked(_length + (int)offset);
- if ( unchecked(_length + offset) < _origin || tempPosition < _origin )
- throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin"));
- _position = tempPosition;
- break;
- }
- default:
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidSeekOrigin"));
+ throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_StreamLength);
+ switch (loc)
+ {
+ case SeekOrigin.Begin:
+ {
+ int tempPosition = unchecked(_origin + (int)offset);
+ if (offset < 0 || tempPosition < _origin)
+ throw new IOException(SR.IO_SeekBeforeBegin);
+ _position = tempPosition;
+ break;
+ }
+ case SeekOrigin.Current:
+ {
+ int tempPosition = unchecked(_position + (int)offset);
+ if (unchecked(_position + offset) < _origin || tempPosition < _origin)
+ throw new IOException(SR.IO_SeekBeforeBegin);
+ _position = tempPosition;
+ break;
+ }
+ case SeekOrigin.End:
+ {
+ int tempPosition = unchecked(_length + (int)offset);
+ if (unchecked(_length + offset) < _origin || tempPosition < _origin)
+ throw new IOException(SR.IO_SeekBeforeBegin);
+ _position = tempPosition;
+ break;
+ }
+ default:
+ throw new ArgumentException(SR.Argument_InvalidSeekOrigin);
}
Debug.Assert(_position >= 0, "_position >= 0");
return _position;
}
-
+
// Sets the length of the stream to a given value. The new
// value must be nonnegative and less than the space remaining in
// the array, Int32.MaxValue - origin
@@ -513,9 +558,11 @@ namespace System.IO {
// the stream is made longer than the maximum possible length of the
// array (Int32.MaxValue).
//
- public override void SetLength(long value) {
- if (value < 0 || value > Int32.MaxValue) {
- throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_StreamLength"));
+ public override void SetLength(long value)
+ {
+ if (value < 0 || value > Int32.MaxValue)
+ {
+ throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_StreamLength);
}
Contract.Ensures(_length - _origin == value);
Contract.EndContractBlock();
@@ -523,8 +570,9 @@ namespace System.IO {
// Origin wasn't publicly exposed above.
Debug.Assert(MemStreamMaxLength == Int32.MaxValue); // Check parameter validation logic in this method if this fails.
- if (value > (Int32.MaxValue - _origin)) {
- throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_StreamLength"));
+ if (value > (Int32.MaxValue - _origin))
+ {
+ throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_StreamLength);
}
int newLength = _origin + (int)value;
@@ -533,25 +581,26 @@ namespace System.IO {
Array.Clear(_buffer, _length, newLength - _length);
_length = newLength;
if (_position > newLength) _position = newLength;
-
}
-
- public virtual byte[] ToArray() {
+
+ public virtual byte[] ToArray()
+ {
BCLDebug.Perf(_exposable, "MemoryStream::GetBuffer will let you avoid a copy.");
byte[] copy = new byte[_length - _origin];
Buffer.InternalBlockCopy(_buffer, _origin, copy, 0, _length - _origin);
return copy;
}
-
- public override void Write(byte[] buffer, int offset, int count) {
- if (buffer==null)
- throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
+
+ public override void Write(byte[] buffer, int offset, int count)
+ {
+ if (buffer == null)
+ throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (offset < 0)
- throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
- throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
+ throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock();
if (!_isOpen) __Error.StreamIsClosed();
@@ -560,11 +609,13 @@ namespace System.IO {
int i = _position + count;
// Check for overflow
if (i < 0)
- throw new IOException(Environment.GetResourceString("IO.IO_StreamTooLong"));
+ throw new IOException(SR.IO_StreamTooLong);
- if (i > _length) {
+ if (i > _length)
+ {
bool mustZero = _position > _length;
- if (i > _capacity) {
+ if (i > _capacity)
+ {
bool allocatedNewArray = EnsureCapacity(i);
if (allocatedNewArray)
mustZero = false;
@@ -582,23 +633,22 @@ namespace System.IO {
else
Buffer.InternalBlockCopy(buffer, offset, _buffer, _position, count);
_position = i;
-
}
public override Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (buffer == null)
- throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
+ throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (offset < 0)
- throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
- throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
+ throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock(); // contract validation copied from Write(...)
// If cancellation is already requested, bail early
- if (cancellationToken.IsCancellationRequested)
+ if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled(cancellationToken);
try
@@ -616,14 +666,17 @@ namespace System.IO {
}
}
- public override void WriteByte(byte value) {
+ public override void WriteByte(byte value)
+ {
if (!_isOpen) __Error.StreamIsClosed();
EnsureWriteable();
-
- if (_position >= _length) {
+
+ if (_position >= _length)
+ {
int newLength = _position + 1;
bool mustZero = _position > _length;
- if (newLength >= _capacity) {
+ if (newLength >= _capacity)
+ {
bool allocatedNewArray = EnsureCapacity(newLength);
if (allocatedNewArray)
mustZero = false;
@@ -633,13 +686,13 @@ namespace System.IO {
_length = newLength;
}
_buffer[_position++] = value;
-
}
-
+
// Writes this MemoryStream to another stream.
- public virtual void WriteTo(Stream stream) {
- if (stream==null)
- throw new ArgumentNullException(nameof(stream), Environment.GetResourceString("ArgumentNull_Stream"));
+ public virtual void WriteTo(Stream stream)
+ {
+ if (stream == null)
+ throw new ArgumentNullException(nameof(stream), SR.ArgumentNull_Stream);
Contract.EndContractBlock();
if (!_isOpen) __Error.StreamIsClosed();
diff --git a/src/mscorlib/src/System/IO/PathTooLongException.cs b/src/mscorlib/src/System/IO/PathTooLongException.cs
deleted file mode 100644
index a84fdfb..0000000
--- a/src/mscorlib/src/System/IO/PathTooLongException.cs
+++ /dev/null
@@ -1,43 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-/*============================================================
-**
-**
-**
-**
-**
-** Purpose: Exception for paths and/or filenames that are
-** too long.
-**
-**
-===========================================================*/
-
-using System;
-using System.Runtime.Serialization;
-
-namespace System.IO {
-
- [Serializable]
- public class PathTooLongException : IOException
- {
- public PathTooLongException()
- : base(Environment.GetResourceString("IO.PathTooLong")) {
- SetErrorCode(__HResults.COR_E_PATHTOOLONG);
- }
-
- public PathTooLongException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_PATHTOOLONG);
- }
-
- public PathTooLongException(String message, Exception innerException)
- : base(message, innerException) {
- SetErrorCode(__HResults.COR_E_PATHTOOLONG);
- }
-
- protected PathTooLongException(SerializationInfo info, StreamingContext context) : base (info, context) {
- }
- }
-}
diff --git a/src/mscorlib/src/System/IO/PinnedBufferMemoryStream.cs b/src/mscorlib/src/System/IO/PinnedBufferMemoryStream.cs
index 2cbd14f..284cd92 100644
--- a/src/mscorlib/src/System/IO/PinnedBufferMemoryStream.cs
+++ b/src/mscorlib/src/System/IO/PinnedBufferMemoryStream.cs
@@ -13,19 +13,21 @@
**
**
===========================================================*/
+
using System;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Diagnostics.Contracts;
-namespace System.IO {
+namespace System.IO
+{
internal sealed unsafe class PinnedBufferMemoryStream : UnmanagedMemoryStream
{
private byte[] _array;
private GCHandle _pinningHandle;
// The new inheritance model requires a Critical default ctor since base (UnmanagedMemoryStream) has one
- private PinnedBufferMemoryStream():base(){}
+ private PinnedBufferMemoryStream() : base() { }
internal PinnedBufferMemoryStream(byte[] array)
{
@@ -33,7 +35,8 @@ namespace System.IO {
int len = array.Length;
// Handle 0 length byte arrays specially.
- if (len == 0) {
+ if (len == 0)
+ {
array = new byte[1];
len = 0;
}
@@ -42,7 +45,7 @@ namespace System.IO {
_pinningHandle = new GCHandle(array, GCHandleType.Pinned);
// Now the byte[] is pinned for the lifetime of this instance.
// But I also need to get a pointer to that block of memory...
- fixed(byte* ptr = &_array[0])
+ fixed (byte* ptr = &_array[0])
Initialize(ptr, len, len, FileAccess.Read);
}
@@ -53,14 +56,16 @@ namespace System.IO {
protected override void Dispose(bool disposing)
{
- if (_isOpen) {
+ if (_isOpen)
+ {
_pinningHandle.Free();
_isOpen = false;
}
#if _DEBUG
// To help track down lifetime issues on checked builds, force
//a full GC here.
- if (disposing) {
+ if (disposing)
+ {
GC.Collect();
GC.WaitForPendingFinalizers();
}
diff --git a/src/mscorlib/src/System/IO/SearchOption.cs b/src/mscorlib/src/System/IO/SearchOption.cs
index e2f761c..75909d7 100644
--- a/src/mscorlib/src/System/IO/SearchOption.cs
+++ b/src/mscorlib/src/System/IO/SearchOption.cs
@@ -18,9 +18,10 @@
using System;
-namespace System.IO {
+namespace System.IO
+{
[Serializable]
- public enum SearchOption
+ internal enum SearchOption
{
// Include only the current directory in the search operation
TopDirectoryOnly,
diff --git a/src/mscorlib/src/System/IO/SeekOrigin.cs b/src/mscorlib/src/System/IO/SeekOrigin.cs
deleted file mode 100644
index bff49e6..0000000
--- a/src/mscorlib/src/System/IO/SeekOrigin.cs
+++ /dev/null
@@ -1,31 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-/*============================================================
-**
-** Enum: SeekOrigin
-**
-**
-**
-**
-** Purpose: Enum describing locations in a stream you could
-** seek relative to.
-**
-**
-===========================================================*/
-
-using System;
-
-namespace System.IO {
- // Provides seek reference points. To seek to the end of a stream,
- // call stream.Seek(0, SeekOrigin.End).
- [Serializable]
- public enum SeekOrigin
- {
- // These constants match Win32's FILE_BEGIN, FILE_CURRENT, and FILE_END
- Begin = 0,
- Current = 1,
- End = 2,
- }
-}
diff --git a/src/mscorlib/src/System/IO/Stream.cs b/src/mscorlib/src/System/IO/Stream.cs
index 790f0a0..92fe374 100644
--- a/src/mscorlib/src/System/IO/Stream.cs
+++ b/src/mscorlib/src/System/IO/Stream.cs
@@ -14,6 +14,7 @@
**
**
===========================================================*/
+
using System;
using System.Buffers;
using System.Threading;
@@ -27,10 +28,11 @@ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Reflection;
-namespace System.IO {
+namespace System.IO
+{
[Serializable]
- public abstract class Stream : MarshalByRefObject, IDisposable {
-
+ public abstract class Stream : MarshalByRefObject, IDisposable
+ {
public static readonly Stream Null = new NullStream();
//We pick a value that is the largest multiple of 4096 that is still smaller than the large object heap threshold (85K).
@@ -52,55 +54,68 @@ namespace System.IO {
return LazyInitializer.EnsureInitialized(ref _asyncActiveSemaphore, () => new SemaphoreSlim(1, 1));
}
- public abstract bool CanRead {
+ public abstract bool CanRead
+ {
[Pure]
get;
}
// If CanSeek is false, Position, Seek, Length, and SetLength should throw.
- public abstract bool CanSeek {
+ public abstract bool CanSeek
+ {
[Pure]
get;
}
- public virtual bool CanTimeout {
+ public virtual bool CanTimeout
+ {
[Pure]
- get {
+ get
+ {
return false;
}
}
-
- public abstract bool CanWrite {
+
+ public abstract bool CanWrite
+ {
[Pure]
get;
}
- public abstract long Length {
+ public abstract long Length
+ {
get;
}
- public abstract long Position {
+ public abstract long Position
+ {
get;
set;
}
- public virtual int ReadTimeout {
- get {
+ public virtual int ReadTimeout
+ {
+ get
+ {
Contract.Ensures(Contract.Result<int>() >= 0);
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_TimeoutsNotSupported"));
+ throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported);
}
- set {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_TimeoutsNotSupported"));
+ set
+ {
+ throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported);
}
}
- public virtual int WriteTimeout {
- get {
+ public virtual int WriteTimeout
+ {
+ get
+ {
Contract.Ensures(Contract.Result<int>() >= 0);
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_TimeoutsNotSupported"));
+ throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported);
}
- set {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_TimeoutsNotSupported"));
+ set
+ {
+ throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported);
}
}
@@ -127,7 +142,7 @@ namespace System.IO {
// because it would be a breaking change if the stream's override didn't throw before,
// or in a different order. So for simplicity, we just set the bufferSize to 1
// (not 0 since the default implementation throws for 0) and forward to the virtual method.
- bufferSize = 1;
+ bufferSize = 1;
}
else
{
@@ -295,7 +310,7 @@ namespace System.IO {
}
internal IAsyncResult BeginReadInternal(
- byte[] buffer, int offset, int count, AsyncCallback callback, Object state,
+ byte[] buffer, int offset, int count, AsyncCallback callback, Object state,
bool serializeAsynchronously, bool apm)
{
Contract.Ensures(Contract.Result<IAsyncResult>() != null);
@@ -341,7 +356,7 @@ namespace System.IO {
{
thisTask._stream.FinishTrackingAsyncOperation();
}
-
+
thisTask.ClearBeginState(); // just to help alleviate some memory pressure
}
}, state, this, buffer, offset, count, callback);
@@ -352,7 +367,7 @@ namespace System.IO {
else
RunReadWriteTask(asyncResult);
-
+
return asyncResult; // return it
}
@@ -367,18 +382,18 @@ namespace System.IO {
if (readTask == null)
{
- throw new ArgumentException(Environment.GetResourceString("InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple"));
+ throw new ArgumentException(SR.InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple);
}
else if (readTask != asyncResult)
{
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple"));
+ throw new InvalidOperationException(SR.InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple);
}
else if (!readTask._isRead)
{
- throw new ArgumentException(Environment.GetResourceString("InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple"));
+ throw new ArgumentException(SR.InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple);
}
-
- try
+
+ try
{
return readTask.GetAwaiter().GetResult(); // block until completion, then get result / propagate any exception
}
@@ -437,12 +452,12 @@ namespace System.IO {
}
internal IAsyncResult BeginWriteInternal(
- byte[] buffer, int offset, int count, AsyncCallback callback, Object state,
+ byte[] buffer, int offset, int count, AsyncCallback callback, Object state,
bool serializeAsynchronously, bool apm)
{
Contract.Ensures(Contract.Result<IAsyncResult>() != null);
if (!CanWrite) __Error.WriteNotSupported();
-
+
// To avoid a race condition with a stream's position pointer & generating conditions
// with internal buffer indexes in our own streams that
// don't natively support async IO operations when there are multiple
@@ -472,7 +487,7 @@ namespace System.IO {
try
{
// Do the Write
- thisTask._stream.Write(thisTask._buffer, thisTask._offset, thisTask._count);
+ thisTask._stream.Write(thisTask._buffer, thisTask._offset, thisTask._count);
return 0; // not used, but signature requires a value be returned
}
finally
@@ -501,7 +516,7 @@ namespace System.IO {
private void RunReadWriteTaskWhenReady(Task asyncWaiter, ReadWriteTask readWriteTask)
{
Debug.Assert(readWriteTask != null); // Should be Contract.Requires, but CCRewrite is doing a poor job with
- // preconditions in async methods that await.
+ // preconditions in async methods that await.
Debug.Assert(asyncWaiter != null); // Ditto
// If the wait has already completed, run the task.
@@ -509,10 +524,11 @@ namespace System.IO {
{
Debug.Assert(asyncWaiter.IsRanToCompletion, "The semaphore wait should always complete successfully.");
RunReadWriteTask(readWriteTask);
- }
+ }
else // Otherwise, wait for our turn, and then run the task.
{
- asyncWaiter.ContinueWith((t, state) => {
+ asyncWaiter.ContinueWith((t, state) =>
+ {
Debug.Assert(t.IsRanToCompletion, "The semaphore wait should always complete successfully.");
var rwt = (ReadWriteTask)state;
rwt._stream.RunReadWriteTask(rwt); // RunReadWriteTask(readWriteTask);
@@ -536,32 +552,32 @@ namespace System.IO {
private void FinishTrackingAsyncOperation()
{
- _activeReadWriteTask = null;
+ _activeReadWriteTask = null;
Debug.Assert(_asyncActiveSemaphore != null, "Must have been initialized in order to get here.");
_asyncActiveSemaphore.Release();
}
public virtual void EndWrite(IAsyncResult asyncResult)
{
- if (asyncResult==null)
+ if (asyncResult == null)
throw new ArgumentNullException(nameof(asyncResult));
Contract.EndContractBlock();
var writeTask = _activeReadWriteTask;
if (writeTask == null)
{
- throw new ArgumentException(Environment.GetResourceString("InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple"));
+ throw new ArgumentException(SR.InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple);
}
else if (writeTask != asyncResult)
{
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple"));
+ throw new InvalidOperationException(SR.InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple);
}
else if (writeTask._isRead)
{
- throw new ArgumentException(Environment.GetResourceString("InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple"));
+ throw new ArgumentException(SR.InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple);
}
- try
+ try
{
writeTask.GetAwaiter().GetResult(); // block until completion, then propagate any exceptions
Debug.Assert(writeTask.Status == TaskStatus.RanToCompletion);
@@ -590,10 +606,10 @@ namespace System.IO {
// with a single allocation.
private sealed class ReadWriteTask : Task<int>, ITaskCompletionAction
{
- internal readonly bool _isRead;
+ internal readonly bool _isRead;
internal readonly bool _apm; // true if this is from Begin/EndXx; false if it's from XxAsync
internal Stream _stream;
- internal byte [] _buffer;
+ internal byte[] _buffer;
internal readonly int _offset;
internal readonly int _count;
private AsyncCallback _callback;
@@ -608,7 +624,7 @@ namespace System.IO {
public ReadWriteTask(
bool isRead,
bool apm,
- Func<object,int> function, object state,
+ Func<object, int> function, object state,
Stream stream, byte[] buffer, int offset, int count, AsyncCallback callback) :
base(function, state, CancellationToken.None, TaskCreationOptions.DenyChildAttach)
{
@@ -647,23 +663,23 @@ namespace System.IO {
}
private static ContextCallback s_invokeAsyncCallback;
-
+
void ITaskCompletionAction.Invoke(Task completingTask)
{
// Get the ExecutionContext. If there is none, just run the callback
// directly, passing in the completed task as the IAsyncResult.
// If there is one, process it with ExecutionContext.Run.
var context = _context;
- if (context == null)
+ if (context == null)
{
var callback = _callback;
_callback = null;
callback(completingTask);
}
- else
+ else
{
_context = null;
-
+
var invokeAsyncCallback = s_invokeAsyncCallback;
if (invokeAsyncCallback == null) s_invokeAsyncCallback = invokeAsyncCallback = InvokeAsyncCallback; // benign race condition
@@ -704,14 +720,14 @@ namespace System.IO {
// Otherwise, we need to wrap calls to Begin/EndWrite to ensure we use the derived type's functionality.
return TaskFactory<VoidTaskResult>.FromAsyncTrim(
- this, new ReadWriteParameters { Buffer=buffer, Offset=offset, Count=count },
+ this, new ReadWriteParameters { Buffer = buffer, Offset = offset, Count = count },
(stream, args, callback, state) => stream.BeginWrite(args.Buffer, args.Offset, args.Count, callback, state), // cached by compiler
(stream, asyncResult) => // cached by compiler
{
stream.EndWrite(asyncResult);
return default(VoidTaskResult);
});
- }
+ }
public abstract long Seek(long offset, SeekOrigin origin);
@@ -732,7 +748,7 @@ namespace System.IO {
byte[] oneByteArray = new byte[1];
int r = Read(oneByteArray, 0, 1);
- if (r==0)
+ if (r == 0)
return -1;
return oneByteArray[0];
}
@@ -751,20 +767,20 @@ namespace System.IO {
Write(oneByteArray, 0, 1);
}
- public static Stream Synchronized(Stream stream)
+ public static Stream Synchronized(Stream stream)
{
- if (stream==null)
+ if (stream == null)
throw new ArgumentNullException(nameof(stream));
Contract.Ensures(Contract.Result<Stream>() != null);
Contract.EndContractBlock();
if (stream is SyncStream)
return stream;
-
+
return new SyncStream(stream);
}
[Obsolete("Do not call or override this method.")]
- protected virtual void ObjectInvariant()
+ protected virtual void ObjectInvariant()
{
}
@@ -778,16 +794,19 @@ namespace System.IO {
// async requests outstanding, we will block the application's main
// thread and do the IO synchronously.
// This can't perform well - use a different approach.
- SynchronousAsyncResult asyncResult;
- try {
+ SynchronousAsyncResult asyncResult;
+ try
+ {
int numRead = Read(buffer, offset, count);
asyncResult = new SynchronousAsyncResult(numRead, state);
}
- catch (IOException ex) {
+ catch (IOException ex)
+ {
asyncResult = new SynchronousAsyncResult(ex, state, isWrite: false);
}
-
- if (callback != null) {
+
+ if (callback != null)
+ {
callback(asyncResult);
}
@@ -812,15 +831,18 @@ namespace System.IO {
// thread and do the IO synchronously.
// This can't perform well - use a different approach.
SynchronousAsyncResult asyncResult;
- try {
+ try
+ {
Write(buffer, offset, count);
asyncResult = new SynchronousAsyncResult(state);
}
- catch (IOException ex) {
+ catch (IOException ex)
+ {
asyncResult = new SynchronousAsyncResult(ex, state, isWrite: true);
}
- if (callback != null) {
+ if (callback != null)
+ {
callback(asyncResult);
}
@@ -835,45 +857,50 @@ namespace System.IO {
[Serializable]
private sealed class NullStream : Stream
{
- internal NullStream() {}
+ internal NullStream() { }
- public override bool CanRead {
+ public override bool CanRead
+ {
[Pure]
get { return true; }
}
- public override bool CanWrite {
+ public override bool CanWrite
+ {
[Pure]
get { return true; }
}
- public override bool CanSeek {
+ public override bool CanSeek
+ {
[Pure]
get { return true; }
}
- public override long Length {
+ public override long Length
+ {
get { return 0; }
}
- public override long Position {
+ public override long Position
+ {
get { return 0; }
- set {}
+ set { }
}
-
+
public override void CopyTo(Stream destination, int bufferSize)
{
StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
-
+
// After we validate arguments this is a nop.
}
-
+
public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken)
{
// Validate arguments here for compat, since previously this method
// was inherited from Stream (which did check its arguments).
StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
-
+
return cancellationToken.IsCancellationRequested ?
Task.FromCanceled(cancellationToken) :
Task.CompletedTask;
@@ -935,7 +962,7 @@ namespace System.IO {
public override Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
var nullReadTask = s_nullReadTask;
- if (nullReadTask == null)
+ if (nullReadTask == null)
s_nullReadTask = nullReadTask = new Task<int>(false, 0, (TaskCreationOptions)InternalTaskOptions.DoNotDispose, CancellationToken.None); // benign race condition
return nullReadTask;
}
@@ -971,11 +998,11 @@ namespace System.IO {
}
}
-
+
/// <summary>Used as the IAsyncResult object when using asynchronous IO methods on the base Stream class.</summary>
- internal sealed class SynchronousAsyncResult : IAsyncResult {
-
- private readonly Object _stateObject;
+ internal sealed class SynchronousAsyncResult : IAsyncResult
+ {
+ private readonly Object _stateObject;
private readonly bool _isWrite;
private ManualResetEvent _waitHandle;
private ExceptionDispatchInfo _exceptionInfo;
@@ -983,49 +1010,58 @@ namespace System.IO {
private bool _endXxxCalled;
private Int32 _bytesRead;
- internal SynchronousAsyncResult(Int32 bytesRead, Object asyncStateObject) {
+ internal SynchronousAsyncResult(Int32 bytesRead, Object asyncStateObject)
+ {
_bytesRead = bytesRead;
_stateObject = asyncStateObject;
//_isWrite = false;
}
- internal SynchronousAsyncResult(Object asyncStateObject) {
+ internal SynchronousAsyncResult(Object asyncStateObject)
+ {
_stateObject = asyncStateObject;
_isWrite = true;
}
- internal SynchronousAsyncResult(Exception ex, Object asyncStateObject, bool isWrite) {
+ internal SynchronousAsyncResult(Exception ex, Object asyncStateObject, bool isWrite)
+ {
_exceptionInfo = ExceptionDispatchInfo.Capture(ex);
_stateObject = asyncStateObject;
- _isWrite = isWrite;
+ _isWrite = isWrite;
}
- public bool IsCompleted {
+ public bool IsCompleted
+ {
// We never hand out objects of this type to the user before the synchronous IO completed:
get { return true; }
}
- public WaitHandle AsyncWaitHandle {
- get {
- return LazyInitializer.EnsureInitialized(ref _waitHandle, () => new ManualResetEvent(true));
+ public WaitHandle AsyncWaitHandle
+ {
+ get
+ {
+ return LazyInitializer.EnsureInitialized(ref _waitHandle, () => new ManualResetEvent(true));
}
}
- public Object AsyncState {
+ public Object AsyncState
+ {
get { return _stateObject; }
}
- public bool CompletedSynchronously {
+ public bool CompletedSynchronously
+ {
get { return true; }
}
- internal void ThrowIfError() {
+ internal void ThrowIfError()
+ {
if (_exceptionInfo != null)
_exceptionInfo.Throw();
- }
-
- internal static Int32 EndRead(IAsyncResult asyncResult) {
+ }
+ internal static Int32 EndRead(IAsyncResult asyncResult)
+ {
SynchronousAsyncResult ar = asyncResult as SynchronousAsyncResult;
if (ar == null || ar._isWrite)
__Error.WrongAsyncResult();
@@ -1039,8 +1075,8 @@ namespace System.IO {
return ar._bytesRead;
}
- internal static void EndWrite(IAsyncResult asyncResult) {
-
+ internal static void EndWrite(IAsyncResult asyncResult)
+ {
SynchronousAsyncResult ar = asyncResult as SynchronousAsyncResult;
if (ar == null || !ar._isWrite)
__Error.WrongAsyncResult();
@@ -1069,64 +1105,83 @@ namespace System.IO {
Contract.EndContractBlock();
_stream = stream;
}
-
- public override bool CanRead {
+
+ public override bool CanRead
+ {
[Pure]
get { return _stream.CanRead; }
}
-
- public override bool CanWrite {
+
+ public override bool CanWrite
+ {
[Pure]
get { return _stream.CanWrite; }
}
-
- public override bool CanSeek {
+
+ public override bool CanSeek
+ {
[Pure]
get { return _stream.CanSeek; }
}
-
- public override bool CanTimeout {
+
+ public override bool CanTimeout
+ {
[Pure]
- get {
+ get
+ {
return _stream.CanTimeout;
}
}
- public override long Length {
- get {
- lock(_stream) {
+ public override long Length
+ {
+ get
+ {
+ lock (_stream)
+ {
return _stream.Length;
}
}
}
-
- public override long Position {
- get {
- lock(_stream) {
+
+ public override long Position
+ {
+ get
+ {
+ lock (_stream)
+ {
return _stream.Position;
}
}
- set {
- lock(_stream) {
+ set
+ {
+ lock (_stream)
+ {
_stream.Position = value;
}
}
}
- public override int ReadTimeout {
- get {
+ public override int ReadTimeout
+ {
+ get
+ {
return _stream.ReadTimeout;
}
- set {
+ set
+ {
_stream.ReadTimeout = value;
}
}
- public override int WriteTimeout {
- get {
+ public override int WriteTimeout
+ {
+ get
+ {
return _stream.WriteTimeout;
}
- set {
+ set
+ {
_stream.WriteTimeout = value;
}
}
@@ -1135,48 +1190,54 @@ namespace System.IO {
// semantics for Close vs. Dispose, let's preserve that.
public override void Close()
{
- lock(_stream) {
- try {
+ lock (_stream)
+ {
+ try
+ {
_stream.Close();
}
- finally {
+ finally
+ {
base.Dispose(true);
}
}
}
-
+
protected override void Dispose(bool disposing)
{
- lock(_stream) {
- try {
+ lock (_stream)
+ {
+ try
+ {
// Explicitly pick up a potentially methodimpl'ed Dispose
if (disposing)
((IDisposable)_stream).Dispose();
}
- finally {
+ finally
+ {
base.Dispose(disposing);
}
}
}
-
+
public override void Flush()
{
- lock(_stream)
+ lock (_stream)
_stream.Flush();
}
-
+
public override int Read([In, Out]byte[] bytes, int offset, int count)
{
- lock(_stream)
+ lock (_stream)
return _stream.Read(bytes, offset, count);
}
-
+
public override int ReadByte()
{
- lock(_stream)
+ lock (_stream)
return _stream.ReadByte();
}
-
+
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
bool overridesBeginRead = _stream.HasOverriddenBeginEndRead();
@@ -1194,7 +1255,7 @@ namespace System.IO {
_stream.BeginReadInternal(buffer, offset, count, callback, state, serializeAsynchronously: true, apm: true);
}
}
-
+
public override int EndRead(IAsyncResult asyncResult)
{
if (asyncResult == null)
@@ -1202,34 +1263,34 @@ namespace System.IO {
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.EndContractBlock();
- lock(_stream)
+ lock (_stream)
return _stream.EndRead(asyncResult);
}
-
+
public override long Seek(long offset, SeekOrigin origin)
{
- lock(_stream)
+ lock (_stream)
return _stream.Seek(offset, origin);
}
-
+
public override void SetLength(long length)
{
- lock(_stream)
+ lock (_stream)
_stream.SetLength(length);
}
-
+
public override void Write(byte[] bytes, int offset, int count)
{
- lock(_stream)
+ lock (_stream)
_stream.Write(bytes, offset, count);
}
-
+
public override void WriteByte(byte b)
{
- lock(_stream)
+ lock (_stream)
_stream.WriteByte(b);
}
-
+
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
bool overridesBeginWrite = _stream.HasOverriddenBeginEndWrite();
@@ -1247,14 +1308,14 @@ namespace System.IO {
_stream.BeginWriteInternal(buffer, offset, count, callback, state, serializeAsynchronously: true, apm: true);
}
}
-
+
public override void EndWrite(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException(nameof(asyncResult));
Contract.EndContractBlock();
- lock(_stream)
+ lock (_stream)
_stream.EndWrite(asyncResult);
}
}
diff --git a/src/mscorlib/src/System/IO/StreamHelpers.CopyValidation.cs b/src/mscorlib/src/System/IO/StreamHelpers.CopyValidation.cs
deleted file mode 100644
index 8ff0e04..0000000
--- a/src/mscorlib/src/System/IO/StreamHelpers.CopyValidation.cs
+++ /dev/null
@@ -1,46 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-namespace System.IO
-{
- /// <summary>Provides methods to help in the implementation of Stream-derived types.</summary>
- internal static partial class StreamHelpers
- {
- /// <summary>Validate the arguments to CopyTo, as would Stream.CopyTo.</summary>
- public static void ValidateCopyToArgs(Stream source, Stream destination, int bufferSize)
- {
- if (destination == null)
- {
- throw new ArgumentNullException(nameof(destination));
- }
-
- if (bufferSize <= 0)
- {
- throw new ArgumentOutOfRangeException(nameof(bufferSize), bufferSize, Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
- }
-
- bool sourceCanRead = source.CanRead;
- if (!sourceCanRead && !source.CanWrite)
- {
- throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_StreamClosed"));
- }
-
- bool destinationCanWrite = destination.CanWrite;
- if (!destinationCanWrite && !destination.CanRead)
- {
- throw new ObjectDisposedException(nameof(destination), Environment.GetResourceString("ObjectDisposed_StreamClosed"));
- }
-
- if (!sourceCanRead)
- {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnreadableStream"));
- }
-
- if (!destinationCanWrite)
- {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnwritableStream"));
- }
- }
- }
-}
diff --git a/src/mscorlib/src/System/IO/StreamReader.cs b/src/mscorlib/src/System/IO/StreamReader.cs
index 6d50347..dfb928c 100644
--- a/src/mscorlib/src/System/IO/StreamReader.cs
+++ b/src/mscorlib/src/System/IO/StreamReader.cs
@@ -103,7 +103,7 @@ namespace System.IO
Task t = _asyncReadTask;
if (t != null && !t.IsCompleted)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_AsyncIOInProgress"));
+ throw new InvalidOperationException(SR.InvalidOperation_AsyncIOInProgress);
}
// StreamReader by default will ignore illegal UTF8 characters. We don't want to
@@ -149,9 +149,9 @@ namespace System.IO
if (stream == null || encoding == null)
throw new ArgumentNullException((stream == null ? nameof(stream) : nameof(encoding)));
if (!stream.CanRead)
- throw new ArgumentException(Environment.GetResourceString("Argument_StreamNotReadable"));
+ throw new ArgumentException(SR.Argument_StreamNotReadable);
if (bufferSize <= 0)
- throw new ArgumentOutOfRangeException(nameof(bufferSize), Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
+ throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedPosNum);
Contract.EndContractBlock();
Init(stream, encoding, detectEncodingFromByteOrderMarks, bufferSize, leaveOpen);
@@ -181,9 +181,9 @@ namespace System.IO
if (path==null || encoding==null)
throw new ArgumentNullException((path==null ? nameof(path) : nameof(encoding)));
if (path.Length==0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
+ throw new ArgumentException(SR.Argument_EmptyPath);
if (bufferSize <= 0)
- throw new ArgumentOutOfRangeException(nameof(bufferSize), Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
+ throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedPosNum);
Contract.EndContractBlock();
Stream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, DefaultFileStreamBufferSize, FileOptions.SequentialScan);
@@ -338,11 +338,11 @@ namespace System.IO
public override int Read([In, Out] char[] buffer, int index, int count)
{
if (buffer==null)
- throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
+ throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (index < 0 || count < 0)
- throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - index < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
+ throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock();
if (stream == null)
@@ -396,11 +396,11 @@ namespace System.IO
public override int ReadBlock([In, Out] char[] buffer, int index, int count)
{
if (buffer==null)
- throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
+ throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (index < 0 || count < 0)
- throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - index < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
+ throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock();
if (stream == null)
@@ -540,7 +540,7 @@ namespace System.IO
return sb.ToString();
}
- internal virtual int ReadBuffer() {
+ internal int ReadBuffer() {
charLen = 0;
charPos = 0;
@@ -777,16 +777,16 @@ namespace System.IO
private async Task<String> ReadLineAsyncInternal()
{
- if (CharPos_Prop == CharLen_Prop && (await ReadBufferAsync().ConfigureAwait(false)) == 0)
+ if (charPos == charLen && (await ReadBufferAsync().ConfigureAwait(false)) == 0)
return null;
StringBuilder sb = null;
do
{
- char[] tmpCharBuffer = CharBuffer_Prop;
- int tmpCharLen = CharLen_Prop;
- int tmpCharPos = CharPos_Prop;
+ char[] tmpCharBuffer = charBuffer;
+ int tmpCharLen = charLen;
+ int tmpCharPos = charPos;
int i = tmpCharPos;
do
@@ -809,13 +809,13 @@ namespace System.IO
s = new String(tmpCharBuffer, tmpCharPos, i - tmpCharPos);
}
- CharPos_Prop = tmpCharPos = i + 1;
+ charPos = tmpCharPos = i + 1;
if (ch == '\r' && (tmpCharPos < tmpCharLen || (await ReadBufferAsync().ConfigureAwait(false)) > 0))
{
- tmpCharPos = CharPos_Prop;
- if (CharBuffer_Prop[tmpCharPos] == '\n')
- CharPos_Prop = ++tmpCharPos;
+ tmpCharPos = charPos;
+ if (charBuffer[tmpCharPos] == '\n')
+ charPos = ++tmpCharPos;
}
return s;
@@ -857,14 +857,14 @@ namespace System.IO
private async Task<String> ReadToEndAsyncInternal()
{
// Call ReadBuffer, then pull data out of charBuffer.
- StringBuilder sb = AcquireSharedStringBuilder(CharLen_Prop - CharPos_Prop);
+ StringBuilder sb = AcquireSharedStringBuilder(charLen - charPos);
do
{
- int tmpCharPos = CharPos_Prop;
- sb.Append(CharBuffer_Prop, tmpCharPos, CharLen_Prop - tmpCharPos);
- CharPos_Prop = CharLen_Prop; // We consumed these characters
+ int tmpCharPos = charPos;
+ sb.Append(charBuffer, tmpCharPos, charLen - tmpCharPos);
+ charPos = charLen; // We consumed these characters
await ReadBufferAsync().ConfigureAwait(false);
- } while (CharLen_Prop > 0);
+ } while (charLen > 0);
return GetStringAndReleaseSharedStringBuilder(sb);
}
@@ -872,11 +872,11 @@ namespace System.IO
public override Task<int> ReadAsync(char[] buffer, int index, int count)
{
if (buffer==null)
- throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
+ throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (index < 0 || count < 0)
- throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - index < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
+ throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock();
// If we have been inherited into a subclass, the following implementation could be incorrect
@@ -899,7 +899,7 @@ namespace System.IO
internal override async Task<int> ReadAsyncInternal(char[] buffer, int index, int count)
{
- if (CharPos_Prop == CharLen_Prop && (await ReadBufferAsync().ConfigureAwait(false)) == 0)
+ if (charPos == charLen && (await ReadBufferAsync().ConfigureAwait(false)) == 0)
return 0;
int charsRead = 0;
@@ -908,24 +908,24 @@ namespace System.IO
// data read in, let's try writing directly to the user's buffer.
bool readToUserBuffer = false;
- Byte[] tmpByteBuffer = ByteBuffer_Prop;
- Stream tmpStream = Stream_Prop;
+ Byte[] tmpByteBuffer = byteBuffer;
+ Stream tmpStream = stream;
while (count > 0)
{
// n is the characters available in _charBuffer
- int n = CharLen_Prop - CharPos_Prop;
+ int n = charLen - charPos;
// charBuffer is empty, let's read from the stream
if (n == 0)
{
- CharLen_Prop = 0;
- CharPos_Prop = 0;
+ charLen = 0;
+ charPos = 0;
- if (!CheckPreamble_Prop)
- ByteLen_Prop = 0;
+ if (!_checkPreamble)
+ byteLen = 0;
- readToUserBuffer = count >= MaxCharsPerBuffer_Prop;
+ readToUserBuffer = count >= _maxCharsPerBuffer;
// We loop here so that we read in enough bytes to yield at least 1 char.
// We break out of the loop if the stream is blocked (EOF is reached).
@@ -933,10 +933,10 @@ namespace System.IO
{
Debug.Assert(n == 0);
- if (CheckPreamble_Prop)
+ if (_checkPreamble)
{
- Debug.Assert(BytePos_Prop <= Preamble_Prop.Length, "possible bug in _compressPreamble. Are two threads using this StreamReader at the same time?");
- int tmpBytePos = BytePos_Prop;
+ Debug.Assert(bytePos <= _preamble.Length, "possible bug in _compressPreamble. Are two threads using this StreamReader at the same time?");
+ int tmpBytePos = bytePos;
int len = await tmpStream.ReadAsync(tmpByteBuffer, tmpBytePos, tmpByteBuffer.Length - tmpBytePos).ConfigureAwait(false);
Debug.Assert(len >= 0, "Stream.Read returned a negative number! This is a bug in your stream class.");
@@ -944,42 +944,42 @@ namespace System.IO
{
// EOF but we might have buffered bytes from previous
// attempts to detect preamble that needs to be decoded now
- if (ByteLen_Prop > 0)
+ if (byteLen > 0)
{
if (readToUserBuffer)
{
- n = Decoder_Prop.GetChars(tmpByteBuffer, 0, ByteLen_Prop, buffer, index + charsRead);
- CharLen_Prop = 0; // StreamReader's buffer is empty.
+ n = decoder.GetChars(tmpByteBuffer, 0, byteLen, buffer, index + charsRead);
+ charLen = 0; // StreamReader's buffer is empty.
}
else
{
- n = Decoder_Prop.GetChars(tmpByteBuffer, 0, ByteLen_Prop, CharBuffer_Prop, 0);
- CharLen_Prop += n; // Number of chars in StreamReader's buffer.
+ n = decoder.GetChars(tmpByteBuffer, 0, byteLen, charBuffer, 0);
+ charLen += n; // Number of chars in StreamReader's buffer.
}
}
// How can part of the preamble yield any chars?
Debug.Assert(n == 0);
- IsBlocked_Prop = true;
+ _isBlocked = true;
break;
}
else
{
- ByteLen_Prop += len;
+ byteLen += len;
}
}
else
{
- Debug.Assert(BytePos_Prop == 0, "_bytePos can be non zero only when we are trying to _checkPreamble. Are two threads using this StreamReader at the same time?");
+ Debug.Assert(bytePos == 0, "_bytePos can be non zero only when we are trying to _checkPreamble. Are two threads using this StreamReader at the same time?");
- ByteLen_Prop = await tmpStream.ReadAsync(tmpByteBuffer, 0, tmpByteBuffer.Length).ConfigureAwait(false);
+ byteLen = await tmpStream.ReadAsync(tmpByteBuffer, 0, tmpByteBuffer.Length).ConfigureAwait(false);
- Debug.Assert(ByteLen_Prop >= 0, "Stream.Read returned a negative number! This is a bug in your stream class.");
+ Debug.Assert(byteLen >= 0, "Stream.Read returned a negative number! This is a bug in your stream class.");
- if (ByteLen_Prop == 0) // EOF
+ if (byteLen == 0) // EOF
{
- IsBlocked_Prop = true;
+ _isBlocked = true;
break;
}
}
@@ -987,7 +987,7 @@ namespace System.IO
// _isBlocked == whether we read fewer bytes than we asked for.
// Note we must check it here because CompressBuffer or
// DetectEncoding will change _byteLen.
- IsBlocked_Prop = (ByteLen_Prop < tmpByteBuffer.Length);
+ _isBlocked = (byteLen < tmpByteBuffer.Length);
// Check for preamble before detect encoding. This is not to override the
// user suppplied Encoding for the one we implicitly detect. The user could
@@ -998,33 +998,33 @@ namespace System.IO
continue;
// On the first call to ReadBuffer, if we're supposed to detect the encoding, do it.
- if (DetectEncoding_Prop && ByteLen_Prop >= 2)
+ if (_detectEncoding && byteLen >= 2)
{
DetectEncoding();
// DetectEncoding changes some buffer state. Recompute this.
- readToUserBuffer = count >= MaxCharsPerBuffer_Prop;
+ readToUserBuffer = count >= _maxCharsPerBuffer;
}
Debug.Assert(n == 0);
- CharPos_Prop = 0;
+ charPos = 0;
if (readToUserBuffer)
{
- n += Decoder_Prop.GetChars(tmpByteBuffer, 0, ByteLen_Prop, buffer, index + charsRead);
+ n += decoder.GetChars(tmpByteBuffer, 0, byteLen, buffer, index + charsRead);
// Why did the bytes yield no chars?
Debug.Assert(n > 0);
- CharLen_Prop = 0; // StreamReader's buffer is empty.
+ charLen = 0; // StreamReader's buffer is empty.
}
else
{
- n = Decoder_Prop.GetChars(tmpByteBuffer, 0, ByteLen_Prop, CharBuffer_Prop, 0);
+ n = decoder.GetChars(tmpByteBuffer, 0, byteLen, charBuffer, 0);
// Why did the bytes yield no chars?
Debug.Assert(n > 0);
- CharLen_Prop += n; // Number of chars in StreamReader's buffer.
+ charLen += n; // Number of chars in StreamReader's buffer.
}
} while (n == 0);
@@ -1038,8 +1038,8 @@ namespace System.IO
if (!readToUserBuffer)
{
- Buffer.InternalBlockCopy(CharBuffer_Prop, CharPos_Prop * 2, buffer, (index + charsRead) * 2, n * 2);
- CharPos_Prop += n;
+ Buffer.InternalBlockCopy(charBuffer, charPos * 2, buffer, (index + charsRead) * 2, n * 2);
+ charPos += n;
}
charsRead += n;
@@ -1048,7 +1048,7 @@ namespace System.IO
// This function shouldn't block for an indefinite amount of time,
// or reading from a network stream won't work right. If we got
// fewer bytes than we requested, then we want to break right here.
- if (IsBlocked_Prop)
+ if (_isBlocked)
break;
} // while (count > 0)
@@ -1058,11 +1058,11 @@ namespace System.IO
public override Task<int> ReadBlockAsync(char[] buffer, int index, int count)
{
if (buffer==null)
- throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
+ throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (index < 0 || count < 0)
- throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - index < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
+ throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock();
// If we have been inherited into a subclass, the following implementation could be incorrect
@@ -1083,113 +1083,50 @@ namespace System.IO
return task;
}
- #region Private properties for async method performance
- // Access to instance fields of MarshalByRefObject-derived types requires special JIT helpers that check
- // if the instance operated on is remote. This is optimised for fields on this but if a method is Async
- // and is thus lifted to a state machine type, access will be slow.
- // As a workaround, we either cache instance fields in locals or use properties to access such fields.
-
- private Int32 CharLen_Prop {
- get { return charLen; }
- set { charLen = value; }
- }
-
- private Int32 CharPos_Prop {
- get { return charPos; }
- set { charPos = value; }
- }
-
- private Int32 ByteLen_Prop {
- get { return byteLen; }
- set { byteLen = value; }
- }
-
- private Int32 BytePos_Prop {
- get { return bytePos; }
- set { bytePos = value; }
- }
-
- private Byte[] Preamble_Prop {
- get { return _preamble; }
- }
-
- private bool CheckPreamble_Prop {
- get { return _checkPreamble; }
- }
-
- private Decoder Decoder_Prop {
- get { return decoder; }
- }
-
- private bool DetectEncoding_Prop {
- get { return _detectEncoding; }
- }
-
- private Char[] CharBuffer_Prop {
- get { return charBuffer; }
- }
-
- private Byte[] ByteBuffer_Prop {
- get { return byteBuffer; }
- }
-
- private bool IsBlocked_Prop {
- get { return _isBlocked; }
- set { _isBlocked = value; }
- }
-
- private Stream Stream_Prop {
- get { return stream; }
- }
-
- private Int32 MaxCharsPerBuffer_Prop {
- get { return _maxCharsPerBuffer; }
- }
- #endregion Private properties for async method performance
private async Task<int> ReadBufferAsync()
{
- CharLen_Prop = 0;
- CharPos_Prop = 0;
- Byte[] tmpByteBuffer = ByteBuffer_Prop;
- Stream tmpStream = Stream_Prop;
+ charLen = 0;
+ charPos = 0;
+ Byte[] tmpByteBuffer = byteBuffer;
+ Stream tmpStream = stream;
- if (!CheckPreamble_Prop)
- ByteLen_Prop = 0;
+ if (!_checkPreamble)
+ byteLen = 0;
do {
- if (CheckPreamble_Prop) {
- Debug.Assert(BytePos_Prop <= Preamble_Prop.Length, "possible bug in _compressPreamble. Are two threads using this StreamReader at the same time?");
- int tmpBytePos = BytePos_Prop;
+ if (_checkPreamble) {
+ Debug.Assert(bytePos <= _preamble.Length, "possible bug in _compressPreamble. Are two threads using this StreamReader at the same time?");
+ int tmpBytePos = bytePos;
int len = await tmpStream.ReadAsync(tmpByteBuffer, tmpBytePos, tmpByteBuffer.Length - tmpBytePos).ConfigureAwait(false);
Debug.Assert(len >= 0, "Stream.Read returned a negative number! This is a bug in your stream class.");
if (len == 0) {
// EOF but we might have buffered bytes from previous
// attempt to detect preamble that needs to be decoded now
- if (ByteLen_Prop > 0)
+ if (byteLen > 0)
{
- CharLen_Prop += Decoder_Prop.GetChars(tmpByteBuffer, 0, ByteLen_Prop, CharBuffer_Prop, CharLen_Prop);
+ charLen += decoder.GetChars(tmpByteBuffer, 0, byteLen, charBuffer, charLen);
// Need to zero out the _byteLen after we consume these bytes so that we don't keep infinitely hitting this code path
- BytePos_Prop = 0; ByteLen_Prop = 0;
+ bytePos = 0; byteLen = 0;
}
- return CharLen_Prop;
+ return charLen;
}
- ByteLen_Prop += len;
+ byteLen += len;
}
else {
- Debug.Assert(BytePos_Prop == 0, "_bytePos can be non zero only when we are trying to _checkPreamble. Are two threads using this StreamReader at the same time?");
- ByteLen_Prop = await tmpStream.ReadAsync(tmpByteBuffer, 0, tmpByteBuffer.Length).ConfigureAwait(false);
- Debug.Assert(ByteLen_Prop >= 0, "Stream.Read returned a negative number! Bug in stream class.");
+ Debug.Assert(bytePos == 0, "_bytePos can be non zero only when we are trying to _checkPreamble. Are two threads using this StreamReader at the same time?");
+ byteLen = await tmpStream.ReadAsync(tmpByteBuffer, 0, tmpByteBuffer.Length).ConfigureAwait(false);
+ Debug.Assert(byteLen >= 0, "Stream.Read returned a negative number! Bug in stream class.");
- if (ByteLen_Prop == 0) // We're at EOF
- return CharLen_Prop;
+ if (byteLen == 0) // We're at EOF
+ return charLen;
}
// _isBlocked == whether we read fewer bytes than we asked for.
// Note we must check it here because CompressBuffer or
// DetectEncoding will change _byteLen.
- IsBlocked_Prop = (ByteLen_Prop < tmpByteBuffer.Length);
+ _isBlocked = (byteLen < tmpByteBuffer.Length);
// Check for preamble before detect encoding. This is not to override the
// user suppplied Encoding for the one we implicitly detect. The user could
@@ -1199,13 +1136,13 @@ namespace System.IO
// If we're supposed to detect the encoding and haven't done so yet,
// do it. Note this may need to be called more than once.
- if (DetectEncoding_Prop && ByteLen_Prop >= 2)
+ if (_detectEncoding && byteLen >= 2)
DetectEncoding();
- CharLen_Prop += Decoder_Prop.GetChars(tmpByteBuffer, 0, ByteLen_Prop, CharBuffer_Prop, CharLen_Prop);
- } while (CharLen_Prop == 0);
+ charLen += decoder.GetChars(tmpByteBuffer, 0, byteLen, charBuffer, charLen);
+ } while (charLen == 0);
- return CharLen_Prop;
+ return charLen;
}
#endregion
@@ -1254,12 +1191,6 @@ namespace System.IO
{
return String.Empty;
}
-
- internal override int ReadBuffer()
- {
- return 0;
- }
-
}
}
}
diff --git a/src/mscorlib/src/System/IO/TextReader.cs b/src/mscorlib/src/System/IO/TextReader.cs
index 15ba8fb..3da6859 100644
--- a/src/mscorlib/src/System/IO/TextReader.cs
+++ b/src/mscorlib/src/System/IO/TextReader.cs
@@ -93,13 +93,13 @@ namespace System.IO {
public virtual int Read([In, Out] char[] buffer, int index, int count)
{
if (buffer==null)
- throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
+ throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (index < 0)
- throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
- throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - index < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
+ throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.Ensures(Contract.Result<int>() <= Contract.OldValue(count));
Contract.EndContractBlock();
@@ -192,11 +192,11 @@ namespace System.IO {
public virtual Task<int> ReadAsync(char[] buffer, int index, int count)
{
if (buffer==null)
- throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
+ throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (index < 0 || count < 0)
- throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - index < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
+ throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock();
return ReadAsyncInternal(buffer, index, count);
@@ -221,11 +221,11 @@ namespace System.IO {
public virtual Task<int> ReadBlockAsync(char[] buffer, int index, int count)
{
if (buffer==null)
- throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
+ throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (index < 0 || count < 0)
- throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - index < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
+ throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock();
@@ -362,11 +362,11 @@ namespace System.IO {
public override Task<int> ReadBlockAsync(char[] buffer, int index, int count)
{
if (buffer==null)
- throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
+ throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (index < 0 || count < 0)
- throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - index < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
+ throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock();
@@ -377,11 +377,11 @@ namespace System.IO {
public override Task<int> ReadAsync(char[] buffer, int index, int count)
{
if (buffer==null)
- throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
+ throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (index < 0 || count < 0)
- throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - index < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
+ throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock();
return Task.FromResult(Read(buffer, index, count));
diff --git a/src/mscorlib/src/System/IO/UnmanagedMemoryAccessor.cs b/src/mscorlib/src/System/IO/UnmanagedMemoryAccessor.cs
index f3fd718..5f6f588 100644
--- a/src/mscorlib/src/System/IO/UnmanagedMemoryAccessor.cs
+++ b/src/mscorlib/src/System/IO/UnmanagedMemoryAccessor.cs
@@ -12,6 +12,7 @@
**
**
===========================================================*/
+
using System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
@@ -21,13 +22,13 @@ using Microsoft.Win32.SafeHandles;
using System.Diagnostics;
using System.Diagnostics.Contracts;
-namespace System.IO {
-
+namespace System.IO
+{
/// Perf notes: ReadXXX, WriteXXX (for basic types) acquire and release the
/// SafeBuffer pointer rather than relying on generic Read(T) from SafeBuffer because
/// this gives better throughput; benchmarks showed about 12-15% better.
- public class UnmanagedMemoryAccessor : IDisposable {
-
+ public class UnmanagedMemoryAccessor : IDisposable
+ {
private SafeBuffer _buffer;
private Int64 _offset;
[ContractPublicPropertyName("Capacity")]
@@ -37,7 +38,8 @@ namespace System.IO {
private bool _canRead;
private bool _canWrite;
- protected UnmanagedMemoryAccessor() {
+ protected UnmanagedMemoryAccessor()
+ {
_isOpen = false;
}
@@ -45,47 +47,61 @@ namespace System.IO {
// <SecurityKernel Critical="True" Ring="1">
// <ReferencesCritical Name="Method: Initialize(SafeBuffer, Int64, Int64, FileAccess):Void" Ring="1" />
// </SecurityKernel>
- public UnmanagedMemoryAccessor(SafeBuffer buffer, Int64 offset, Int64 capacity) {
+ public UnmanagedMemoryAccessor(SafeBuffer buffer, Int64 offset, Int64 capacity)
+ {
Initialize(buffer, offset, capacity, FileAccess.Read);
}
- public UnmanagedMemoryAccessor(SafeBuffer buffer, Int64 offset, Int64 capacity, FileAccess access) {
+ public UnmanagedMemoryAccessor(SafeBuffer buffer, Int64 offset, Int64 capacity, FileAccess access)
+ {
Initialize(buffer, offset, capacity, access);
}
- protected void Initialize(SafeBuffer buffer, Int64 offset, Int64 capacity, FileAccess access) {
- if (buffer == null) {
+ protected void Initialize(SafeBuffer buffer, Int64 offset, Int64 capacity, FileAccess access)
+ {
+ if (buffer == null)
+ {
throw new ArgumentNullException(nameof(buffer));
}
- if (offset < 0) {
- throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ if (offset < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
}
- if (capacity < 0) {
- throw new ArgumentOutOfRangeException(nameof(capacity), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ if (capacity < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_NeedNonNegNum);
}
- if (buffer.ByteLength < (UInt64)(offset + capacity)) {
- throw new ArgumentException(Environment.GetResourceString("Argument_OffsetAndCapacityOutOfBounds"));
+ if (buffer.ByteLength < (UInt64)(offset + capacity))
+ {
+ throw new ArgumentException(SR.Argument_OffsetAndCapacityOutOfBounds);
}
- if (access < FileAccess.Read || access > FileAccess.ReadWrite) {
+ if (access < FileAccess.Read || access > FileAccess.ReadWrite)
+ {
throw new ArgumentOutOfRangeException(nameof(access));
}
Contract.EndContractBlock();
- if (_isOpen) {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CalledTwice"));
+ if (_isOpen)
+ {
+ throw new InvalidOperationException(SR.InvalidOperation_CalledTwice);
}
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
buffer.AcquirePointer(ref pointer);
- if (((byte*)((Int64)pointer + offset + capacity)) < pointer) {
- throw new ArgumentException(Environment.GetResourceString("Argument_UnmanagedMemAccessorWrapAround"));
+ if (((byte*)((Int64)pointer + offset + capacity)) < pointer)
+ {
+ throw new ArgumentException(SR.Argument_UnmanagedMemAccessorWrapAround);
}
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
buffer.ReleasePointer();
}
}
@@ -102,38 +118,48 @@ namespace System.IO {
#endregion
- public Int64 Capacity {
- get {
- return _capacity;
+ public Int64 Capacity
+ {
+ get
+ {
+ return _capacity;
}
}
- public bool CanRead {
- get {
- return _isOpen && _canRead;
+ public bool CanRead
+ {
+ get
+ {
+ return _isOpen && _canRead;
}
}
- public bool CanWrite {
- get {
- return _isOpen && _canWrite;
+ public bool CanWrite
+ {
+ get
+ {
+ return _isOpen && _canWrite;
}
}
- protected virtual void Dispose(bool disposing) {
+ protected virtual void Dispose(bool disposing)
+ {
_isOpen = false;
}
- public void Dispose() {
+ public void Dispose()
+ {
Dispose(true);
GC.SuppressFinalize(this);
}
- protected bool IsOpen {
+ protected bool IsOpen
+ {
get { return _isOpen; }
}
- public bool ReadBoolean(Int64 position) {
+ public bool ReadBoolean(Int64 position)
+ {
int sizeOfType = sizeof(bool);
EnsureSafeToRead(position, sizeOfType);
@@ -141,40 +167,32 @@ namespace System.IO {
return b != 0;
}
- public byte ReadByte(Int64 position) {
+ public byte ReadByte(Int64 position)
+ {
int sizeOfType = sizeof(byte);
EnsureSafeToRead(position, sizeOfType);
return InternalReadByte(position);
}
- public char ReadChar(Int64 position) {
- int sizeOfType = sizeof(char);
- EnsureSafeToRead(position, sizeOfType);
-
- char result;
+ public char ReadChar(Int64 position)
+ {
+ EnsureSafeToRead(position, sizeof(char));
- unsafe {
+ char result;
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
- pointer += (_offset + position);
-
-#if ALIGN_ACCESS
- // check if pointer is aligned
- if (((int)pointer & (sizeOfType - 1)) == 0) {
-#endif
- result = *((char*)(pointer));
-#if ALIGN_ACCESS
- }
- else {
- result = (char)( *pointer | *(pointer + 1) << 8 ) ;
- }
-#endif
+ result = Unsafe.ReadUnaligned<char>(pointer + _offset + position);
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
@@ -184,33 +202,24 @@ namespace System.IO {
}
// See comment above.
- public Int16 ReadInt16(Int64 position) {
- int sizeOfType = sizeof(Int16);
- EnsureSafeToRead(position, sizeOfType);
+ public Int16 ReadInt16(Int64 position)
+ {
+ EnsureSafeToRead(position, sizeof(Int16));
Int16 result;
-
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
- pointer += (_offset + position);
-
-#if ALIGN_ACCESS
- // check if pointer is aligned
- if (((int)pointer & (sizeOfType - 1)) == 0) {
-#endif
- result = *((Int16*)(pointer));
-#if ALIGN_ACCESS
- }
- else {
- result = (Int16)( *pointer | *(pointer + 1) << 8 );
- }
-#endif
+ result = Unsafe.ReadUnaligned<Int16>(pointer + _offset + position);
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
@@ -220,32 +229,24 @@ namespace System.IO {
}
- public Int32 ReadInt32(Int64 position) {
- int sizeOfType = sizeof(Int32);
- EnsureSafeToRead(position, sizeOfType);
+ public Int32 ReadInt32(Int64 position)
+ {
+ EnsureSafeToRead(position, sizeof(Int32));
Int32 result;
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
- pointer += (_offset + position);
-
-#if ALIGN_ACCESS
- // check if pointer is aligned
- if (((int)pointer & (sizeOfType - 1)) == 0) {
-#endif
- result = *((Int32*)(pointer));
-#if ALIGN_ACCESS
- }
- else {
- result = (Int32)( *pointer | *(pointer + 1) << 8 | *(pointer + 2) << 16 | *(pointer + 3) << 24 );
- }
-#endif
+ result = Unsafe.ReadUnaligned<Int32>(pointer + _offset + position);
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
@@ -254,34 +255,24 @@ namespace System.IO {
return result;
}
- public Int64 ReadInt64(Int64 position) {
- int sizeOfType = sizeof(Int64);
- EnsureSafeToRead(position, sizeOfType);
+ public Int64 ReadInt64(Int64 position)
+ {
+ EnsureSafeToRead(position, sizeof(Int64));
Int64 result;
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
- pointer += (_offset + position);
-
-#if ALIGN_ACCESS
- // check if pointer is aligned
- if (((int)pointer & (sizeOfType - 1)) == 0) {
-#endif
- result = *((Int64*)(pointer));
-#if ALIGN_ACCESS
- }
- else {
- int lo = *pointer | *(pointer + 1) << 8 | *(pointer + 2) << 16 | *(pointer + 3) << 24;
- int hi = *(pointer + 4) | *(pointer + 5) << 8 | *(pointer + 6) << 16 | *(pointer + 7) << 24;
- result = (Int64)(((Int64)hi << 32) | (UInt32)lo);
- }
-#endif
- }
- finally {
- if (pointer != null) {
+ result = Unsafe.ReadUnaligned<Int64>(pointer + _offset + position);
+ }
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
@@ -290,28 +281,14 @@ namespace System.IO {
return result;
}
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- private unsafe Int32 UnsafeReadInt32(byte* pointer)
+ public Decimal ReadDecimal(Int64 position)
{
- Int32 result;
- // check if pointer is aligned
- if (((int)pointer & (sizeof(Int32) - 1)) == 0)
- {
- result = *((Int32*)pointer);
- }
- else
- {
- result = (Int32)(*(pointer) | *(pointer + 1) << 8 | *(pointer + 2) << 16 | *(pointer + 3) << 24);
- }
-
- return result;
- }
- public Decimal ReadDecimal(Int64 position) {
const int ScaleMask = 0x00FF0000;
const int SignMask = unchecked((int)0x80000000);
- int sizeOfType = sizeof(Decimal);
- EnsureSafeToRead(position, sizeOfType);
+ EnsureSafeToRead(position, sizeof(Decimal));
+
+ int lo, mid, hi, flags;
unsafe
{
@@ -319,23 +296,11 @@ namespace System.IO {
try
{
_buffer.AcquirePointer(ref pointer);
- pointer += (_offset + position);
-
- int lo = UnsafeReadInt32(pointer);
- int mid = UnsafeReadInt32(pointer + 4);
- int hi = UnsafeReadInt32(pointer + 8);
- int flags = UnsafeReadInt32(pointer + 12);
-
- // Check for invalid Decimal values
- if (!((flags & ~(SignMask | ScaleMask)) == 0 && (flags & ScaleMask) <= (28 << 16)))
- {
- throw new ArgumentException(Environment.GetResourceString("Arg_BadDecimal")); // Throw same Exception type as Decimal(int[]) ctor for compat
- }
-
- bool isNegative = (flags & SignMask) != 0;
- byte scale = (byte)(flags >> 16);
-
- return new decimal(lo, mid, hi, isNegative, scale);
+
+ lo = Unsafe.ReadUnaligned<Int32>(pointer + _offset + position);
+ mid = Unsafe.ReadUnaligned<Int32>(pointer + _offset + position + 4);
+ hi = Unsafe.ReadUnaligned<Int32>(pointer + _offset + position + 8);
+ flags = Unsafe.ReadUnaligned<Int32>(pointer + _offset + position + 12);
}
finally
{
@@ -345,35 +310,37 @@ namespace System.IO {
}
}
}
+
+ // Check for invalid Decimal values
+ if (!((flags & ~(SignMask | ScaleMask)) == 0 && (flags & ScaleMask) <= (28 << 16)))
+ {
+ throw new ArgumentException(SR.Arg_BadDecimal); // Throw same Exception type as Decimal(int[]) ctor for compat
+ }
+
+ bool isNegative = (flags & SignMask) != 0;
+ byte scale = (byte)(flags >> 16);
+
+ return new decimal(lo, mid, hi, isNegative, scale);
}
- public Single ReadSingle(Int64 position) {
- int sizeOfType = sizeof(Single);
- EnsureSafeToRead(position, sizeOfType);
+ public Single ReadSingle(Int64 position)
+ {
+ EnsureSafeToRead(position, sizeof(Single));
Single result;
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
- pointer += (_offset + position);
-
-#if ALIGN_ACCESS
- // check if pointer is aligned
- if (((int)pointer & (sizeOfType - 1)) == 0) {
-#endif
- result = BitConverter.Int32BitsToSingle(*((int*)(pointer)));
-#if ALIGN_ACCESS
- }
- else {
- UInt32 tempResult = (UInt32)( *pointer | *(pointer + 1) << 8 | *(pointer + 2) << 16 | *(pointer + 3) << 24 );
- result = *((float*)&tempResult);
- }
-#endif
+ result = Unsafe.ReadUnaligned<Single>(pointer + _offset + position);
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
@@ -382,37 +349,24 @@ namespace System.IO {
return result;
}
- public Double ReadDouble(Int64 position) {
- int sizeOfType = sizeof(Double);
- EnsureSafeToRead(position, sizeOfType);
+ public Double ReadDouble(Int64 position)
+ {
+ EnsureSafeToRead(position, sizeof(Double));
Double result;
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
- pointer += (_offset + position);
-
-#if ALIGN_ACCESS
- // check if pointer is aligned
- if (((int)pointer & (sizeOfType - 1)) == 0) {
-#endif
- result = BitConverter.Int64BitsToDouble(*((long*)(pointer)));
-#if ALIGN_ACCESS
- }
- else {
-
- UInt32 lo = (UInt32)( *pointer | *(pointer + 1) << 8 | *(pointer + 2) << 16 | *(pointer + 3) << 24 );
- UInt32 hi = (UInt32)( *(pointer + 4) | *(pointer + 5) << 8 | *(pointer + 6) << 16 | *(pointer + 7) << 24 );
- UInt64 tempResult = ((UInt64)hi) << 32 | lo;
- result = *((double*)&tempResult);
-
- }
-#endif
+ result = Unsafe.ReadUnaligned<Double>(pointer + _offset + position);
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
@@ -422,21 +376,25 @@ namespace System.IO {
}
[CLSCompliant(false)]
- public SByte ReadSByte(Int64 position) {
+ public SByte ReadSByte(Int64 position)
+ {
int sizeOfType = sizeof(SByte);
EnsureSafeToRead(position, sizeOfType);
SByte result;
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
- pointer += (_offset + position);
- result = *((SByte*)pointer);
+ result = *((SByte*)(pointer + _offset + position));
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
@@ -444,35 +402,26 @@ namespace System.IO {
return result;
}
-
+
[CLSCompliant(false)]
- public UInt16 ReadUInt16(Int64 position) {
- int sizeOfType = sizeof(UInt16);
- EnsureSafeToRead(position, sizeOfType);
+ public UInt16 ReadUInt16(Int64 position)
+ {
+ EnsureSafeToRead(position, sizeof(UInt16));
UInt16 result;
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
- pointer += (_offset + position);
-
-#if ALIGN_ACCESS
- // check if pointer is aligned
- if (((int)pointer & (sizeOfType - 1)) == 0) {
-#endif
- result = *((UInt16*)(pointer));
-#if ALIGN_ACCESS
- }
- else {
- result = (UInt16)( *pointer | *(pointer + 1) << 8 );
- }
-#endif
-
+ result = Unsafe.ReadUnaligned<UInt16>(pointer + _offset + position);
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
@@ -480,35 +429,26 @@ namespace System.IO {
return result;
}
-
+
[CLSCompliant(false)]
- public UInt32 ReadUInt32(Int64 position) {
- int sizeOfType = sizeof(UInt32);
- EnsureSafeToRead(position, sizeOfType);
+ public UInt32 ReadUInt32(Int64 position)
+ {
+ EnsureSafeToRead(position, sizeof(UInt32));
UInt32 result;
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
- pointer += (_offset + position);
-
-#if ALIGN_ACCESS
- // check if pointer is aligned
- if (((int)pointer & (sizeOfType - 1)) == 0) {
-#endif
- result = *((UInt32*)(pointer));
-#if ALIGN_ACCESS
- }
- else {
- result = (UInt32)( *pointer | *(pointer + 1) << 8 | *(pointer + 2) << 16 | *(pointer + 3) << 24 );
- }
-#endif
-
+ result = Unsafe.ReadUnaligned<UInt32>(pointer + _offset + position);
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
@@ -518,35 +458,24 @@ namespace System.IO {
}
[CLSCompliant(false)]
- public UInt64 ReadUInt64(Int64 position) {
- int sizeOfType = sizeof(UInt64);
- EnsureSafeToRead(position, sizeOfType);
+ public UInt64 ReadUInt64(Int64 position)
+ {
+ EnsureSafeToRead(position, sizeof(UInt64));
UInt64 result;
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
- pointer += (_offset + position);
-
-#if ALIGN_ACCESS
- // check if pointer is aligned
- if (((int)pointer & (sizeOfType - 1)) == 0) {
-#endif
- result = *((UInt64*)(pointer));
-#if ALIGN_ACCESS
- }
- else {
- UInt32 lo = (UInt32)( *pointer | *(pointer + 1) << 8 | *(pointer + 2) << 16 | *(pointer + 3) << 24 );
- UInt32 hi = (UInt32)( *(pointer + 4) | *(pointer + 5) << 8 | *(pointer + 6) << 16 | *(pointer + 7) << 24 );
- result = (UInt64)(((UInt64)hi << 32) | lo );
- }
-#endif
-
+ result = Unsafe.ReadUnaligned<UInt64>(pointer + _offset + position);
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
@@ -569,26 +498,33 @@ namespace System.IO {
// such, it is best to use the ReadXXX methods for small standard types such as ints, longs,
// bools, etc.
- public void Read<T>(Int64 position, out T structure) where T : struct {
- if (position < 0) {
- throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ public void Read<T>(Int64 position, out T structure) where T : struct
+ {
+ if (position < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_NeedNonNegNum);
}
Contract.EndContractBlock();
- if (!_isOpen) {
- throw new ObjectDisposedException("UnmanagedMemoryAccessor", Environment.GetResourceString("ObjectDisposed_ViewAccessorClosed"));
+ if (!_isOpen)
+ {
+ throw new ObjectDisposedException("UnmanagedMemoryAccessor", SR.ObjectDisposed_ViewAccessorClosed);
}
- if (!CanRead) {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_Reading"));
+ if (!CanRead)
+ {
+ throw new NotSupportedException(SR.NotSupported_Reading);
}
UInt32 sizeOfT = Marshal.SizeOfType(typeof(T));
- if (position > _capacity - sizeOfT) {
- if (position >= _capacity) {
- throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_PositionLessThanCapacityRequired"));
+ if (position > _capacity - sizeOfT)
+ {
+ if (position >= _capacity)
+ {
+ throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_PositionLessThanCapacityRequired);
}
- else {
- throw new ArgumentException(Environment.GetResourceString("Argument_NotEnoughBytesToRead", typeof(T).FullName), nameof(position));
+ else
+ {
+ throw new ArgumentException(SR.Format(SR.Argument_NotEnoughBytesToRead, typeof (T).FullName), nameof(position));
}
}
@@ -601,47 +537,60 @@ namespace System.IO {
// struct that contains reference members will most likely cause the runtime to AV. This
// is consistent with Marshal.PtrToStructure.
- public int ReadArray<T>(Int64 position, T[] array, Int32 offset, Int32 count) where T : struct {
- if (array == null) {
+ public int ReadArray<T>(Int64 position, T[] array, Int32 offset, Int32 count) where T : struct
+ {
+ if (array == null)
+ {
throw new ArgumentNullException(nameof(array), "Buffer cannot be null.");
}
- if (offset < 0) {
- throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ if (offset < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
}
- if (count < 0) {
- throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ if (count < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
}
- if (array.Length - offset < count) {
- throw new ArgumentException(Environment.GetResourceString("Argument_OffsetAndLengthOutOfBounds"));
+ if (array.Length - offset < count)
+ {
+ throw new ArgumentException(SR.Argument_OffsetAndLengthOutOfBounds);
}
Contract.EndContractBlock();
- if (!CanRead) {
- if (!_isOpen) {
- throw new ObjectDisposedException("UnmanagedMemoryAccessor", Environment.GetResourceString("ObjectDisposed_ViewAccessorClosed"));
+ if (!CanRead)
+ {
+ if (!_isOpen)
+ {
+ throw new ObjectDisposedException("UnmanagedMemoryAccessor", SR.ObjectDisposed_ViewAccessorClosed);
}
- else {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_Reading"));
+ else
+ {
+ throw new NotSupportedException(SR.NotSupported_Reading);
}
}
- if (position < 0) {
- throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ if (position < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_NeedNonNegNum);
}
UInt32 sizeOfT = Marshal.AlignedSizeOf<T>();
// only check position and ask for fewer Ts if count is too big
- if (position >= _capacity) {
- throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_PositionLessThanCapacityRequired"));
+ if (position >= _capacity)
+ {
+ throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_PositionLessThanCapacityRequired);
}
int n = count;
long spaceLeft = _capacity - position;
- if (spaceLeft < 0) {
+ if (spaceLeft < 0)
+ {
n = 0;
}
- else {
+ else
+ {
ulong spaceNeeded = (ulong)(sizeOfT * count);
- if ((ulong)spaceLeft < spaceNeeded) {
+ if ((ulong)spaceLeft < spaceNeeded)
+ {
n = (int)(spaceLeft / sizeOfT);
}
}
@@ -659,7 +608,8 @@ namespace System.IO {
// double, short, int, long, sbyte, float, ushort, uint, or ulong.
- public void Write(Int64 position, bool value) {
+ public void Write(Int64 position, bool value)
+ {
int sizeOfType = sizeof(bool);
EnsureSafeToWrite(position, sizeOfType);
@@ -667,73 +617,55 @@ namespace System.IO {
InternalWrite(position, b);
}
- public void Write(Int64 position, byte value) {
+ public void Write(Int64 position, byte value)
+ {
int sizeOfType = sizeof(byte);
EnsureSafeToWrite(position, sizeOfType);
InternalWrite(position, value);
}
- public void Write(Int64 position, char value) {
- int sizeOfType = sizeof(char);
- EnsureSafeToWrite(position, sizeOfType);
+ public void Write(Int64 position, char value)
+ {
+ EnsureSafeToWrite(position, sizeof(char));
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
- pointer += (_offset + position);
-
-#if ALIGN_ACCESS
- // check if pointer is aligned
- if (((int)pointer & (sizeOfType - 1)) == 0) {
-#endif
- *((char*)pointer) = value;
-#if ALIGN_ACCESS
- }
- else {
- *(pointer) = (byte)value;
- *(pointer+1) = (byte)(value >> 8);
- }
-#endif
+ Unsafe.WriteUnaligned<char>(pointer + _offset + position, value);
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
}
-
}
- public void Write(Int64 position, Int16 value) {
- int sizeOfType = sizeof(Int16);
- EnsureSafeToWrite(position, sizeOfType);
+ public void Write(Int64 position, Int16 value)
+ {
+ EnsureSafeToWrite(position, sizeof(Int16));
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
- pointer += (_offset + position);
-
-#if ALIGN_ACCESS
- // check if pointer is aligned
- if (((int)pointer & (sizeOfType - 1)) == 0) {
-#endif
- *((Int16*)pointer) = value;
-#if ALIGN_ACCESS
- }
- else {
- *(pointer) = (byte)value;
- *(pointer + 1) = (byte)(value >> 8);
- }
-#endif
+ Unsafe.WriteUnaligned<Int16>(pointer + _offset + position, value);
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
@@ -741,116 +673,73 @@ namespace System.IO {
}
- public void Write(Int64 position, Int32 value) {
- int sizeOfType = sizeof(Int32);
- EnsureSafeToWrite(position, sizeOfType);
+ public void Write(Int64 position, Int32 value)
+ {
+ EnsureSafeToWrite(position, sizeof(Int32));
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
- pointer += (_offset + position);
-
-#if ALIGN_ACCESS
- // check if pointer is aligned
- if (((int)pointer & (sizeOfType - 1)) == 0) {
-#endif
- *((Int32*)pointer) = value;
-#if ALIGN_ACCESS
- }
- else {
- *(pointer) = (byte)value;
- *(pointer + 1) = (byte)(value >> 8);
- *(pointer + 2) = (byte)(value >> 16);
- *(pointer + 3) = (byte)(value >> 24);
- }
-#endif
+ Unsafe.WriteUnaligned<Int32>(pointer + _offset + position, value);
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
}
}
- public void Write(Int64 position, Int64 value) {
- int sizeOfType = sizeof(Int64);
- EnsureSafeToWrite(position, sizeOfType);
+ public void Write(Int64 position, Int64 value)
+ {
+ EnsureSafeToWrite(position, sizeof(Int64));
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
- pointer += (_offset + position);
-#if ALIGN_ACCESS
- // check if pointer is aligned
- if (((int)pointer & (sizeOfType - 1)) == 0) {
-#endif
- *((Int64*)pointer) = value;
-#if ALIGN_ACCESS
- }
- else {
- *(pointer) = (byte)value;
- *(pointer + 1) = (byte)(value >> 8);
- *(pointer + 2) = (byte)(value >> 16);
- *(pointer + 3) = (byte)(value >> 24);
- *(pointer + 4) = (byte)(value >> 32);
- *(pointer + 5) = (byte)(value >> 40);
- *(pointer + 6) = (byte)(value >> 48);
- *(pointer + 7) = (byte)(value >> 56);
- }
-#endif
+ Unsafe.WriteUnaligned<Int64>(pointer + _offset + position, value);
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
}
}
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- private unsafe void UnsafeWriteInt32(byte* pointer, Int32 value)
+ public void Write(Int64 position, Decimal value)
{
- // check if pointer is aligned
- if (((int)pointer & (sizeof(Int32) - 1)) == 0)
- {
- *((Int32*)pointer) = value;
- }
- else
- {
- *(pointer) = (byte)value;
- *(pointer + 1) = (byte)(value >> 8);
- *(pointer + 2) = (byte)(value >> 16);
- *(pointer + 3) = (byte)(value >> 24);
- }
- }
-
- public void Write(Int64 position, Decimal value) {
- int sizeOfType = sizeof(Decimal);
- EnsureSafeToWrite(position, sizeOfType);
+ EnsureSafeToWrite(position, sizeof(Decimal));
unsafe
{
+ int* valuePtr = (int*)(&value);
+ int flags = *valuePtr;
+ int hi = *(valuePtr + 1);
+ int lo = *(valuePtr + 2);
+ int mid = *(valuePtr + 3);
+
byte* pointer = null;
try
{
_buffer.AcquirePointer(ref pointer);
- pointer += (_offset + position);
-
- int* valuePtr = (int*)(&value);
- int flags = *valuePtr;
- int hi = *(valuePtr + 1);
- int lo = *(valuePtr + 2);
- int mid = *(valuePtr + 3);
-
- UnsafeWriteInt32(pointer, lo);
- UnsafeWriteInt32(pointer + 4, mid);
- UnsafeWriteInt32(pointer + 8, hi);
- UnsafeWriteInt32(pointer + 12, flags);
+
+ Unsafe.WriteUnaligned<Int32>(pointer + _offset + position, lo);
+ Unsafe.WriteUnaligned<Int32>(pointer + _offset + position + 4, mid);
+ Unsafe.WriteUnaligned<Int32>(pointer + _offset + position + 8, hi);
+ Unsafe.WriteUnaligned<Int32>(pointer + _offset + position + 12, flags);
}
finally
{
@@ -862,74 +751,46 @@ namespace System.IO {
}
}
- public void Write(Int64 position, Single value) {
- int sizeOfType = sizeof(Single);
- EnsureSafeToWrite(position, sizeOfType);
+ public void Write(Int64 position, Single value)
+ {
+ EnsureSafeToWrite(position, sizeof(Single));
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
- pointer += (_offset + position);
-#if ALIGN_ACCESS
- // check if pointer is aligned
- if (((int)pointer & (sizeOfType - 1)) == 0) {
-#endif
- *((int*)pointer) = BitConverter.SingleToInt32Bits(value);
-#if ALIGN_ACCESS
- }
- else {
- UInt32 tmpValue = *(UInt32*)&value;
- *(pointer) = (byte)tmpValue;
- *(pointer + 1) = (byte)(tmpValue >> 8);
- *(pointer + 2) = (byte)(tmpValue >> 16);
- *(pointer + 3) = (byte)(tmpValue >> 24);
-
- }
-#endif
+ Unsafe.WriteUnaligned<Single>(pointer + _offset + position, value);
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
}
}
- public void Write(Int64 position, Double value) {
- int sizeOfType = sizeof(Double);
- EnsureSafeToWrite(position, sizeOfType);
+ public void Write(Int64 position, Double value)
+ {
+ EnsureSafeToWrite(position, sizeof(Double));
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
- pointer += (_offset + position);
-#if ALIGN_ACCESS
- // check if pointer is aligned
- if (((int)pointer & (sizeOfType - 1)) == 0) {
-#endif
- *((long*)pointer) = BitConverter.DoubleToInt64Bits(value);
-#if ALIGN_ACCESS
- }
- else {
- UInt64 tmpValue = *(UInt64 *)&value;
- *(pointer) = (byte) tmpValue;
- *(pointer + 1) = (byte) (tmpValue >> 8);
- *(pointer + 2) = (byte) (tmpValue >> 16);
- *(pointer + 3) = (byte) (tmpValue >> 24);
- *(pointer + 4) = (byte) (tmpValue >> 32);
- *(pointer + 5) = (byte) (tmpValue >> 40);
- *(pointer + 6) = (byte) (tmpValue >> 48);
- *(pointer + 7) = (byte) (tmpValue >> 56);
-
- }
-#endif
+ Unsafe.WriteUnaligned<Double>(pointer + _offset + position, value);
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
@@ -937,20 +798,23 @@ namespace System.IO {
}
[CLSCompliant(false)]
- public void Write(Int64 position, SByte value) {
- int sizeOfType = sizeof(SByte);
- EnsureSafeToWrite(position, sizeOfType);
+ public void Write(Int64 position, SByte value)
+ {
+ EnsureSafeToWrite(position, sizeof(SByte));
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
- pointer += (_offset + position);
- *((SByte*)pointer) = value;
+ *((SByte*)(pointer + _offset + position)) = value;
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
@@ -958,32 +822,24 @@ namespace System.IO {
}
[CLSCompliant(false)]
- public void Write(Int64 position, UInt16 value) {
+ public void Write(Int64 position, UInt16 value)
+ {
int sizeOfType = sizeof(UInt16);
EnsureSafeToWrite(position, sizeOfType);
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
- pointer += (_offset + position);
-
-#if ALIGN_ACCESS
- // check if pointer is aligned
- if (((int)pointer & (sizeOfType - 1)) == 0) {
-#endif
- *((UInt16*)pointer) = value;
-#if ALIGN_ACCESS
- }
- else {
- *(pointer) = (byte)value;
- *(pointer + 1) = (byte)(value >> 8);
- }
-#endif
+ Unsafe.WriteUnaligned<UInt16>(pointer + _offset + position, value);
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
@@ -991,35 +847,23 @@ namespace System.IO {
}
[CLSCompliant(false)]
- public void Write(Int64 position, UInt32 value) {
- int sizeOfType = sizeof(UInt32);
- EnsureSafeToWrite(position, sizeOfType);
+ public void Write(Int64 position, UInt32 value)
+ {
+ EnsureSafeToWrite(position, sizeof(UInt32));
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
- pointer += (_offset + position);
-
-#if ALIGN_ACCESS
- // check if pointer is aligned
- if (((int)pointer & (sizeOfType - 1)) == 0) {
-#endif
- *((UInt32*)pointer) = value;
-#if ALIGN_ACCESS
- }
- else {
- *(pointer) = (byte)value;
- *(pointer + 1) = (byte)(value >> 8);
- *(pointer + 2) = (byte)(value >> 16);
- *(pointer + 3) = (byte)(value >> 24);
- }
-#endif
-
+ Unsafe.WriteUnaligned<UInt32>(pointer + _offset + position, value);
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
@@ -1027,38 +871,23 @@ namespace System.IO {
}
[CLSCompliant(false)]
- public void Write(Int64 position, UInt64 value) {
- int sizeOfType = sizeof(UInt64);
- EnsureSafeToWrite(position, sizeOfType);
+ public void Write(Int64 position, UInt64 value)
+ {
+ EnsureSafeToWrite(position, sizeof(UInt64));
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
- pointer += (_offset + position);
-#if ALIGN_ACCESS
- // check if pointer is aligned
- if (((int)pointer & (sizeOfType - 1)) == 0) {
-#endif
- *((UInt64*)pointer) = value;
-#if ALIGN_ACCESS
- }
- else {
- *(pointer) = (byte)value;
- *(pointer + 1) = (byte)(value >> 8);
- *(pointer + 2) = (byte)(value >> 16);
- *(pointer + 3) = (byte)(value >> 24);
- *(pointer + 4) = (byte)(value >> 32);
- *(pointer + 5) = (byte)(value >> 40);
- *(pointer + 6) = (byte)(value >> 48);
- *(pointer + 7) = (byte)(value >> 56);
- }
-#endif
-
+ Unsafe.WriteUnaligned<UInt64>(pointer + _offset + position, value);
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
@@ -1070,26 +899,33 @@ namespace System.IO {
// though this is number is JIT and architecture dependent). As such, it is best to use
// the WriteX methods for small standard types such as ints, longs, bools, etc.
- public void Write<T>(Int64 position, ref T structure) where T : struct {
- if (position < 0) {
- throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ public void Write<T>(Int64 position, ref T structure) where T : struct
+ {
+ if (position < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_NeedNonNegNum);
}
Contract.EndContractBlock();
- if (!_isOpen) {
- throw new ObjectDisposedException("UnmanagedMemoryAccessor", Environment.GetResourceString("ObjectDisposed_ViewAccessorClosed"));
+ if (!_isOpen)
+ {
+ throw new ObjectDisposedException("UnmanagedMemoryAccessor", SR.ObjectDisposed_ViewAccessorClosed);
}
- if (!CanWrite) {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_Writing"));
+ if (!CanWrite)
+ {
+ throw new NotSupportedException(SR.NotSupported_Writing);
}
UInt32 sizeOfT = Marshal.SizeOfType(typeof(T));
- if (position > _capacity - sizeOfT) {
- if (position >= _capacity) {
- throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_PositionLessThanCapacityRequired"));
+ if (position > _capacity - sizeOfT)
+ {
+ if (position >= _capacity)
+ {
+ throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_PositionLessThanCapacityRequired);
}
- else {
- throw new ArgumentException(Environment.GetResourceString("Argument_NotEnoughBytesToWrite", typeof(T).FullName), nameof(position));
+ else
+ {
+ throw new ArgumentException(SR.Format(SR.Argument_NotEnoughBytesToWrite, typeof (T).FullName), nameof(position));
}
}
@@ -1099,52 +935,66 @@ namespace System.IO {
// Writes 'count' structs of type T from 'array' (starting at 'offset') into unmanaged memory.
- public void WriteArray<T>(Int64 position, T[] array, Int32 offset, Int32 count) where T : struct {
- if (array == null) {
+ public void WriteArray<T>(Int64 position, T[] array, Int32 offset, Int32 count) where T : struct
+ {
+ if (array == null)
+ {
throw new ArgumentNullException(nameof(array), "Buffer cannot be null.");
}
- if (offset < 0) {
- throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ if (offset < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
}
- if (count < 0) {
- throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ if (count < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
}
- if (array.Length - offset < count) {
- throw new ArgumentException(Environment.GetResourceString("Argument_OffsetAndLengthOutOfBounds"));
+ if (array.Length - offset < count)
+ {
+ throw new ArgumentException(SR.Argument_OffsetAndLengthOutOfBounds);
}
- if (position < 0) {
- throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ if (position < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_NeedNonNegNum);
}
- if (position >= Capacity) {
- throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_PositionLessThanCapacityRequired"));
+ if (position >= Capacity)
+ {
+ throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_PositionLessThanCapacityRequired);
}
Contract.EndContractBlock();
- if (!_isOpen) {
- throw new ObjectDisposedException("UnmanagedMemoryAccessor", Environment.GetResourceString("ObjectDisposed_ViewAccessorClosed"));
+ if (!_isOpen)
+ {
+ throw new ObjectDisposedException("UnmanagedMemoryAccessor", SR.ObjectDisposed_ViewAccessorClosed);
}
- if (!CanWrite) {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_Writing"));
+ if (!CanWrite)
+ {
+ throw new NotSupportedException(SR.NotSupported_Writing);
}
_buffer.WriteArray<T>((UInt64)(_offset + position), array, offset, count);
}
- private byte InternalReadByte(Int64 position) {
+ private byte InternalReadByte(Int64 position)
+ {
Debug.Assert(CanRead, "UMA not readable");
Debug.Assert(position >= 0, "position less than 0");
Debug.Assert(position <= _capacity - sizeof(byte), "position is greater than capacity - sizeof(byte)");
byte result;
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
- result = *((byte*)(pointer + _offset + position));
+ result = *(pointer + _offset + position);
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
@@ -1152,67 +1002,85 @@ namespace System.IO {
return result;
}
- private void InternalWrite(Int64 position, byte value) {
+ private void InternalWrite(Int64 position, byte value)
+ {
Debug.Assert(CanWrite, "UMA not writable");
Debug.Assert(position >= 0, "position less than 0");
Debug.Assert(position <= _capacity - sizeof(byte), "position is greater than capacity - sizeof(byte)");
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
- *((byte*)(pointer + _offset + position)) = value;
+ *(pointer + _offset + position) = value;
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
}
}
- private void EnsureSafeToRead(Int64 position, int sizeOfType) {
- if (!_isOpen) {
- throw new ObjectDisposedException("UnmanagedMemoryAccessor", Environment.GetResourceString("ObjectDisposed_ViewAccessorClosed"));
+ private void EnsureSafeToRead(Int64 position, int sizeOfType)
+ {
+ if (!_isOpen)
+ {
+ throw new ObjectDisposedException("UnmanagedMemoryAccessor", SR.ObjectDisposed_ViewAccessorClosed);
}
- if (!CanRead) {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_Reading"));
+ if (!CanRead)
+ {
+ throw new NotSupportedException(SR.NotSupported_Reading);
}
- if (position < 0) {
- throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ if (position < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_NeedNonNegNum);
}
Contract.EndContractBlock();
- if (position > _capacity - sizeOfType) {
- if (position >= _capacity) {
- throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_PositionLessThanCapacityRequired"));
+ if (position > _capacity - sizeOfType)
+ {
+ if (position >= _capacity)
+ {
+ throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_PositionLessThanCapacityRequired);
}
- else {
- throw new ArgumentException(Environment.GetResourceString("Argument_NotEnoughBytesToRead"), nameof(position));
+ else
+ {
+ throw new ArgumentException(SR.Argument_NotEnoughBytesToRead, nameof(position));
}
}
}
- private void EnsureSafeToWrite(Int64 position, int sizeOfType) {
- if (!_isOpen) {
- throw new ObjectDisposedException("UnmanagedMemoryAccessor", Environment.GetResourceString("ObjectDisposed_ViewAccessorClosed"));
+ private void EnsureSafeToWrite(Int64 position, int sizeOfType)
+ {
+ if (!_isOpen)
+ {
+ throw new ObjectDisposedException("UnmanagedMemoryAccessor", SR.ObjectDisposed_ViewAccessorClosed);
}
- if (!CanWrite) {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_Writing"));
+ if (!CanWrite)
+ {
+ throw new NotSupportedException(SR.NotSupported_Writing);
}
- if (position < 0) {
- throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ if (position < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_NeedNonNegNum);
}
Contract.EndContractBlock();
- if (position > _capacity - sizeOfType) {
- if (position >= _capacity) {
- throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_PositionLessThanCapacityRequired"));
+ if (position > _capacity - sizeOfType)
+ {
+ if (position >= _capacity)
+ {
+ throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_PositionLessThanCapacityRequired);
}
- else {
- throw new ArgumentException(Environment.GetResourceString("Argument_NotEnoughBytesToWrite", nameof(Byte)), nameof(position));
+ else
+ {
+ throw new ArgumentException(SR.Format(SR.Argument_NotEnoughBytesToWrite, nameof(Byte)), nameof(position));
}
}
}
-
}
}
diff --git a/src/mscorlib/src/System/IO/UnmanagedMemoryStream.cs b/src/mscorlib/src/System/IO/UnmanagedMemoryStream.cs
index 165b6d2..f21fe47 100644
--- a/src/mscorlib/src/System/IO/UnmanagedMemoryStream.cs
+++ b/src/mscorlib/src/System/IO/UnmanagedMemoryStream.cs
@@ -12,6 +12,7 @@
**
**
===========================================================*/
+
using System;
using System.Runtime;
using System.Runtime.CompilerServices;
@@ -20,11 +21,11 @@ using System.Security;
using System.Threading;
using System.Diagnostics;
using System.Diagnostics.Contracts;
-using System.Threading.Tasks;
-
+using System.Threading.Tasks;
-namespace System.IO {
+namespace System.IO
+{
/*
* This class is used to access a contiguous block of memory, likely outside
* the GC heap (or pinned in place in the GC heap, but a MemoryStream may
@@ -93,61 +94,76 @@ namespace System.IO {
private long _offset;
private FileAccess _access;
internal bool _isOpen;
- [NonSerialized]
+ [NonSerialized]
private Task<Int32> _lastReadTask; // The last successful task returned from ReadAsync
// Needed for subclasses that need to map a file, etc.
protected UnmanagedMemoryStream()
{
- unsafe {
+ unsafe
+ {
_mem = null;
}
_isOpen = false;
}
- public UnmanagedMemoryStream(SafeBuffer buffer, long offset, long length) {
+ public UnmanagedMemoryStream(SafeBuffer buffer, long offset, long length)
+ {
Initialize(buffer, offset, length, FileAccess.Read);
}
- public UnmanagedMemoryStream(SafeBuffer buffer, long offset, long length, FileAccess access) {
+ public UnmanagedMemoryStream(SafeBuffer buffer, long offset, long length, FileAccess access)
+ {
Initialize(buffer, offset, length, access);
}
- protected void Initialize(SafeBuffer buffer, long offset, long length, FileAccess access) {
- if (buffer == null) {
+ protected void Initialize(SafeBuffer buffer, long offset, long length, FileAccess access)
+ {
+ if (buffer == null)
+ {
throw new ArgumentNullException(nameof(buffer));
}
- if (offset < 0) {
- throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ if (offset < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
}
- if (length < 0) {
- throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ if (length < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NeedNonNegNum);
}
- if (buffer.ByteLength < (ulong)(offset + length)) {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidSafeBufferOffLen"));
+ if (buffer.ByteLength < (ulong)(offset + length))
+ {
+ throw new ArgumentException(SR.Argument_InvalidSafeBufferOffLen);
}
- if (access < FileAccess.Read || access > FileAccess.ReadWrite) {
+ if (access < FileAccess.Read || access > FileAccess.ReadWrite)
+ {
throw new ArgumentOutOfRangeException(nameof(access));
}
Contract.EndContractBlock();
- if (_isOpen) {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CalledTwice"));
+ if (_isOpen)
+ {
+ throw new InvalidOperationException(SR.InvalidOperation_CalledTwice);
}
// check for wraparound
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
buffer.AcquirePointer(ref pointer);
- if ( (pointer + offset + length) < pointer) {
- throw new ArgumentException(Environment.GetResourceString("ArgumentOutOfRange_UnmanagedMemStreamWrapAround"));
+ if ((pointer + offset + length) < pointer)
+ {
+ throw new ArgumentException(SR.ArgumentOutOfRange_UnmanagedMemStreamWrapAround);
}
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
buffer.ReleasePointer();
}
}
@@ -168,28 +184,28 @@ namespace System.IO {
}
[CLSCompliant(false)]
- public unsafe UnmanagedMemoryStream(byte* pointer, long length, long capacity, FileAccess access)
+ public unsafe UnmanagedMemoryStream(byte* pointer, long length, long capacity, FileAccess access)
{
Initialize(pointer, length, capacity, access);
}
[CLSCompliant(false)]
- protected unsafe void Initialize(byte* pointer, long length, long capacity, FileAccess access)
+ protected unsafe void Initialize(byte* pointer, long length, long capacity, FileAccess access)
{
if (pointer == null)
throw new ArgumentNullException(nameof(pointer));
if (length < 0 || capacity < 0)
- throw new ArgumentOutOfRangeException((length < 0) ? nameof(length) : nameof(capacity), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((length < 0) ? nameof(length) : nameof(capacity), SR.ArgumentOutOfRange_NeedNonNegNum);
if (length > capacity)
- throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_LengthGreaterThanCapacity"));
+ throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_LengthGreaterThanCapacity);
Contract.EndContractBlock();
// Check for wraparound.
- if (((byte*) ((long)pointer + capacity)) < pointer)
- throw new ArgumentOutOfRangeException(nameof(capacity), Environment.GetResourceString("ArgumentOutOfRange_UnmanagedMemStreamWrapAround"));
+ if (((byte*)((long)pointer + capacity)) < pointer)
+ throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_UnmanagedMemStreamWrapAround);
if (access < FileAccess.Read || access > FileAccess.ReadWrite)
- throw new ArgumentOutOfRangeException(nameof(access), Environment.GetResourceString("ArgumentOutOfRange_Enum"));
+ throw new ArgumentOutOfRangeException(nameof(access), SR.ArgumentOutOfRange_Enum);
if (_isOpen)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CalledTwice"));
+ throw new InvalidOperationException(SR.InvalidOperation_CalledTwice);
_mem = pointer;
_offset = 0;
@@ -199,17 +215,20 @@ namespace System.IO {
_isOpen = true;
}
- public override bool CanRead {
+ public override bool CanRead
+ {
[Pure]
get { return _isOpen && (_access & FileAccess.Read) != 0; }
}
- public override bool CanSeek {
+ public override bool CanSeek
+ {
[Pure]
get { return _isOpen; }
}
- public override bool CanWrite {
+ public override bool CanWrite
+ {
[Pure]
get { return _isOpen && (_access & FileAccess.Write) != 0; }
}
@@ -225,58 +244,66 @@ namespace System.IO {
base.Dispose(disposing);
}
- public override void Flush() {
+ public override void Flush()
+ {
if (!_isOpen) __Error.StreamIsClosed();
}
-
- public override Task FlushAsync(CancellationToken cancellationToken) {
-
- if (cancellationToken.IsCancellationRequested)
- return Task.FromCanceled(cancellationToken);
-
- try {
-
- Flush();
- return Task.CompletedTask;
-
- } catch(Exception ex) {
-
- return Task.FromException(ex);
- }
- }
-
-
- public override long Length {
- get {
+
+ public override Task FlushAsync(CancellationToken cancellationToken)
+ {
+ if (cancellationToken.IsCancellationRequested)
+ return Task.FromCanceled(cancellationToken);
+
+ try
+ {
+ Flush();
+ return Task.CompletedTask;
+ }
+ catch (Exception ex)
+ {
+ return Task.FromException(ex);
+ }
+ }
+
+
+ public override long Length
+ {
+ get
+ {
if (!_isOpen) __Error.StreamIsClosed();
return Interlocked.Read(ref _length);
}
}
- public long Capacity {
- get {
+ public long Capacity
+ {
+ get
+ {
if (!_isOpen) __Error.StreamIsClosed();
return _capacity;
}
}
- public override long Position {
- get {
+ public override long Position
+ {
+ get
+ {
if (!CanSeek) __Error.StreamIsClosed();
Contract.EndContractBlock();
return Interlocked.Read(ref _position);
}
- set {
+ set
+ {
if (value < 0)
- throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
if (!CanSeek) __Error.StreamIsClosed();
-
+
#if !BIT64
unsafe {
// On 32 bit machines, ensure we don't wrap around.
if (value > (long) Int32.MaxValue || _mem + value < _mem)
- throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_StreamLength"));
+ throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_StreamLength);
}
#endif
Interlocked.Exchange(ref _position, value);
@@ -284,54 +311,61 @@ namespace System.IO {
}
[CLSCompliant(false)]
- public unsafe byte* PositionPointer {
- get {
- if (_buffer != null) {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_UmsSafeBuffer"));
+ public unsafe byte* PositionPointer
+ {
+ get
+ {
+ if (_buffer != null)
+ {
+ throw new NotSupportedException(SR.NotSupported_UmsSafeBuffer);
}
// Use a temp to avoid a race
long pos = Interlocked.Read(ref _position);
if (pos > _capacity)
- throw new IndexOutOfRangeException(Environment.GetResourceString("IndexOutOfRange_UMSPosition"));
- byte * ptr = _mem + pos;
+ throw new IndexOutOfRangeException(SR.IndexOutOfRange_UMSPosition);
+ byte* ptr = _mem + pos;
if (!_isOpen) __Error.StreamIsClosed();
return ptr;
}
- set {
+ set
+ {
if (_buffer != null)
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_UmsSafeBuffer"));
+ throw new NotSupportedException(SR.NotSupported_UmsSafeBuffer);
if (!_isOpen) __Error.StreamIsClosed();
// Note: subtracting pointers returns an Int64. Working around
// to avoid hitting compiler warning CS0652 on this line.
if (new IntPtr(value - _mem).ToInt64() > UnmanagedMemStreamMaxLength)
- throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_UnmanagedMemStreamLength"));
+ throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_UnmanagedMemStreamLength);
if (value < _mem)
- throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin"));
+ throw new IOException(SR.IO_SeekBeforeBegin);
Interlocked.Exchange(ref _position, value - _mem);
}
}
- internal unsafe byte* Pointer {
- get {
+ internal unsafe byte* Pointer
+ {
+ get
+ {
if (_buffer != null)
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_UmsSafeBuffer"));
+ throw new NotSupportedException(SR.NotSupported_UmsSafeBuffer);
return _mem;
}
}
-
- public override int Read([In, Out] byte[] buffer, int offset, int count) {
- if (buffer==null)
- throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
+
+ public override int Read([In, Out] byte[] buffer, int offset, int count)
+ {
+ if (buffer == null)
+ throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (offset < 0)
- throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
- throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
+ throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock(); // Keep this in sync with contract validation in ReadAsync
if (!_isOpen) __Error.StreamIsClosed();
@@ -347,7 +381,7 @@ namespace System.IO {
if (n <= 0)
return 0;
- int nInt = (int) n; // Safe because n <= count, which is an Int32
+ int nInt = (int)n; // Safe because n <= count, which is an Int32
if (nInt < 0)
return 0; // _position could be beyond EOF
Debug.Assert(pos + nInt >= 0, "_position + n >= 0"); // len is less than 2^63 -1.
@@ -383,35 +417,37 @@ namespace System.IO {
Interlocked.Exchange(ref _position, pos + n);
return nInt;
}
-
- public override Task<Int32> ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) {
- if (buffer==null)
- throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
+
+ public override Task<Int32> ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)
+ {
+ if (buffer == null)
+ throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (offset < 0)
- throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
- throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
+ throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock(); // contract validation copied from Read(...)
-
- if (cancellationToken.IsCancellationRequested)
- return Task.FromCanceled<Int32>(cancellationToken);
-
- try {
-
- Int32 n = Read(buffer, offset, count);
+
+ if (cancellationToken.IsCancellationRequested)
+ return Task.FromCanceled<Int32>(cancellationToken);
+
+ try
+ {
+ Int32 n = Read(buffer, offset, count);
Task<Int32> t = _lastReadTask;
- return (t != null && t.Result == n) ? t : (_lastReadTask = Task.FromResult<Int32>(n));
-
- } catch (Exception ex) {
-
- Debug.Assert(! (ex is OperationCanceledException));
- return Task.FromException<Int32>(ex);
- }
- }
-
- public override int ReadByte() {
+ return (t != null && t.Result == n) ? t : (_lastReadTask = Task.FromResult<Int32>(n));
+ }
+ catch (Exception ex)
+ {
+ Debug.Assert(!(ex is OperationCanceledException));
+ return Task.FromException<Int32>(ex);
+ }
+ }
+
+ public override int ReadByte()
+ {
if (!_isOpen) __Error.StreamIsClosed();
if (!CanRead) __Error.ReadNotSupported();
@@ -421,56 +457,65 @@ namespace System.IO {
return -1;
Interlocked.Exchange(ref _position, pos + 1);
int result;
- if (_buffer != null) {
- unsafe {
+ if (_buffer != null)
+ {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
result = *(pointer + pos + _offset);
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
}
}
- else {
- unsafe {
+ else
+ {
+ unsafe
+ {
result = _mem[pos];
}
}
return result;
}
- public override long Seek(long offset, SeekOrigin loc) {
+ public override long Seek(long offset, SeekOrigin loc)
+ {
if (!_isOpen) __Error.StreamIsClosed();
if (offset > UnmanagedMemStreamMaxLength)
- throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_UnmanagedMemStreamLength"));
- switch(loc) {
- case SeekOrigin.Begin:
- if (offset < 0)
- throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin"));
- Interlocked.Exchange(ref _position, offset);
- break;
-
- case SeekOrigin.Current:
- long pos = Interlocked.Read(ref _position);
- if (offset + pos < 0)
- throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin"));
- Interlocked.Exchange(ref _position, offset + pos);
- break;
-
- case SeekOrigin.End:
- long len = Interlocked.Read(ref _length);
- if (len + offset < 0)
- throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin"));
- Interlocked.Exchange(ref _position, len + offset);
- break;
-
- default:
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidSeekOrigin"));
+ throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_UnmanagedMemStreamLength);
+ switch (loc)
+ {
+ case SeekOrigin.Begin:
+ if (offset < 0)
+ throw new IOException(SR.IO_SeekBeforeBegin);
+ Interlocked.Exchange(ref _position, offset);
+ break;
+
+ case SeekOrigin.Current:
+ long pos = Interlocked.Read(ref _position);
+ if (offset + pos < 0)
+ throw new IOException(SR.IO_SeekBeforeBegin);
+ Interlocked.Exchange(ref _position, offset + pos);
+ break;
+
+ case SeekOrigin.End:
+ long len = Interlocked.Read(ref _length);
+ if (len + offset < 0)
+ throw new IOException(SR.IO_SeekBeforeBegin);
+ Interlocked.Exchange(ref _position, len + offset);
+ break;
+
+ default:
+ throw new ArgumentException(SR.Argument_InvalidSeekOrigin);
}
long finalPos = Interlocked.Read(ref _position);
@@ -478,40 +523,45 @@ namespace System.IO {
return finalPos;
}
- public override void SetLength(long value) {
+ public override void SetLength(long value)
+ {
if (value < 0)
- throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException("length", SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
if (_buffer != null)
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_UmsSafeBuffer"));
+ throw new NotSupportedException(SR.NotSupported_UmsSafeBuffer);
if (!_isOpen) __Error.StreamIsClosed();
if (!CanWrite) __Error.WriteNotSupported();
if (value > _capacity)
- throw new IOException(Environment.GetResourceString("IO.IO_FixedCapacity"));
+ throw new IOException(SR.IO_FixedCapacity);
long pos = Interlocked.Read(ref _position);
long len = Interlocked.Read(ref _length);
- if (value > len) {
- unsafe {
- Buffer.ZeroMemory(_mem+len, value-len);
+ if (value > len)
+ {
+ unsafe
+ {
+ Buffer.ZeroMemory(_mem + len, value - len);
}
}
Interlocked.Exchange(ref _length, value);
- if (pos > value) {
+ if (pos > value)
+ {
Interlocked.Exchange(ref _position, value);
- }
+ }
}
- public override void Write(byte[] buffer, int offset, int count) {
- if (buffer==null)
- throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
+ public override void Write(byte[] buffer, int offset, int count)
+ {
+ if (buffer == null)
+ throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (offset < 0)
- throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
- throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
+ throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock(); // Keep contract validation in sync with WriteAsync(..)
if (!_isOpen) __Error.StreamIsClosed();
@@ -522,23 +572,28 @@ namespace System.IO {
long n = pos + count;
// Check for overflow
if (n < 0)
- throw new IOException(Environment.GetResourceString("IO.IO_StreamTooLong"));
+ throw new IOException(SR.IO_StreamTooLong);
- if (n > _capacity) {
- throw new NotSupportedException(Environment.GetResourceString("IO.IO_FixedCapacity"));
+ if (n > _capacity)
+ {
+ throw new NotSupportedException(SR.IO_FixedCapacity);
}
- if (_buffer == null) {
+ if (_buffer == null)
+ {
// Check to see whether we are now expanding the stream and must
// zero any memory in the middle.
- if (pos > len) {
- unsafe {
- Buffer.ZeroMemory(_mem+len, pos-len);
+ if (pos > len)
+ {
+ unsafe
+ {
+ Buffer.ZeroMemory(_mem + len, pos - len);
}
}
// set length after zeroing memory to avoid race condition of accessing unzeroed memory
- if (n > len) {
+ if (n > len)
+ {
Interlocked.Exchange(ref _length, n);
}
}
@@ -552,7 +607,7 @@ namespace System.IO {
long bytesLeft = _capacity - pos;
if (bytesLeft < count)
{
- throw new ArgumentException(Environment.GetResourceString("Arg_BufferTooSmall"));
+ throw new ArgumentException(SR.Arg_BufferTooSmall);
}
byte* pointer = null;
@@ -579,57 +634,62 @@ namespace System.IO {
Interlocked.Exchange(ref _position, n);
return;
}
-
- public override Task WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) {
-
- if (buffer==null)
- throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
+
+ public override Task WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)
+ {
+ if (buffer == null)
+ throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (offset < 0)
- throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
- throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
+ throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock(); // contract validation copied from Write(..)
-
- if (cancellationToken.IsCancellationRequested)
- return Task.FromCanceled(cancellationToken);
-
- try {
-
- Write(buffer, offset, count);
- return Task.CompletedTask;
-
- } catch (Exception ex) {
-
- Debug.Assert(! (ex is OperationCanceledException));
- return Task.FromException<Int32>(ex);
- }
- }
-
-
- public override void WriteByte(byte value) {
+
+ if (cancellationToken.IsCancellationRequested)
+ return Task.FromCanceled(cancellationToken);
+
+ try
+ {
+ Write(buffer, offset, count);
+ return Task.CompletedTask;
+ }
+ catch (Exception ex)
+ {
+ Debug.Assert(!(ex is OperationCanceledException));
+ return Task.FromException<Int32>(ex);
+ }
+ }
+
+
+ public override void WriteByte(byte value)
+ {
if (!_isOpen) __Error.StreamIsClosed();
if (!CanWrite) __Error.WriteNotSupported();
long pos = Interlocked.Read(ref _position); // Use a local to avoid a race condition
long len = Interlocked.Read(ref _length);
long n = pos + 1;
- if (pos >= len) {
+ if (pos >= len)
+ {
// Check for overflow
if (n < 0)
- throw new IOException(Environment.GetResourceString("IO.IO_StreamTooLong"));
-
+ throw new IOException(SR.IO_StreamTooLong);
+
if (n > _capacity)
- throw new NotSupportedException(Environment.GetResourceString("IO.IO_FixedCapacity"));
+ throw new NotSupportedException(SR.IO_FixedCapacity);
// Check to see whether we are now expanding the stream and must
// zero any memory in the middle.
// don't do if created from SafeBuffer
- if (_buffer == null) {
- if (pos > len) {
- unsafe {
- Buffer.ZeroMemory(_mem+len, pos-len);
+ if (_buffer == null)
+ {
+ if (pos > len)
+ {
+ unsafe
+ {
+ Buffer.ZeroMemory(_mem + len, pos - len);
}
}
@@ -638,24 +698,31 @@ namespace System.IO {
}
}
- if (_buffer != null) {
- unsafe {
+ if (_buffer != null)
+ {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
*(pointer + pos + _offset) = value;
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
}
}
- else {
- unsafe {
- _mem[pos] = value;
+ else
+ {
+ unsafe
+ {
+ _mem[pos] = value;
}
}
Interlocked.Exchange(ref _position, n);
diff --git a/src/mscorlib/src/System/IO/UnmanagedMemoryStreamWrapper.cs b/src/mscorlib/src/System/IO/UnmanagedMemoryStreamWrapper.cs
index 99b257e..86e4707 100644
--- a/src/mscorlib/src/System/IO/UnmanagedMemoryStreamWrapper.cs
+++ b/src/mscorlib/src/System/IO/UnmanagedMemoryStreamWrapper.cs
@@ -18,94 +18,117 @@ using System.Diagnostics.Contracts;
using System.Threading;
using System.Threading.Tasks;
-namespace System.IO {
+namespace System.IO
+{
// Needed for backwards compatibility with V1.x usages of the
// ResourceManager, where a MemoryStream is now returned as an
// UnmanagedMemoryStream from ResourceReader.
- internal sealed class UnmanagedMemoryStreamWrapper : MemoryStream {
+ internal sealed class UnmanagedMemoryStreamWrapper : MemoryStream
+ {
private UnmanagedMemoryStream _unmanagedStream;
-
- internal UnmanagedMemoryStreamWrapper(UnmanagedMemoryStream stream) {
+
+ internal UnmanagedMemoryStreamWrapper(UnmanagedMemoryStream stream)
+ {
_unmanagedStream = stream;
}
-
- public override bool CanRead {
+
+ public override bool CanRead
+ {
[Pure]
get { return _unmanagedStream.CanRead; }
}
-
- public override bool CanSeek {
+
+ public override bool CanSeek
+ {
[Pure]
get { return _unmanagedStream.CanSeek; }
}
-
- public override bool CanWrite {
+
+ public override bool CanWrite
+ {
[Pure]
get { return _unmanagedStream.CanWrite; }
}
-
+
protected override void Dispose(bool disposing)
{
- try {
+ try
+ {
if (disposing)
_unmanagedStream.Close();
}
- finally {
+ finally
+ {
base.Dispose(disposing);
}
}
-
- public override void Flush() {
+
+ public override void Flush()
+ {
_unmanagedStream.Flush();
}
-
- public override byte[] GetBuffer() {
- throw new UnauthorizedAccessException(Environment.GetResourceString("UnauthorizedAccess_MemStreamBuffer"));
+
+ public override byte[] GetBuffer()
+ {
+ throw new UnauthorizedAccessException(SR.UnauthorizedAccess_MemStreamBuffer);
}
- public override bool TryGetBuffer(out ArraySegment<byte> buffer) {
+ public override bool TryGetBuffer(out ArraySegment<byte> buffer)
+ {
buffer = default(ArraySegment<byte>);
return false;
}
- public override int Capacity {
- get {
- return (int) _unmanagedStream.Capacity;
+ public override int Capacity
+ {
+ get
+ {
+ return (int)_unmanagedStream.Capacity;
}
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- set {
- throw new IOException(Environment.GetResourceString("IO.IO_FixedCapacity"));
+ set
+ {
+ throw new IOException(SR.IO_FixedCapacity);
}
- }
-
- public override long Length {
- get {
+ }
+
+ public override long Length
+ {
+ get
+ {
return _unmanagedStream.Length;
}
}
- public override long Position {
- get {
+ public override long Position
+ {
+ get
+ {
return _unmanagedStream.Position;
}
- set {
+ set
+ {
_unmanagedStream.Position = value;
}
}
-
- public override int Read([In, Out] byte[] buffer, int offset, int count) {
+
+ public override int Read([In, Out] byte[] buffer, int offset, int count)
+ {
return _unmanagedStream.Read(buffer, offset, count);
}
-
- public override int ReadByte() {
+
+ public override int ReadByte()
+ {
return _unmanagedStream.ReadByte();
}
-
- public override long Seek(long offset, SeekOrigin loc) {
+
+ public override long Seek(long offset, SeekOrigin loc)
+ {
return _unmanagedStream.Seek(offset, loc);
}
- public unsafe override byte[] ToArray() {
+ public unsafe override byte[] ToArray()
+ {
if (!_unmanagedStream._isOpen) __Error.StreamIsClosed();
if (!_unmanagedStream.CanRead) __Error.ReadNotSupported();
@@ -113,31 +136,34 @@ namespace System.IO {
Buffer.Memcpy(buffer, 0, _unmanagedStream.Pointer, 0, (int)_unmanagedStream.Length);
return buffer;
}
-
- public override void Write(byte[] buffer, int offset, int count) {
+
+ public override void Write(byte[] buffer, int offset, int count)
+ {
_unmanagedStream.Write(buffer, offset, count);
}
-
- public override void WriteByte(byte value) {
+
+ public override void WriteByte(byte value)
+ {
_unmanagedStream.WriteByte(value);
}
-
+
// Writes this MemoryStream to another stream.
- public unsafe override void WriteTo(Stream stream) {
- if (stream==null)
- throw new ArgumentNullException(nameof(stream), Environment.GetResourceString("ArgumentNull_Stream"));
+ public unsafe override void WriteTo(Stream stream)
+ {
+ if (stream == null)
+ throw new ArgumentNullException(nameof(stream), SR.ArgumentNull_Stream);
Contract.EndContractBlock();
if (!_unmanagedStream._isOpen) __Error.StreamIsClosed();
if (!CanRead) __Error.ReadNotSupported();
byte[] buffer = ToArray();
-
+
stream.Write(buffer, 0, buffer.Length);
}
- public override void SetLength(Int64 value) {
-
+ public override void SetLength(Int64 value)
+ {
// This was probably meant to call _unmanagedStream.SetLength(value), but it was forgotten in V.4.0.
// Now this results in a call to the base which touches the underlying array which is never actually used.
// We cannot fix it due to compat now, but we should fix this at the next SxS release oportunity.
@@ -145,26 +171,26 @@ namespace System.IO {
}
- public override Task CopyToAsync(Stream destination, Int32 bufferSize, CancellationToken cancellationToken) {
-
+ public override Task CopyToAsync(Stream destination, Int32 bufferSize, CancellationToken cancellationToken)
+ {
// The parameter checks must be in sync with the base version:
if (destination == null)
throw new ArgumentNullException(nameof(destination));
-
+
if (bufferSize <= 0)
- throw new ArgumentOutOfRangeException(nameof(bufferSize), Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
+ throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedPosNum);
if (!CanRead && !CanWrite)
- throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_StreamClosed"));
+ throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
if (!destination.CanRead && !destination.CanWrite)
- throw new ObjectDisposedException(nameof(destination), Environment.GetResourceString("ObjectDisposed_StreamClosed"));
+ throw new ObjectDisposedException(nameof(destination), SR.ObjectDisposed_StreamClosed);
if (!CanRead)
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnreadableStream"));
+ throw new NotSupportedException(SR.NotSupported_UnreadableStream);
if (!destination.CanWrite)
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnwritableStream"));
+ throw new NotSupportedException(SR.NotSupported_UnwritableStream);
Contract.EndContractBlock();
@@ -172,23 +198,22 @@ namespace System.IO {
}
- public override Task FlushAsync(CancellationToken cancellationToken) {
-
+ public override Task FlushAsync(CancellationToken cancellationToken)
+ {
return _unmanagedStream.FlushAsync(cancellationToken);
}
- public override Task<Int32> ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) {
-
+ public override Task<Int32> ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)
+ {
return _unmanagedStream.ReadAsync(buffer, offset, count, cancellationToken);
}
- public override Task WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) {
-
+ public override Task WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)
+ {
return _unmanagedStream.WriteAsync(buffer, offset, count, cancellationToken);
}
-
} // class UnmanagedMemoryStreamWrapper
} // namespace
diff --git a/src/mscorlib/src/System/IO/__Error.cs b/src/mscorlib/src/System/IO/__Error.cs
index 955ddbe..70f8326 100644
--- a/src/mscorlib/src/System/IO/__Error.cs
+++ b/src/mscorlib/src/System/IO/__Error.cs
@@ -23,46 +23,56 @@ using System.Globalization;
using System.Security;
using System.Diagnostics.Contracts;
-namespace System.IO {
+namespace System.IO
+{
[Pure]
internal static class __Error
{
- internal static void EndOfFile() {
- throw new EndOfStreamException(Environment.GetResourceString("IO.EOF_ReadBeyondEOF"));
+ internal static void EndOfFile()
+ {
+ throw new EndOfStreamException(SR.IO_EOF_ReadBeyondEOF);
}
- internal static void FileNotOpen() {
- throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_FileClosed"));
+ internal static void FileNotOpen()
+ {
+ throw new ObjectDisposedException(null, SR.ObjectDisposed_FileClosed);
}
-
- internal static void StreamIsClosed() {
- throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_StreamClosed"));
+
+ internal static void StreamIsClosed()
+ {
+ throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
}
-
- internal static void MemoryStreamNotExpandable() {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_MemStreamNotExpandable"));
+
+ internal static void MemoryStreamNotExpandable()
+ {
+ throw new NotSupportedException(SR.NotSupported_MemStreamNotExpandable);
}
-
- internal static void ReaderClosed() {
- throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_ReaderClosed"));
+
+ internal static void ReaderClosed()
+ {
+ throw new ObjectDisposedException(null, SR.ObjectDisposed_ReaderClosed);
}
- internal static void ReadNotSupported() {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnreadableStream"));
+ internal static void ReadNotSupported()
+ {
+ throw new NotSupportedException(SR.NotSupported_UnreadableStream);
}
- internal static void WrongAsyncResult() {
- throw new ArgumentException(Environment.GetResourceString("Arg_WrongAsyncResult"));
+ internal static void WrongAsyncResult()
+ {
+ throw new ArgumentException(SR.Arg_WrongAsyncResult);
}
- internal static void EndReadCalledTwice() {
+ internal static void EndReadCalledTwice()
+ {
// Should ideally be InvalidOperationExc but we can't maitain parity with Stream and FileStream without some work
- throw new ArgumentException(Environment.GetResourceString("InvalidOperation_EndReadCalledMultiple"));
+ throw new ArgumentException(SR.InvalidOperation_EndReadCalledMultiple);
}
- internal static void EndWriteCalledTwice() {
+ internal static void EndWriteCalledTwice()
+ {
// Should ideally be InvalidOperationExc but we can't maintain parity with Stream and FileStream without some work
- throw new ArgumentException(Environment.GetResourceString("InvalidOperation_EndWriteCalledMultiple"));
+ throw new ArgumentException(SR.InvalidOperation_EndWriteCalledMultiple);
}
// Given a possible fully qualified path, ensure that we have path
@@ -71,7 +81,6 @@ namespace System.IO {
// directory name.
internal static String GetDisplayablePath(String path, bool isInvalidPath)
{
-
if (String.IsNullOrEmpty(path))
return String.Empty;
@@ -81,7 +90,8 @@ namespace System.IO {
return path;
if (PathInternal.IsDirectorySeparator(path[0]) && PathInternal.IsDirectorySeparator(path[1]))
isFullyQualified = true;
- else if (path[1] == Path.VolumeSeparatorChar) {
+ else if (path[1] == Path.VolumeSeparatorChar)
+ {
isFullyQualified = true;
}
@@ -89,26 +99,32 @@ namespace System.IO {
return path;
bool safeToReturn = false;
- try {
- if (!isInvalidPath) {
+ try
+ {
+ if (!isInvalidPath)
+ {
safeToReturn = true;
}
}
- catch (SecurityException) {
+ catch (SecurityException)
+ {
}
- catch (ArgumentException) {
+ catch (ArgumentException)
+ {
// ? and * characters cause ArgumentException to be thrown from HasIllegalCharacters
// inside FileIOPermission.AddPathList
}
- catch (NotSupportedException) {
+ catch (NotSupportedException)
+ {
// paths like "!Bogus\\dir:with/junk_.in it" can cause NotSupportedException to be thrown
// from Security.Util.StringExpressionSet.CanonicalizePath when ':' is found in the path
// beyond string index position 1.
}
-
- if (!safeToReturn) {
+
+ if (!safeToReturn)
+ {
if (PathInternal.IsDirectorySeparator(path[path.Length - 1]))
- path = Environment.GetResourceString("IO.IO_NoPermissionToDirectoryName");
+ path = SR.IO_NoPermissionToDirectoryName;
else
path = Path.GetFileName(path);
}
@@ -116,81 +132,85 @@ namespace System.IO {
return path;
}
- internal static void WinIOError() {
+ internal static void WinIOError()
+ {
int errorCode = Marshal.GetLastWin32Error();
WinIOError(errorCode, String.Empty);
}
-
+
// After calling GetLastWin32Error(), it clears the last error field,
// so you must save the HResult and pass it to this method. This method
// will determine the appropriate exception to throw dependent on your
// error, and depending on the error, insert a string into the message
// gotten from the ResourceManager.
- internal static void WinIOError(int errorCode, String maybeFullPath) {
+ internal static void WinIOError(int errorCode, String maybeFullPath)
+ {
// This doesn't have to be perfect, but is a perf optimization.
bool isInvalidPath = errorCode == Win32Native.ERROR_INVALID_NAME || errorCode == Win32Native.ERROR_BAD_PATHNAME;
String str = GetDisplayablePath(maybeFullPath, isInvalidPath);
- switch (errorCode) {
- case Win32Native.ERROR_FILE_NOT_FOUND:
- if (str.Length == 0)
- throw new FileNotFoundException(Environment.GetResourceString("IO.FileNotFound"));
- else
- throw new FileNotFoundException(Environment.GetResourceString("IO.FileNotFound_FileName", str), str);
-
- case Win32Native.ERROR_PATH_NOT_FOUND:
- if (str.Length == 0)
- throw new DirectoryNotFoundException(Environment.GetResourceString("IO.PathNotFound_NoPathName"));
- else
- throw new DirectoryNotFoundException(Environment.GetResourceString("IO.PathNotFound_Path", str));
-
- case Win32Native.ERROR_ACCESS_DENIED:
- if (str.Length == 0)
- throw new UnauthorizedAccessException(Environment.GetResourceString("UnauthorizedAccess_IODenied_NoPathName"));
- else
- throw new UnauthorizedAccessException(Environment.GetResourceString("UnauthorizedAccess_IODenied_Path", str));
-
- case Win32Native.ERROR_ALREADY_EXISTS:
- if (str.Length == 0)
- goto default;
- throw new IOException(Environment.GetResourceString("IO.IO_AlreadyExists_Name", str), Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath);
-
- case Win32Native.ERROR_FILENAME_EXCED_RANGE:
- throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
-
- case Win32Native.ERROR_INVALID_DRIVE:
- throw new DriveNotFoundException(Environment.GetResourceString("IO.DriveNotFound_Drive", str));
-
- case Win32Native.ERROR_INVALID_PARAMETER:
- throw new IOException(Win32Native.GetMessage(errorCode), Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath);
-
- case Win32Native.ERROR_SHARING_VIOLATION:
- if (str.Length == 0)
- throw new IOException(Environment.GetResourceString("IO.IO_SharingViolation_NoFileName"), Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath);
- else
- throw new IOException(Environment.GetResourceString("IO.IO_SharingViolation_File", str), Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath);
-
- case Win32Native.ERROR_FILE_EXISTS:
- if (str.Length == 0)
- goto default;
- throw new IOException(Environment.GetResourceString("IO.IO_FileExists_Name", str), Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath);
-
- case Win32Native.ERROR_OPERATION_ABORTED:
- throw new OperationCanceledException();
-
- default:
- throw new IOException(Win32Native.GetMessage(errorCode), Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath);
+ switch (errorCode)
+ {
+ case Win32Native.ERROR_FILE_NOT_FOUND:
+ if (str.Length == 0)
+ throw new FileNotFoundException(SR.IO_FileNotFound);
+ else
+ throw new FileNotFoundException(SR.Format(SR.IO_FileNotFound_FileName, str), str);
+
+ case Win32Native.ERROR_PATH_NOT_FOUND:
+ if (str.Length == 0)
+ throw new DirectoryNotFoundException(SR.IO_PathNotFound_NoPathName);
+ else
+ throw new DirectoryNotFoundException(SR.Format(SR.IO_PathNotFound_Path, str));
+
+ case Win32Native.ERROR_ACCESS_DENIED:
+ if (str.Length == 0)
+ throw new UnauthorizedAccessException(SR.UnauthorizedAccess_IODenied_NoPathName);
+ else
+ throw new UnauthorizedAccessException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, str));
+
+ case Win32Native.ERROR_ALREADY_EXISTS:
+ if (str.Length == 0)
+ goto default;
+ throw new IOException(SR.Format(SR.IO_AlreadyExists_Name, str), Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath);
+
+ case Win32Native.ERROR_FILENAME_EXCED_RANGE:
+ throw new PathTooLongException(SR.IO_PathTooLong);
+
+ case Win32Native.ERROR_INVALID_DRIVE:
+ throw new DriveNotFoundException(SR.Format(SR.IO_DriveNotFound_Drive, str));
+
+ case Win32Native.ERROR_INVALID_PARAMETER:
+ throw new IOException(Win32Native.GetMessage(errorCode), Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath);
+
+ case Win32Native.ERROR_SHARING_VIOLATION:
+ if (str.Length == 0)
+ throw new IOException(SR.IO_SharingViolation_NoFileName, Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath);
+ else
+ throw new IOException(SR.Format(SR.IO_SharingViolation_File, str), Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath);
+
+ case Win32Native.ERROR_FILE_EXISTS:
+ if (str.Length == 0)
+ goto default;
+ throw new IOException(SR.Format(SR.IO_FileExists_Name, str), Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath);
+
+ case Win32Native.ERROR_OPERATION_ABORTED:
+ throw new OperationCanceledException();
+
+ default:
+ throw new IOException(Win32Native.GetMessage(errorCode), Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath);
}
}
-
- internal static void WriteNotSupported() {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnwritableStream"));
+
+ internal static void WriteNotSupported()
+ {
+ throw new NotSupportedException(SR.NotSupported_UnwritableStream);
}
// From WinError.h
internal const int ERROR_FILE_NOT_FOUND = Win32Native.ERROR_FILE_NOT_FOUND;
internal const int ERROR_PATH_NOT_FOUND = Win32Native.ERROR_PATH_NOT_FOUND;
- internal const int ERROR_ACCESS_DENIED = Win32Native.ERROR_ACCESS_DENIED;
+ internal const int ERROR_ACCESS_DENIED = Win32Native.ERROR_ACCESS_DENIED;
internal const int ERROR_INVALID_PARAMETER = Win32Native.ERROR_INVALID_PARAMETER;
}
}
diff --git a/src/mscorlib/src/System/IO/__HResults.cs b/src/mscorlib/src/System/IO/__HResults.cs
index e19f28f..633c353 100644
--- a/src/mscorlib/src/System/IO/__HResults.cs
+++ b/src/mscorlib/src/System/IO/__HResults.cs
@@ -11,8 +11,11 @@
//
//
//===========================================================================*/
-namespace System.IO {
- using System;
+
+using System;
+
+namespace System.IO
+{
// Only static data no need to serialize
internal static class __HResults
{