• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 #region Copyright notice and license
2 // Protocol Buffers - Google's data interchange format
3 // Copyright 2008 Google Inc.  All rights reserved.
4 //
5 // Use of this source code is governed by a BSD-style
6 // license that can be found in the LICENSE file or at
7 // https://developers.google.com/open-source/licenses/bsd
8 #endregion
9 
10 using System;
11 using System.IO;
12 using System.Threading;
13 using System.Threading.Tasks;
14 
15 namespace Google.Protobuf
16 {
17     /// <summary>
18     /// SecuritySafeCritical attribute can not be placed on types with async methods.
19     /// This class has ByteString's async methods so it can be marked with SecuritySafeCritical.
20     /// </summary>
21     internal static class ByteStringAsync
22     {
FromStreamAsyncCore(Stream stream, CancellationToken cancellationToken)23         internal static async Task<ByteString> FromStreamAsyncCore(Stream stream, CancellationToken cancellationToken)
24         {
25             int capacity = stream.CanSeek ? checked((int)(stream.Length - stream.Position)) : 0;
26             var memoryStream = new MemoryStream(capacity);
27             // We have to specify the buffer size here, as there's no overload accepting the cancellation token
28             // alone. But it's documented to use 81920 by default if not specified.
29             await stream.CopyToAsync(memoryStream, 81920, cancellationToken);
30 #if NETSTANDARD1_1
31             byte[] bytes = memoryStream.ToArray();
32 #else
33             // Avoid an extra copy if we can.
34             byte[] bytes = memoryStream.Length == memoryStream.Capacity ? memoryStream.GetBuffer() : memoryStream.ToArray();
35 #endif
36             return ByteString.AttachBytes(bytes);
37         }
38     }
39 }