Quellcode durchsuchen

Merge pull request #7596 from jtattermusch/safe_span_accessors

annotate ByteString.Span and ByteString.Memory as SecuritySafeCritical
Jan Tattermusch vor 5 Jahren
Ursprung
Commit
daada70233

+ 16 - 0
csharp/src/Google.Protobuf.Test/ByteStringTest.cs

@@ -233,5 +233,21 @@ namespace Google.Protobuf
             ByteString b2 = ByteString.CopyFrom(200, 1, 2, 3, 4);
             Assert.AreNotEqual(b1.GetHashCode(), b2.GetHashCode());
         }
+
+        [Test]
+        public void GetContentsAsReadOnlySpan()
+        {
+            var byteString = ByteString.CopyFrom(1, 2, 3, 4, 5);
+            var copied = byteString.Span.ToArray();
+            CollectionAssert.AreEqual(byteString, copied);
+        }
+
+        [Test]
+        public void GetContentsAsReadOnlyMemory()
+        {
+            var byteString = ByteString.CopyFrom(1, 2, 3, 4, 5);
+            var copied = byteString.Memory.ToArray();
+            CollectionAssert.AreEqual(byteString, copied);
+        }
     }
 }

+ 17 - 2
csharp/src/Google.Protobuf/ByteString.cs

@@ -34,6 +34,7 @@ using System;
 using System.Collections;
 using System.Collections.Generic;
 using System.IO;
+using System.Security;
 using System.Text;
 #if !NET35
 using System.Threading;
@@ -115,13 +116,27 @@ namespace Google.Protobuf
         /// Provides read-only access to the data of this <see cref="ByteString"/>.
         /// No data is copied so this is the most efficient way of accessing.
         /// </summary>
-        public ReadOnlySpan<byte> Span => new ReadOnlySpan<byte>(bytes);
+        public ReadOnlySpan<byte> Span
+        {
+            [SecuritySafeCritical]
+            get
+            {
+                return new ReadOnlySpan<byte>(bytes);
+            }
+        }
 
         /// <summary>
         /// Provides read-only access to the data of this <see cref="ByteString"/>.
         /// No data is copied so this is the most efficient way of accessing.
         /// </summary>
-        public ReadOnlyMemory<byte> Memory => new ReadOnlyMemory<byte>(bytes);
+        public ReadOnlyMemory<byte> Memory
+        {
+            [SecuritySafeCritical]
+            get
+            {
+                return new ReadOnlyMemory<byte>(bytes);
+            }
+        }
 #endif
 
         /// <summary>