diff --git a/csharp/src/Google.Protobuf/ByteString.cs b/csharp/src/Google.Protobuf/ByteString.cs index 4abdb7182c5ab..32078b4df5dc4 100644 --- a/csharp/src/Google.Protobuf/ByteString.cs +++ b/csharp/src/Google.Protobuf/ByteString.cs @@ -67,15 +67,6 @@ internal static ByteString FromBytes(byte[] bytes) { return new ByteString(bytes); } - - /// - /// Provides direct, unrestricted access to the bytes contained in this instance. - /// You must not modify or resize the byte array returned by this method. - /// - internal static byte[] GetBuffer(ByteString bytes) - { - return bytes.bytes; - } } /// @@ -119,6 +110,14 @@ public bool IsEmpty get { return Length == 0; } } +#if NETSTANDARD2_0 + /// + /// Provides read-only access to the data of this . + /// No data is copied so this is the most efficient way of accessing. + /// + public ReadOnlySpan Span => new ReadOnlySpan(bytes); +#endif + /// /// Converts this into a byte array. /// @@ -161,7 +160,7 @@ public static ByteString FromStream(Stream stream) int capacity = stream.CanSeek ? checked((int) (stream.Length - stream.Position)) : 0; var memoryStream = new MemoryStream(capacity); stream.CopyTo(memoryStream); -#if NETSTANDARD1_0 +#if NETSTANDARD1_0 || NETSTANDARD2_0 byte[] bytes = memoryStream.ToArray(); #else // Avoid an extra copy if we can. @@ -187,7 +186,7 @@ public static ByteString FromStream(Stream stream) // We have to specify the buffer size here, as there's no overload accepting the cancellation token // alone. But it's documented to use 81920 by default if not specified. await stream.CopyToAsync(memoryStream, 81920, cancellationToken); -#if NETSTANDARD1_0 +#if NETSTANDARD1_0 || NETSTANDARD2_0 byte[] bytes = memoryStream.ToArray(); #else // Avoid an extra copy if we can. @@ -219,6 +218,18 @@ public static ByteString CopyFrom(byte[] bytes, int offset, int count) return new ByteString(portion); } +#if NETSTANDARD2_0 + /// + /// Constructs a from a read only span. The contents + /// are copied, so further modifications to the span will not + /// be reflected in the returned . + /// + public static ByteString CopyFrom(ReadOnlySpan bytes) + { + return new ByteString(bytes.ToArray()); + } +#endif + /// /// Creates a new by encoding the specified text with /// the given encoding. diff --git a/csharp/src/Google.Protobuf/Google.Protobuf.csproj b/csharp/src/Google.Protobuf/Google.Protobuf.csproj index 9270786193e76..be67357577b94 100644 --- a/csharp/src/Google.Protobuf/Google.Protobuf.csproj +++ b/csharp/src/Google.Protobuf/Google.Protobuf.csproj @@ -7,7 +7,7 @@ 3.7.0 6 Google Inc. - netstandard1.0;net45 + netstandard1.0;netstandard2.0;net45 true ../../keys/Google.Protobuf.snk true @@ -28,9 +28,13 @@ - Visual Studio. --> - netstandard1.0 + netstandard1.0;netstandard2.0 + + + +