forked from nearby-sharing/android
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CdpFileProvider.cs
58 lines (47 loc) · 1.56 KB
/
CdpFileProvider.cs
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
using System.IO;
using System.Text;
namespace ShortDev.Microsoft.ConnectedDevices.NearShare;
public sealed class CdpFileProvider : IDisposable
{
readonly Stream _buffer;
private CdpFileProvider(string fileName, Stream buffer)
{
FileName = fileName;
_buffer = buffer;
}
public static CdpFileProvider FromContent(string fileName, string content)
=> FromContent(fileName, content, Encoding.UTF8);
public static CdpFileProvider FromContent(string fileName, string content, Encoding encoding)
{
var buffer = encoding.GetBytes(content);
return FromBuffer(fileName, buffer);
}
public static CdpFileProvider FromBuffer(string fileName, ReadOnlyMemory<byte> buffer)
{
MemoryStream stream = new();
stream.Write(buffer.Span);
return FromStream(fileName, stream);
}
public static CdpFileProvider FromStream(string fileName, Stream stream)
{
if (!stream.CanSeek)
throw new ArgumentException("Stream can't seek", nameof(stream));
if (!stream.CanRead)
throw new ArgumentException("Stream can't read", nameof(stream));
return new(fileName, stream);
}
public string FileName { get; }
public ulong FileSize
=> (ulong)_buffer.Length;
public ReadOnlySpan<byte> ReadBlob(ulong start, uint length)
{
Span<byte> buffer = new byte[length];
_buffer.Position = (long)start;
_buffer.Read(buffer);
return buffer;
}
public void Dispose()
{
_buffer.Dispose();
}
}