-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEsfsChain.cs
156 lines (124 loc) · 3.77 KB
/
EsfsChain.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
using System;
using System.Collections.Generic;
using System.Linq;
namespace EsfsLite
{
public class EsfsChain : EsfsSector
{
private readonly object _lock = new object();
private int _cacheIndex;
private readonly List<long> _chainCache = new List<long>(8192);
public EsfsChain(EsfsSal sal, Int64 baseSectorOffset) : base(sal)
{
Index = baseSectorOffset;
Read();
_cacheIndex = 0;
_chainCache.Add(baseSectorOffset);
}
public void Next()
{
lock (_lock)
{
if ((_cacheIndex + 1) < _chainCache.Count)
{
_cacheIndex++;
Index = _chainCache[_cacheIndex];
}
else
{
Index = _chainCache[_cacheIndex];
Read();
if (Link == Index)
{
throw new EsfsException("Unable to follow next sector - end of chunk");
}
if (Sal.IsValidSector(Link) == false)
{
throw new EsfsException("Unable to follow next sector - invalid link");
}
if (_chainCache.Contains(Link))
{
throw new EsfsException("Unable to follow next sector - chain loop detected");
}
_chainCache.Add(Link);
_cacheIndex++;
Index = Link;
}
}
}
public bool IsCanGoForward()
{
if (Sal.IsValidSector(Link) == false ||
Link == Index)
{
return false;
}
return true;
}
public void Seek(int sectorIndex)
{
lock (_lock)
{
while (sectorIndex >= _chainCache.Count)
{
Next();
}
if (sectorIndex < _chainCache.Count)
{
_cacheIndex = sectorIndex;
Index = _chainCache[sectorIndex];
}
}
Read();
}
public long Start()
{
return _chainCache[0];
}
public long End()
{
Index = _chainCache.Last();
Read();
while (IsCanGoForward())
{
Next();
Read();
}
return Index;
}
public int Length()
{
End();
return _chainCache.Count;
}
public EsfsChain Split(int cutSectors)
{
var cutBegining = _chainCache[0];
Seek(cutSectors);
var cuttedChainBegining = Index;
Seek(cutSectors - 1);
Link = Index;
Store();
while (_chainCache[0] != cuttedChainBegining && _chainCache.Count > 0)
{
_chainCache.RemoveAt(0);
if (_cacheIndex > 0)
{
_cacheIndex--;
}
}
return new EsfsChain(Sal, cutBegining);
}
public void Glue(EsfsChain chain)
{
End();
Read();
if (Link != Index)
{
throw new EsfsException(string.Format("Unable to glue chain - invalid link index in last sector ({0})", Link));
}
Link = chain.Start();
Store();
}
}
}