StreamExtensions.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /* Copyright 2015-present MongoDB Inc.
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. using System.IO;
  16. using System.Threading;
  17. using System.Threading.Tasks;
  18. namespace MongoDB.Driver.GridFS
  19. {
  20. internal static class StreamExtensions
  21. {
  22. public static void ReadBytes(this Stream stream, byte[] destination, int offset, int count, CancellationToken cancellationToken)
  23. {
  24. while (count > 0)
  25. {
  26. var bytesRead = stream.Read(destination, offset, count); // TODO: honor cancellationToken?
  27. if (bytesRead == 0)
  28. {
  29. throw new EndOfStreamException();
  30. }
  31. offset += bytesRead;
  32. count -= bytesRead;
  33. }
  34. }
  35. public static async Task ReadBytesAsync(this Stream stream, byte[] destination, int offset, int count, CancellationToken cancellationToken)
  36. {
  37. while (count > 0)
  38. {
  39. var bytesRead = await stream.ReadAsync(destination, offset, count, cancellationToken).ConfigureAwait(false);
  40. if (bytesRead == 0)
  41. {
  42. throw new EndOfStreamException();
  43. }
  44. offset += bytesRead;
  45. count -= bytesRead;
  46. }
  47. }
  48. }
  49. }