-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEsfsSal.cs
105 lines (81 loc) · 3.1 KB
/
EsfsSal.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
using System;
using System.IO;
namespace EsfsLite
{
public class EsfsSal
{
private readonly object _lock = new object();
private readonly Stream _containerStream;
private readonly byte[] _sectorData;
public EsfsSal(Stream containerStream)
{
_containerStream = containerStream;
_sectorData = new byte[Esfs.SectorSizeRawBytes];
}
private void UpsizeContainer(Int64 newSize)
{
var needBytes = newSize - _containerStream.Length;
if (needBytes > 0)
{
_containerStream.Seek(0, SeekOrigin.End);
for (var n = 0; n < Esfs.SectorSizeRawBytes; n++)
{
_sectorData[n] = 0;
}
var bytesRemain = needBytes;
while (bytesRemain > 0)
{
var bytesToWrite = bytesRemain;
if (bytesToWrite > Esfs.SectorSizeRawBytes)
{
bytesToWrite = Esfs.SectorSizeRawBytes;
}
_containerStream.Write(_sectorData, 0, (int) bytesToWrite);
bytesRemain -= bytesToWrite;
}
}
}
public void PutSector(Int64 index, byte[] data, int offset)
{
if (index == 0)
{
throw new EsfsException("Unable to put sector data - invalid sector index (zero)");
}
lock (_lock)
{
var containerOffset = index* Esfs.SectorSizeRawBytes;
if (containerOffset >= _containerStream.Length)
{
UpsizeContainer(containerOffset + Esfs.SectorSizeRawBytes);
}
_containerStream.Seek(containerOffset, SeekOrigin.Begin);
Array.Copy(data, offset, _sectorData, 0, Esfs.SectorSizeRawBytes);
_containerStream.Write(_sectorData, 0, Esfs.SectorSizeRawBytes);
}
}
public byte[] GetSector(Int64 index)
{
if (index == 0)
{
throw new EsfsException("Unable to get sector data - invalid sector index (zero)");
}
lock (_lock)
{
var containerOffset = index*Esfs.SectorSizeRawBytes;
if (containerOffset >= _containerStream.Length)
{
UpsizeContainer(containerOffset + Esfs.SectorSizeRawBytes);
}
_containerStream.Seek(containerOffset, SeekOrigin.Begin);
_containerStream.Read(_sectorData, 0, Esfs.SectorSizeRawBytes);
return _sectorData;
}
}
public bool IsValidSector(Int64 index)
{
var containerOffset = index * Esfs.SectorSizeRawBytes;
var isValid = (containerOffset + Esfs.SectorSizeRawBytes) < _containerStream.Length;
return isValid;
}
}
}