Add String.Create span-based method
authorStephen Toub <stoub@microsoft.com>
Fri, 8 Sep 2017 01:42:42 +0000 (21:42 -0400)
committerStephen Toub <stoub@microsoft.com>
Fri, 8 Sep 2017 11:01:57 +0000 (07:01 -0400)
src/mscorlib/shared/System/Action.cs
src/mscorlib/src/System/String.cs

index b82c14d..da68138 100644 (file)
@@ -33,3 +33,9 @@ namespace System
 
     public delegate bool Predicate<in T>(T obj);
 }
+
+namespace System.Buffers
+{
+    public delegate void SpanAction<T, in TArg>(Span<T> span, TArg arg);
+    public delegate void ReadOnlySpanAction<T, in TArg>(ReadOnlySpan<T> span, TArg arg);
+}
index 9520cce..c74abe9 100644 (file)
@@ -16,6 +16,7 @@ namespace System
 {
     using System.Text;
     using System;
+    using System.Buffers;
     using System.Runtime;
     using System.Runtime.ConstrainedExecution;
     using System.Globalization;
@@ -684,6 +685,28 @@ namespace System
             return result;
         }
 
+        public static string Create<TState>(int length, TState state, SpanAction<char, TState> action)
+        {
+            if (action == null)
+            {
+                throw new ArgumentNullException(nameof(action));
+            }
+
+            if (length > 0)
+            {
+                string result = FastAllocateString(length);
+                action(new Span<char>(ref result.GetRawStringData(), length), state);
+                return result;
+            }
+
+            if (length == 0)
+            {
+                return Empty;
+            }
+
+            throw new ArgumentOutOfRangeException(nameof(length));
+        }
+
         // Returns this string.
         public override String ToString()
         {