forked from marcpabst/PdfiumLight
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStreamExtensions.cs
More file actions
77 lines (59 loc) · 1.85 KB
/
StreamExtensions.cs
File metadata and controls
77 lines (59 loc) · 1.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
using System;
using System.IO;
namespace PdfiumLight
{
internal static class StreamExtensions
{
public static byte[] ToByteArray(Stream stream)
{
if (stream is null)
throw new ArgumentNullException(nameof(stream));
if (stream is MemoryStream memoryStream)
{
return memoryStream.ToArray();
}
if (stream.CanSeek)
return ReadBytesFast(stream);
else
return ReadBytesSlow(stream);
}
private static byte[] ReadBytesFast(Stream stream)
{
byte[] data = new byte[stream.Length];
int offset = 0;
while (offset < data.Length)
{
int read = stream.Read(data, offset, data.Length - offset);
if (read <= 0)
break;
offset += read;
}
if (offset < data.Length)
throw new InvalidOperationException("Incorrect length reported");
return data;
}
private static byte[] ReadBytesSlow(Stream stream)
{
using (var memoryStream = new MemoryStream())
{
CopyStream(stream, memoryStream);
return memoryStream.ToArray();
}
}
public static void CopyStream(Stream from, Stream to)
{
if (@from is null)
throw new ArgumentNullException(nameof(from));
if (to is null)
throw new ArgumentNullException(nameof(to));
var buffer = new byte[4096];
while (true)
{
int read = from.Read(buffer, 0, buffer.Length);
if (read == 0)
return;
to.Write(buffer, 0, read);
}
}
}
}