From b37362640be8f525ef16a6535c92ee1f71c671dd Mon Sep 17 00:00:00 2001 From: Next Turn <45985406+NextTurn@users.noreply.github.com> Date: Sat, 31 Aug 2019 05:04:37 +0800 Subject: [PATCH] Use Span in Encoding (dotnet/coreclr#25860) Commit migrated from https://github.com/dotnet/coreclr/commit/6efffaa9aa6d289f0ae1d44b7bc61c87f00f5a37 --- .../src/System/Text/Encoding.cs | 32 ++++--------------- 1 file changed, 7 insertions(+), 25 deletions(-) diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/Encoding.cs b/src/libraries/System.Private.CoreLib/src/System/Text/Encoding.cs index 3349d961a81..cbd7cbae944 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/Encoding.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/Encoding.cs @@ -600,11 +600,7 @@ namespace System.Text throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); - char[] arrChar = new char[count]; - int index; - - for (index = 0; index < count; index++) - arrChar[index] = chars[index]; + char[] arrChar = new ReadOnlySpan(chars, count).ToArray(); return GetByteCount(arrChar, 0, count); } @@ -744,11 +740,7 @@ namespace System.Text SR.ArgumentOutOfRange_NeedNonNegNum); // Get the char array to convert - char[] arrChar = new char[charCount]; - - int index; - for (index = 0; index < charCount; index++) - arrChar[index] = chars[index]; + char[] arrChar = new ReadOnlySpan(chars, charCount).ToArray(); // Get the byte array to fill byte[] arrByte = new byte[byteCount]; @@ -767,8 +759,7 @@ namespace System.Text byteCount = result; // Copy the data, don't overrun our array! - for (index = 0; index < byteCount; index++) - bytes[index] = arrByte[index]; + new ReadOnlySpan(arrByte, 0, byteCount).CopyTo(new Span(bytes, byteCount)); return byteCount; } @@ -814,13 +805,9 @@ namespace System.Text throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); - byte[] arrbyte = new byte[count]; - int index; + byte[] arrByte = new ReadOnlySpan(bytes, count).ToArray(); - for (index = 0; index < count; index++) - arrbyte[index] = bytes[index]; - - return GetCharCount(arrbyte, 0, count); + return GetCharCount(arrByte, 0, count); } public virtual unsafe int GetCharCount(ReadOnlySpan bytes) @@ -899,11 +886,7 @@ namespace System.Text SR.ArgumentOutOfRange_NeedNonNegNum); // Get the byte array to convert - byte[] arrByte = new byte[byteCount]; - - int index; - for (index = 0; index < byteCount; index++) - arrByte[index] = bytes[index]; + byte[] arrByte = new ReadOnlySpan(bytes, byteCount).ToArray(); // Get the char array to fill char[] arrChar = new char[charCount]; @@ -922,8 +905,7 @@ namespace System.Text charCount = result; // Copy the data, don't overrun our array! - for (index = 0; index < charCount; index++) - chars[index] = arrChar[index]; + new ReadOnlySpan(arrChar, 0, charCount).CopyTo(new Span(chars, charCount)); return charCount; } -- 2.34.1