Streams.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. using System;
  3. using System.IO;
  4. namespace Org.BouncyCastle.Utilities.IO
  5. {
  6. public sealed class Streams
  7. {
  8. private const int BufferSize = 512;
  9. private Streams()
  10. {
  11. }
  12. public static void Drain(Stream inStr)
  13. {
  14. byte[] bs = new byte[BufferSize];
  15. while (inStr.Read(bs, 0, bs.Length) > 0)
  16. {
  17. }
  18. }
  19. public static byte[] ReadAll(Stream inStr)
  20. {
  21. MemoryStream buf = new MemoryStream();
  22. PipeAll(inStr, buf);
  23. return buf.ToArray();
  24. }
  25. public static byte[] ReadAllLimited(Stream inStr, int limit)
  26. {
  27. MemoryStream buf = new MemoryStream();
  28. PipeAllLimited(inStr, limit, buf);
  29. return buf.ToArray();
  30. }
  31. public static int ReadFully(Stream inStr, byte[] buf)
  32. {
  33. return ReadFully(inStr, buf, 0, buf.Length);
  34. }
  35. public static int ReadFully(Stream inStr, byte[] buf, int off, int len)
  36. {
  37. int totalRead = 0;
  38. while (totalRead < len)
  39. {
  40. int numRead = inStr.Read(buf, off + totalRead, len - totalRead);
  41. if (numRead < 1)
  42. break;
  43. totalRead += numRead;
  44. }
  45. return totalRead;
  46. }
  47. public static void PipeAll(Stream inStr, Stream outStr)
  48. {
  49. byte[] bs = new byte[BufferSize];
  50. int numRead;
  51. while ((numRead = inStr.Read(bs, 0, bs.Length)) > 0)
  52. {
  53. outStr.Write(bs, 0, numRead);
  54. }
  55. }
  56. /// <summary>
  57. /// Pipe all bytes from <c>inStr</c> to <c>outStr</c>, throwing <c>StreamFlowException</c> if greater
  58. /// than <c>limit</c> bytes in <c>inStr</c>.
  59. /// </summary>
  60. /// <param name="inStr">
  61. /// A <see cref="Stream"/>
  62. /// </param>
  63. /// <param name="limit">
  64. /// A <see cref="System.Int64"/>
  65. /// </param>
  66. /// <param name="outStr">
  67. /// A <see cref="Stream"/>
  68. /// </param>
  69. /// <returns>The number of bytes actually transferred, if not greater than <c>limit</c></returns>
  70. /// <exception cref="IOException"></exception>
  71. public static long PipeAllLimited(Stream inStr, long limit, Stream outStr)
  72. {
  73. byte[] bs = new byte[BufferSize];
  74. long total = 0;
  75. int numRead;
  76. while ((numRead = inStr.Read(bs, 0, bs.Length)) > 0)
  77. {
  78. if ((limit - total) < numRead)
  79. throw new StreamOverflowException("Data Overflow");
  80. total += numRead;
  81. outStr.Write(bs, 0, numRead);
  82. }
  83. return total;
  84. }
  85. }
  86. }
  87. #endif