Code cleanup

This commit is contained in:
Gustave Monce
2019-12-22 12:25:48 +01:00
parent 0e6f905809
commit a2a1c2302b
149 changed files with 3980 additions and 4088 deletions
+42 -42
View File
@@ -2,54 +2,54 @@
namespace SevenZip namespace SevenZip
{ {
class CRC class CRC
{ {
public static readonly uint[] Table; public static readonly uint[] Table;
static CRC() static CRC()
{ {
Table = new uint[256]; Table = new uint[256];
const uint kPoly = 0xEDB88320; const uint kPoly = 0xEDB88320;
for (uint i = 0; i < 256; i++) for (uint i = 0; i < 256; i++)
{ {
uint r = i; uint r = i;
for (int j = 0; j < 8; j++) for (int j = 0; j < 8; j++)
if ((r & 1) != 0) if ((r & 1) != 0)
r = (r >> 1) ^ kPoly; r = (r >> 1) ^ kPoly;
else else
r >>= 1; r >>= 1;
Table[i] = r; Table[i] = r;
} }
} }
uint _value = 0xFFFFFFFF; uint _value = 0xFFFFFFFF;
public void Init() { _value = 0xFFFFFFFF; } public void Init() { _value = 0xFFFFFFFF; }
public void UpdateByte(byte b) public void UpdateByte(byte b)
{ {
_value = Table[(((byte)(_value)) ^ b)] ^ (_value >> 8); _value = Table[(((byte)(_value)) ^ b)] ^ (_value >> 8);
} }
public void Update(byte[] data, uint offset, uint size) public void Update(byte[] data, uint offset, uint size)
{ {
for (uint i = 0; i < size; i++) for (uint i = 0; i < size; i++)
_value = Table[(((byte)(_value)) ^ data[offset + i])] ^ (_value >> 8); _value = Table[(((byte)(_value)) ^ data[offset + i])] ^ (_value >> 8);
} }
public uint GetDigest() { return _value ^ 0xFFFFFFFF; } public uint GetDigest() { return _value ^ 0xFFFFFFFF; }
static uint CalculateDigest(byte[] data, uint offset, uint size) static uint CalculateDigest(byte[] data, uint offset, uint size)
{ {
CRC crc = new CRC(); CRC crc = new CRC();
// crc.Init(); // crc.Init();
crc.Update(data, offset, size); crc.Update(data, offset, size);
return crc.GetDigest(); return crc.GetDigest();
} }
static bool VerifyDigest(uint digest, byte[] data, uint offset, uint size) static bool VerifyDigest(uint digest, byte[] data, uint offset, uint size)
{ {
return (CalculateDigest(data, offset, size) == digest); return (CalculateDigest(data, offset, size) == digest);
} }
} }
} }
+251 -251
View File
@@ -5,270 +5,270 @@ using System.Collections;
namespace SevenZip.CommandLineParser namespace SevenZip.CommandLineParser
{ {
public enum SwitchType public enum SwitchType
{ {
Simple, Simple,
PostMinus, PostMinus,
LimitedPostString, LimitedPostString,
UnLimitedPostString, UnLimitedPostString,
PostChar PostChar
} }
public class SwitchForm public class SwitchForm
{ {
public string IDString; public string IDString;
public SwitchType Type; public SwitchType Type;
public bool Multi; public bool Multi;
public int MinLen; public int MinLen;
public int MaxLen; public int MaxLen;
public string PostCharSet; public string PostCharSet;
public SwitchForm(string idString, SwitchType type, bool multi, public SwitchForm(string idString, SwitchType type, bool multi,
int minLen, int maxLen, string postCharSet) int minLen, int maxLen, string postCharSet)
{ {
IDString = idString; IDString = idString;
Type = type; Type = type;
Multi = multi; Multi = multi;
MinLen = minLen; MinLen = minLen;
MaxLen = maxLen; MaxLen = maxLen;
PostCharSet = postCharSet; PostCharSet = postCharSet;
} }
public SwitchForm(string idString, SwitchType type, bool multi, int minLen): public SwitchForm(string idString, SwitchType type, bool multi, int minLen) :
this(idString, type, multi, minLen, 0, "") this(idString, type, multi, minLen, 0, "")
{ {
} }
public SwitchForm(string idString, SwitchType type, bool multi): public SwitchForm(string idString, SwitchType type, bool multi) :
this(idString, type, multi, 0) this(idString, type, multi, 0)
{ {
} }
} }
public class SwitchResult public class SwitchResult
{ {
public bool ThereIs; public bool ThereIs;
public bool WithMinus; public bool WithMinus;
public ArrayList PostStrings = new ArrayList(); public ArrayList PostStrings = new ArrayList();
public int PostCharIndex; public int PostCharIndex;
public SwitchResult() public SwitchResult()
{ {
ThereIs = false; ThereIs = false;
} }
} }
public class Parser public class Parser
{ {
public ArrayList NonSwitchStrings = new ArrayList(); public ArrayList NonSwitchStrings = new ArrayList();
SwitchResult[] _switches; SwitchResult[] _switches;
public Parser(int numSwitches) public Parser(int numSwitches)
{ {
_switches = new SwitchResult[numSwitches]; _switches = new SwitchResult[numSwitches];
for (int i = 0; i < numSwitches; i++) for (int i = 0; i < numSwitches; i++)
_switches[i] = new SwitchResult(); _switches[i] = new SwitchResult();
} }
bool ParseString(string srcString, SwitchForm[] switchForms) bool ParseString(string srcString, SwitchForm[] switchForms)
{ {
int len = srcString.Length; int len = srcString.Length;
if (len == 0) if (len == 0)
return false; return false;
int pos = 0; int pos = 0;
if (!IsItSwitchChar(srcString[pos])) if (!IsItSwitchChar(srcString[pos]))
return false; return false;
while (pos < len) while (pos < len)
{ {
if (IsItSwitchChar(srcString[pos])) if (IsItSwitchChar(srcString[pos]))
pos++; pos++;
const int kNoLen = -1; const int kNoLen = -1;
int matchedSwitchIndex = 0; int matchedSwitchIndex = 0;
int maxLen = kNoLen; int maxLen = kNoLen;
for (int switchIndex = 0; switchIndex < _switches.Length; switchIndex++) for (int switchIndex = 0; switchIndex < _switches.Length; switchIndex++)
{ {
int switchLen = switchForms[switchIndex].IDString.Length; int switchLen = switchForms[switchIndex].IDString.Length;
if (switchLen <= maxLen || pos + switchLen > len) if (switchLen <= maxLen || pos + switchLen > len)
continue; continue;
if (String.Compare(switchForms[switchIndex].IDString, 0, if (String.Compare(switchForms[switchIndex].IDString, 0,
srcString, pos, switchLen, true) == 0) srcString, pos, switchLen, true) == 0)
{ {
matchedSwitchIndex = switchIndex; matchedSwitchIndex = switchIndex;
maxLen = switchLen; maxLen = switchLen;
} }
} }
if (maxLen == kNoLen) if (maxLen == kNoLen)
throw new Exception("maxLen == kNoLen"); throw new Exception("maxLen == kNoLen");
SwitchResult matchedSwitch = _switches[matchedSwitchIndex]; SwitchResult matchedSwitch = _switches[matchedSwitchIndex];
SwitchForm switchForm = switchForms[matchedSwitchIndex]; SwitchForm switchForm = switchForms[matchedSwitchIndex];
if ((!switchForm.Multi) && matchedSwitch.ThereIs) if ((!switchForm.Multi) && matchedSwitch.ThereIs)
throw new Exception("switch must be single"); throw new Exception("switch must be single");
matchedSwitch.ThereIs = true; matchedSwitch.ThereIs = true;
pos += maxLen; pos += maxLen;
int tailSize = len - pos; int tailSize = len - pos;
SwitchType type = switchForm.Type; SwitchType type = switchForm.Type;
switch (type) switch (type)
{ {
case SwitchType.PostMinus: case SwitchType.PostMinus:
{ {
if (tailSize == 0) if (tailSize == 0)
matchedSwitch.WithMinus = false; matchedSwitch.WithMinus = false;
else else
{ {
matchedSwitch.WithMinus = (srcString[pos] == kSwitchMinus); matchedSwitch.WithMinus = (srcString[pos] == kSwitchMinus);
if (matchedSwitch.WithMinus) if (matchedSwitch.WithMinus)
pos++; pos++;
} }
break; break;
} }
case SwitchType.PostChar: case SwitchType.PostChar:
{ {
if (tailSize < switchForm.MinLen) if (tailSize < switchForm.MinLen)
throw new Exception("switch is not full"); throw new Exception("switch is not full");
string charSet = switchForm.PostCharSet; string charSet = switchForm.PostCharSet;
const int kEmptyCharValue = -1; const int kEmptyCharValue = -1;
if (tailSize == 0) if (tailSize == 0)
matchedSwitch.PostCharIndex = kEmptyCharValue; matchedSwitch.PostCharIndex = kEmptyCharValue;
else else
{ {
int index = charSet.IndexOf(srcString[pos]); int index = charSet.IndexOf(srcString[pos]);
if (index < 0) if (index < 0)
matchedSwitch.PostCharIndex = kEmptyCharValue; matchedSwitch.PostCharIndex = kEmptyCharValue;
else else
{ {
matchedSwitch.PostCharIndex = index; matchedSwitch.PostCharIndex = index;
pos++; pos++;
} }
} }
break; break;
} }
case SwitchType.LimitedPostString: case SwitchType.LimitedPostString:
case SwitchType.UnLimitedPostString: case SwitchType.UnLimitedPostString:
{ {
int minLen = switchForm.MinLen; int minLen = switchForm.MinLen;
if (tailSize < minLen) if (tailSize < minLen)
throw new Exception("switch is not full"); throw new Exception("switch is not full");
if (type == SwitchType.UnLimitedPostString) if (type == SwitchType.UnLimitedPostString)
{ {
matchedSwitch.PostStrings.Add(srcString.Substring(pos)); matchedSwitch.PostStrings.Add(srcString.Substring(pos));
return true; return true;
} }
String stringSwitch = srcString.Substring(pos, minLen); String stringSwitch = srcString.Substring(pos, minLen);
pos += minLen; pos += minLen;
for (int i = minLen; i < switchForm.MaxLen && pos < len; i++, pos++) for (int i = minLen; i < switchForm.MaxLen && pos < len; i++, pos++)
{ {
char c = srcString[pos]; char c = srcString[pos];
if (IsItSwitchChar(c)) if (IsItSwitchChar(c))
break; break;
stringSwitch += c; stringSwitch += c;
} }
matchedSwitch.PostStrings.Add(stringSwitch); matchedSwitch.PostStrings.Add(stringSwitch);
break; break;
} }
} }
} }
return true; return true;
} }
public void ParseStrings(SwitchForm[] switchForms, string[] commandStrings) public void ParseStrings(SwitchForm[] switchForms, string[] commandStrings)
{ {
int numCommandStrings = commandStrings.Length; int numCommandStrings = commandStrings.Length;
bool stopSwitch = false; bool stopSwitch = false;
for (int i = 0; i < numCommandStrings; i++) for (int i = 0; i < numCommandStrings; i++)
{ {
string s = commandStrings[i]; string s = commandStrings[i];
if (stopSwitch) if (stopSwitch)
NonSwitchStrings.Add(s); NonSwitchStrings.Add(s);
else else
if (s == kStopSwitchParsing) if (s == kStopSwitchParsing)
stopSwitch = true; stopSwitch = true;
else else
if (!ParseString(s, switchForms)) if (!ParseString(s, switchForms))
NonSwitchStrings.Add(s); NonSwitchStrings.Add(s);
} }
} }
public SwitchResult this[int index] { get { return _switches[index]; } } public SwitchResult this[int index] { get { return _switches[index]; } }
public static int ParseCommand(CommandForm[] commandForms, string commandString, public static int ParseCommand(CommandForm[] commandForms, string commandString,
out string postString) out string postString)
{ {
for (int i = 0; i < commandForms.Length; i++) for (int i = 0; i < commandForms.Length; i++)
{ {
string id = commandForms[i].IDString; string id = commandForms[i].IDString;
if (commandForms[i].PostStringMode) if (commandForms[i].PostStringMode)
{ {
if (commandString.IndexOf(id) == 0) if (commandString.IndexOf(id) == 0)
{ {
postString = commandString.Substring(id.Length); postString = commandString.Substring(id.Length);
return i; return i;
} }
} }
else else
if (commandString == id) if (commandString == id)
{ {
postString = ""; postString = "";
return i; return i;
} }
} }
postString = ""; postString = "";
return -1; return -1;
} }
static bool ParseSubCharsCommand(int numForms, CommandSubCharsSet[] forms, static bool ParseSubCharsCommand(int numForms, CommandSubCharsSet[] forms,
string commandString, ArrayList indices) string commandString, ArrayList indices)
{ {
indices.Clear(); indices.Clear();
int numUsedChars = 0; int numUsedChars = 0;
for (int i = 0; i < numForms; i++) for (int i = 0; i < numForms; i++)
{ {
CommandSubCharsSet charsSet = forms[i]; CommandSubCharsSet charsSet = forms[i];
int currentIndex = -1; int currentIndex = -1;
int len = charsSet.Chars.Length; int len = charsSet.Chars.Length;
for (int j = 0; j < len; j++) for (int j = 0; j < len; j++)
{ {
char c = charsSet.Chars[j]; char c = charsSet.Chars[j];
int newIndex = commandString.IndexOf(c); int newIndex = commandString.IndexOf(c);
if (newIndex >= 0) if (newIndex >= 0)
{ {
if (currentIndex >= 0) if (currentIndex >= 0)
return false; return false;
if (commandString.IndexOf(c, newIndex + 1) >= 0) if (commandString.IndexOf(c, newIndex + 1) >= 0)
return false; return false;
currentIndex = j; currentIndex = j;
numUsedChars++; numUsedChars++;
} }
} }
if (currentIndex == -1 && !charsSet.EmptyAllowed) if (currentIndex == -1 && !charsSet.EmptyAllowed)
return false; return false;
indices.Add(currentIndex); indices.Add(currentIndex);
} }
return (numUsedChars == commandString.Length); return (numUsedChars == commandString.Length);
} }
const char kSwitchID1 = '-'; const char kSwitchID1 = '-';
const char kSwitchID2 = '/'; const char kSwitchID2 = '/';
const char kSwitchMinus = '-'; const char kSwitchMinus = '-';
const string kStopSwitchParsing = "--"; const string kStopSwitchParsing = "--";
static bool IsItSwitchChar(char c) static bool IsItSwitchChar(char c)
{ {
return (c == kSwitchID1 || c == kSwitchID2); return (c == kSwitchID1 || c == kSwitchID2);
} }
} }
public class CommandForm public class CommandForm
{ {
public string IDString = ""; public string IDString = "";
public bool PostStringMode = false; public bool PostStringMode = false;
public CommandForm(string idString, bool postStringMode) public CommandForm(string idString, bool postStringMode)
{ {
IDString = idString; IDString = idString;
PostStringMode = postStringMode; PostStringMode = postStringMode;
} }
} }
class CommandSubCharsSet class CommandSubCharsSet
{ {
public string Chars = ""; public string Chars = "";
public bool EmptyAllowed = false; public bool EmptyAllowed = false;
} }
} }
+59 -59
View File
@@ -2,71 +2,71 @@
namespace SevenZip.Buffer namespace SevenZip.Buffer
{ {
public class InBuffer public class InBuffer
{ {
byte[] m_Buffer; byte[] m_Buffer;
uint m_Pos; uint m_Pos;
uint m_Limit; uint m_Limit;
uint m_BufferSize; uint m_BufferSize;
System.IO.Stream m_Stream; System.IO.Stream m_Stream;
bool m_StreamWasExhausted; bool m_StreamWasExhausted;
ulong m_ProcessedSize; ulong m_ProcessedSize;
public InBuffer(uint bufferSize) public InBuffer(uint bufferSize)
{ {
m_Buffer = new byte[bufferSize]; m_Buffer = new byte[bufferSize];
m_BufferSize = bufferSize; m_BufferSize = bufferSize;
} }
public void Init(System.IO.Stream stream) public void Init(System.IO.Stream stream)
{ {
m_Stream = stream; m_Stream = stream;
m_ProcessedSize = 0; m_ProcessedSize = 0;
m_Limit = 0; m_Limit = 0;
m_Pos = 0; m_Pos = 0;
m_StreamWasExhausted = false; m_StreamWasExhausted = false;
} }
public bool ReadBlock() public bool ReadBlock()
{ {
if (m_StreamWasExhausted) if (m_StreamWasExhausted)
return false; return false;
m_ProcessedSize += m_Pos; m_ProcessedSize += m_Pos;
int aNumProcessedBytes = m_Stream.Read(m_Buffer, 0, (int)m_BufferSize); int aNumProcessedBytes = m_Stream.Read(m_Buffer, 0, (int)m_BufferSize);
m_Pos = 0; m_Pos = 0;
m_Limit = (uint)aNumProcessedBytes; m_Limit = (uint)aNumProcessedBytes;
m_StreamWasExhausted = (aNumProcessedBytes == 0); m_StreamWasExhausted = (aNumProcessedBytes == 0);
return (!m_StreamWasExhausted); return (!m_StreamWasExhausted);
} }
public void ReleaseStream() public void ReleaseStream()
{ {
// m_Stream.Close(); // m_Stream.Close();
m_Stream = null; m_Stream = null;
} }
public bool ReadByte(byte b) // check it public bool ReadByte(byte b) // check it
{ {
if (m_Pos >= m_Limit) if (m_Pos >= m_Limit)
if (!ReadBlock()) if (!ReadBlock())
return false; return false;
b = m_Buffer[m_Pos++]; b = m_Buffer[m_Pos++];
return true; return true;
} }
public byte ReadByte() public byte ReadByte()
{ {
// return (byte)m_Stream.ReadByte(); // return (byte)m_Stream.ReadByte();
if (m_Pos >= m_Limit) if (m_Pos >= m_Limit)
if (!ReadBlock()) if (!ReadBlock())
return 0xFF; return 0xFF;
return m_Buffer[m_Pos++]; return m_Buffer[m_Pos++];
} }
public ulong GetProcessedSize() public ulong GetProcessedSize()
{ {
return m_ProcessedSize + m_Pos; return m_ProcessedSize + m_Pos;
} }
} }
} }
+36 -36
View File
@@ -2,46 +2,46 @@
namespace SevenZip.Buffer namespace SevenZip.Buffer
{ {
public class OutBuffer public class OutBuffer
{ {
byte[] m_Buffer; byte[] m_Buffer;
uint m_Pos; uint m_Pos;
uint m_BufferSize; uint m_BufferSize;
System.IO.Stream m_Stream; System.IO.Stream m_Stream;
ulong m_ProcessedSize; ulong m_ProcessedSize;
public OutBuffer(uint bufferSize) public OutBuffer(uint bufferSize)
{ {
m_Buffer = new byte[bufferSize]; m_Buffer = new byte[bufferSize];
m_BufferSize = bufferSize; m_BufferSize = bufferSize;
} }
public void SetStream(System.IO.Stream stream) { m_Stream = stream; } public void SetStream(System.IO.Stream stream) { m_Stream = stream; }
public void FlushStream() { m_Stream.Flush(); } public void FlushStream() { m_Stream.Flush(); }
public void CloseStream() { m_Stream.Close(); } public void CloseStream() { m_Stream.Close(); }
public void ReleaseStream() { m_Stream = null; } public void ReleaseStream() { m_Stream = null; }
public void Init() public void Init()
{ {
m_ProcessedSize = 0; m_ProcessedSize = 0;
m_Pos = 0; m_Pos = 0;
} }
public void WriteByte(byte b) public void WriteByte(byte b)
{ {
m_Buffer[m_Pos++] = b; m_Buffer[m_Pos++] = b;
if (m_Pos >= m_BufferSize) if (m_Pos >= m_BufferSize)
FlushData(); FlushData();
} }
public void FlushData() public void FlushData()
{ {
if (m_Pos == 0) if (m_Pos == 0)
return; return;
m_Stream.Write(m_Buffer, 0, (int)m_Pos); m_Stream.Write(m_Buffer, 0, (int)m_Pos);
m_Pos = 0; m_Pos = 0;
} }
public ulong GetProcessedSize() { return m_ProcessedSize + m_Pos; } public ulong GetProcessedSize() { return m_ProcessedSize + m_Pos; }
} }
} }
+16 -16
View File
@@ -4,21 +4,21 @@ using System;
namespace SevenZip.Compression.LZ namespace SevenZip.Compression.LZ
{ {
interface IInWindowStream interface IInWindowStream
{ {
void SetStream(System.IO.Stream inStream); void SetStream(System.IO.Stream inStream);
void Init(); void Init();
void ReleaseStream(); void ReleaseStream();
Byte GetIndexByte(Int32 index); Byte GetIndexByte(Int32 index);
UInt32 GetMatchLen(Int32 index, UInt32 distance, UInt32 limit); UInt32 GetMatchLen(Int32 index, UInt32 distance, UInt32 limit);
UInt32 GetNumAvailableBytes(); UInt32 GetNumAvailableBytes();
} }
interface IMatchFinder : IInWindowStream interface IMatchFinder : IInWindowStream
{ {
void Create(UInt32 historySize, UInt32 keepAddBufferBefore, void Create(UInt32 historySize, UInt32 keepAddBufferBefore,
UInt32 matchMaxLen, UInt32 keepAddBufferAfter); UInt32 matchMaxLen, UInt32 keepAddBufferAfter);
UInt32 GetMatches(UInt32[] distances); UInt32 GetMatches(UInt32[] distances);
void Skip(UInt32 num); void Skip(UInt32 num);
} }
} }
+324 -324
View File
@@ -4,364 +4,364 @@ using System;
namespace SevenZip.Compression.LZ namespace SevenZip.Compression.LZ
{ {
public class BinTree : InWindow, IMatchFinder public class BinTree : InWindow, IMatchFinder
{ {
UInt32 _cyclicBufferPos; UInt32 _cyclicBufferPos;
UInt32 _cyclicBufferSize = 0; UInt32 _cyclicBufferSize = 0;
UInt32 _matchMaxLen; UInt32 _matchMaxLen;
UInt32[] _son; UInt32[] _son;
UInt32[] _hash; UInt32[] _hash;
UInt32 _cutValue = 0xFF; UInt32 _cutValue = 0xFF;
UInt32 _hashMask; UInt32 _hashMask;
UInt32 _hashSizeSum = 0; UInt32 _hashSizeSum = 0;
bool HASH_ARRAY = true; bool HASH_ARRAY = true;
const UInt32 kHash2Size = 1 << 10; const UInt32 kHash2Size = 1 << 10;
const UInt32 kHash3Size = 1 << 16; const UInt32 kHash3Size = 1 << 16;
const UInt32 kBT2HashSize = 1 << 16; const UInt32 kBT2HashSize = 1 << 16;
const UInt32 kStartMaxLen = 1; const UInt32 kStartMaxLen = 1;
const UInt32 kHash3Offset = kHash2Size; const UInt32 kHash3Offset = kHash2Size;
const UInt32 kEmptyHashValue = 0; const UInt32 kEmptyHashValue = 0;
const UInt32 kMaxValForNormalize = ((UInt32)1 << 31) - 1; const UInt32 kMaxValForNormalize = ((UInt32)1 << 31) - 1;
UInt32 kNumHashDirectBytes = 0;
UInt32 kMinMatchCheck = 4;
UInt32 kFixHashSize = kHash2Size + kHash3Size;
public void SetType(int numHashBytes)
{
HASH_ARRAY = (numHashBytes > 2);
if (HASH_ARRAY)
{
kNumHashDirectBytes = 0;
kMinMatchCheck = 4;
kFixHashSize = kHash2Size + kHash3Size;
}
else
{
kNumHashDirectBytes = 2;
kMinMatchCheck = 2 + 1;
kFixHashSize = 0;
}
}
public new void SetStream(System.IO.Stream stream) { base.SetStream(stream); } UInt32 kNumHashDirectBytes = 0;
public new void ReleaseStream() { base.ReleaseStream(); } UInt32 kMinMatchCheck = 4;
UInt32 kFixHashSize = kHash2Size + kHash3Size;
public new void Init()
{
base.Init();
for (UInt32 i = 0; i < _hashSizeSum; i++)
_hash[i] = kEmptyHashValue;
_cyclicBufferPos = 0;
ReduceOffsets(-1);
}
public new void MovePos() public void SetType(int numHashBytes)
{ {
if (++_cyclicBufferPos >= _cyclicBufferSize) HASH_ARRAY = (numHashBytes > 2);
_cyclicBufferPos = 0; if (HASH_ARRAY)
base.MovePos(); {
if (_pos == kMaxValForNormalize) kNumHashDirectBytes = 0;
Normalize(); kMinMatchCheck = 4;
} kFixHashSize = kHash2Size + kHash3Size;
}
else
{
kNumHashDirectBytes = 2;
kMinMatchCheck = 2 + 1;
kFixHashSize = 0;
}
}
public new Byte GetIndexByte(Int32 index) { return base.GetIndexByte(index); } public new void SetStream(System.IO.Stream stream) { base.SetStream(stream); }
public new void ReleaseStream() { base.ReleaseStream(); }
public new UInt32 GetMatchLen(Int32 index, UInt32 distance, UInt32 limit) public new void Init()
{ return base.GetMatchLen(index, distance, limit); } {
base.Init();
for (UInt32 i = 0; i < _hashSizeSum; i++)
_hash[i] = kEmptyHashValue;
_cyclicBufferPos = 0;
ReduceOffsets(-1);
}
public new UInt32 GetNumAvailableBytes() { return base.GetNumAvailableBytes(); } public new void MovePos()
{
if (++_cyclicBufferPos >= _cyclicBufferSize)
_cyclicBufferPos = 0;
base.MovePos();
if (_pos == kMaxValForNormalize)
Normalize();
}
public void Create(UInt32 historySize, UInt32 keepAddBufferBefore, public new Byte GetIndexByte(Int32 index) { return base.GetIndexByte(index); }
UInt32 matchMaxLen, UInt32 keepAddBufferAfter)
{
if (historySize > kMaxValForNormalize - 256)
throw new Exception();
_cutValue = 16 + (matchMaxLen >> 1);
UInt32 windowReservSize = (historySize + keepAddBufferBefore +
matchMaxLen + keepAddBufferAfter) / 2 + 256;
base.Create(historySize + keepAddBufferBefore, matchMaxLen + keepAddBufferAfter, windowReservSize); public new UInt32 GetMatchLen(Int32 index, UInt32 distance, UInt32 limit)
{ return base.GetMatchLen(index, distance, limit); }
_matchMaxLen = matchMaxLen; public new UInt32 GetNumAvailableBytes() { return base.GetNumAvailableBytes(); }
UInt32 cyclicBufferSize = historySize + 1; public void Create(UInt32 historySize, UInt32 keepAddBufferBefore,
if (_cyclicBufferSize != cyclicBufferSize) UInt32 matchMaxLen, UInt32 keepAddBufferAfter)
_son = new UInt32[(_cyclicBufferSize = cyclicBufferSize) * 2]; {
if (historySize > kMaxValForNormalize - 256)
throw new Exception();
_cutValue = 16 + (matchMaxLen >> 1);
UInt32 hs = kBT2HashSize; UInt32 windowReservSize = (historySize + keepAddBufferBefore +
matchMaxLen + keepAddBufferAfter) / 2 + 256;
if (HASH_ARRAY) base.Create(historySize + keepAddBufferBefore, matchMaxLen + keepAddBufferAfter, windowReservSize);
{
hs = historySize - 1;
hs |= (hs >> 1);
hs |= (hs >> 2);
hs |= (hs >> 4);
hs |= (hs >> 8);
hs >>= 1;
hs |= 0xFFFF;
if (hs > (1 << 24))
hs >>= 1;
_hashMask = hs;
hs++;
hs += kFixHashSize;
}
if (hs != _hashSizeSum)
_hash = new UInt32[_hashSizeSum = hs];
}
public UInt32 GetMatches(UInt32[] distances) _matchMaxLen = matchMaxLen;
{
UInt32 lenLimit;
if (_pos + _matchMaxLen <= _streamPos)
lenLimit = _matchMaxLen;
else
{
lenLimit = _streamPos - _pos;
if (lenLimit < kMinMatchCheck)
{
MovePos();
return 0;
}
}
UInt32 offset = 0; UInt32 cyclicBufferSize = historySize + 1;
UInt32 matchMinPos = (_pos > _cyclicBufferSize) ? (_pos - _cyclicBufferSize) : 0; if (_cyclicBufferSize != cyclicBufferSize)
UInt32 cur = _bufferOffset + _pos; _son = new UInt32[(_cyclicBufferSize = cyclicBufferSize) * 2];
UInt32 maxLen = kStartMaxLen; // to avoid items for len < hashSize;
UInt32 hashValue, hash2Value = 0, hash3Value = 0;
if (HASH_ARRAY) UInt32 hs = kBT2HashSize;
{
UInt32 temp = CRC.Table[_bufferBase[cur]] ^ _bufferBase[cur + 1];
hash2Value = temp & (kHash2Size - 1);
temp ^= ((UInt32)(_bufferBase[cur + 2]) << 8);
hash3Value = temp & (kHash3Size - 1);
hashValue = (temp ^ (CRC.Table[_bufferBase[cur + 3]] << 5)) & _hashMask;
}
else
hashValue = _bufferBase[cur] ^ ((UInt32)(_bufferBase[cur + 1]) << 8);
UInt32 curMatch = _hash[kFixHashSize + hashValue]; if (HASH_ARRAY)
if (HASH_ARRAY) {
{ hs = historySize - 1;
UInt32 curMatch2 = _hash[hash2Value]; hs |= (hs >> 1);
UInt32 curMatch3 = _hash[kHash3Offset + hash3Value]; hs |= (hs >> 2);
_hash[hash2Value] = _pos; hs |= (hs >> 4);
_hash[kHash3Offset + hash3Value] = _pos; hs |= (hs >> 8);
if (curMatch2 > matchMinPos) hs >>= 1;
if (_bufferBase[_bufferOffset + curMatch2] == _bufferBase[cur]) hs |= 0xFFFF;
{ if (hs > (1 << 24))
distances[offset++] = maxLen = 2; hs >>= 1;
distances[offset++] = _pos - curMatch2 - 1; _hashMask = hs;
} hs++;
if (curMatch3 > matchMinPos) hs += kFixHashSize;
if (_bufferBase[_bufferOffset + curMatch3] == _bufferBase[cur]) }
{ if (hs != _hashSizeSum)
if (curMatch3 == curMatch2) _hash = new UInt32[_hashSizeSum = hs];
offset -= 2; }
distances[offset++] = maxLen = 3;
distances[offset++] = _pos - curMatch3 - 1;
curMatch2 = curMatch3;
}
if (offset != 0 && curMatch2 == curMatch)
{
offset -= 2;
maxLen = kStartMaxLen;
}
}
_hash[kFixHashSize + hashValue] = _pos; public UInt32 GetMatches(UInt32[] distances)
{
UInt32 lenLimit;
if (_pos + _matchMaxLen <= _streamPos)
lenLimit = _matchMaxLen;
else
{
lenLimit = _streamPos - _pos;
if (lenLimit < kMinMatchCheck)
{
MovePos();
return 0;
}
}
UInt32 ptr0 = (_cyclicBufferPos << 1) + 1; UInt32 offset = 0;
UInt32 ptr1 = (_cyclicBufferPos << 1); UInt32 matchMinPos = (_pos > _cyclicBufferSize) ? (_pos - _cyclicBufferSize) : 0;
UInt32 cur = _bufferOffset + _pos;
UInt32 maxLen = kStartMaxLen; // to avoid items for len < hashSize;
UInt32 hashValue, hash2Value = 0, hash3Value = 0;
UInt32 len0, len1; if (HASH_ARRAY)
len0 = len1 = kNumHashDirectBytes; {
UInt32 temp = CRC.Table[_bufferBase[cur]] ^ _bufferBase[cur + 1];
if (kNumHashDirectBytes != 0) hash2Value = temp & (kHash2Size - 1);
{ temp ^= ((UInt32)(_bufferBase[cur + 2]) << 8);
if (curMatch > matchMinPos) hash3Value = temp & (kHash3Size - 1);
{ hashValue = (temp ^ (CRC.Table[_bufferBase[cur + 3]] << 5)) & _hashMask;
if (_bufferBase[_bufferOffset + curMatch + kNumHashDirectBytes] != }
_bufferBase[cur + kNumHashDirectBytes]) else
{ hashValue = _bufferBase[cur] ^ ((UInt32)(_bufferBase[cur + 1]) << 8);
distances[offset++] = maxLen = kNumHashDirectBytes;
distances[offset++] = _pos - curMatch - 1;
}
}
}
UInt32 count = _cutValue;
while(true)
{
if(curMatch <= matchMinPos || count-- == 0)
{
_son[ptr0] = _son[ptr1] = kEmptyHashValue;
break;
}
UInt32 delta = _pos - curMatch;
UInt32 cyclicPos = ((delta <= _cyclicBufferPos) ?
(_cyclicBufferPos - delta) :
(_cyclicBufferPos - delta + _cyclicBufferSize)) << 1;
UInt32 pby1 = _bufferOffset + curMatch; UInt32 curMatch = _hash[kFixHashSize + hashValue];
UInt32 len = Math.Min(len0, len1); if (HASH_ARRAY)
if (_bufferBase[pby1 + len] == _bufferBase[cur + len]) {
{ UInt32 curMatch2 = _hash[hash2Value];
while(++len != lenLimit) UInt32 curMatch3 = _hash[kHash3Offset + hash3Value];
if (_bufferBase[pby1 + len] != _bufferBase[cur + len]) _hash[hash2Value] = _pos;
break; _hash[kHash3Offset + hash3Value] = _pos;
if (maxLen < len) if (curMatch2 > matchMinPos)
{ if (_bufferBase[_bufferOffset + curMatch2] == _bufferBase[cur])
distances[offset++] = maxLen = len; {
distances[offset++] = delta - 1; distances[offset++] = maxLen = 2;
if (len == lenLimit) distances[offset++] = _pos - curMatch2 - 1;
{ }
_son[ptr1] = _son[cyclicPos]; if (curMatch3 > matchMinPos)
_son[ptr0] = _son[cyclicPos + 1]; if (_bufferBase[_bufferOffset + curMatch3] == _bufferBase[cur])
break; {
} if (curMatch3 == curMatch2)
} offset -= 2;
} distances[offset++] = maxLen = 3;
if (_bufferBase[pby1 + len] < _bufferBase[cur + len]) distances[offset++] = _pos - curMatch3 - 1;
{ curMatch2 = curMatch3;
_son[ptr1] = curMatch; }
ptr1 = cyclicPos + 1; if (offset != 0 && curMatch2 == curMatch)
curMatch = _son[ptr1]; {
len1 = len; offset -= 2;
} maxLen = kStartMaxLen;
else }
{ }
_son[ptr0] = curMatch;
ptr0 = cyclicPos;
curMatch = _son[ptr0];
len0 = len;
}
}
MovePos();
return offset;
}
public void Skip(UInt32 num) _hash[kFixHashSize + hashValue] = _pos;
{
do
{
UInt32 lenLimit;
if (_pos + _matchMaxLen <= _streamPos)
lenLimit = _matchMaxLen;
else
{
lenLimit = _streamPos - _pos;
if (lenLimit < kMinMatchCheck)
{
MovePos();
continue;
}
}
UInt32 matchMinPos = (_pos > _cyclicBufferSize) ? (_pos - _cyclicBufferSize) : 0; UInt32 ptr0 = (_cyclicBufferPos << 1) + 1;
UInt32 cur = _bufferOffset + _pos; UInt32 ptr1 = (_cyclicBufferPos << 1);
UInt32 hashValue; UInt32 len0, len1;
len0 = len1 = kNumHashDirectBytes;
if (HASH_ARRAY) if (kNumHashDirectBytes != 0)
{ {
UInt32 temp = CRC.Table[_bufferBase[cur]] ^ _bufferBase[cur + 1]; if (curMatch > matchMinPos)
UInt32 hash2Value = temp & (kHash2Size - 1); {
_hash[hash2Value] = _pos; if (_bufferBase[_bufferOffset + curMatch + kNumHashDirectBytes] !=
temp ^= ((UInt32)(_bufferBase[cur + 2]) << 8); _bufferBase[cur + kNumHashDirectBytes])
UInt32 hash3Value = temp & (kHash3Size - 1); {
_hash[kHash3Offset + hash3Value] = _pos; distances[offset++] = maxLen = kNumHashDirectBytes;
hashValue = (temp ^ (CRC.Table[_bufferBase[cur + 3]] << 5)) & _hashMask; distances[offset++] = _pos - curMatch - 1;
} }
else }
hashValue = _bufferBase[cur] ^ ((UInt32)(_bufferBase[cur + 1]) << 8); }
UInt32 curMatch = _hash[kFixHashSize + hashValue]; UInt32 count = _cutValue;
_hash[kFixHashSize + hashValue] = _pos;
UInt32 ptr0 = (_cyclicBufferPos << 1) + 1; while (true)
UInt32 ptr1 = (_cyclicBufferPos << 1); {
if (curMatch <= matchMinPos || count-- == 0)
{
_son[ptr0] = _son[ptr1] = kEmptyHashValue;
break;
}
UInt32 delta = _pos - curMatch;
UInt32 cyclicPos = ((delta <= _cyclicBufferPos) ?
(_cyclicBufferPos - delta) :
(_cyclicBufferPos - delta + _cyclicBufferSize)) << 1;
UInt32 len0, len1; UInt32 pby1 = _bufferOffset + curMatch;
len0 = len1 = kNumHashDirectBytes; UInt32 len = Math.Min(len0, len1);
if (_bufferBase[pby1 + len] == _bufferBase[cur + len])
{
while (++len != lenLimit)
if (_bufferBase[pby1 + len] != _bufferBase[cur + len])
break;
if (maxLen < len)
{
distances[offset++] = maxLen = len;
distances[offset++] = delta - 1;
if (len == lenLimit)
{
_son[ptr1] = _son[cyclicPos];
_son[ptr0] = _son[cyclicPos + 1];
break;
}
}
}
if (_bufferBase[pby1 + len] < _bufferBase[cur + len])
{
_son[ptr1] = curMatch;
ptr1 = cyclicPos + 1;
curMatch = _son[ptr1];
len1 = len;
}
else
{
_son[ptr0] = curMatch;
ptr0 = cyclicPos;
curMatch = _son[ptr0];
len0 = len;
}
}
MovePos();
return offset;
}
UInt32 count = _cutValue; public void Skip(UInt32 num)
while (true) {
{ do
if (curMatch <= matchMinPos || count-- == 0) {
{ UInt32 lenLimit;
_son[ptr0] = _son[ptr1] = kEmptyHashValue; if (_pos + _matchMaxLen <= _streamPos)
break; lenLimit = _matchMaxLen;
} else
{
lenLimit = _streamPos - _pos;
if (lenLimit < kMinMatchCheck)
{
MovePos();
continue;
}
}
UInt32 delta = _pos - curMatch; UInt32 matchMinPos = (_pos > _cyclicBufferSize) ? (_pos - _cyclicBufferSize) : 0;
UInt32 cyclicPos = ((delta <= _cyclicBufferPos) ? UInt32 cur = _bufferOffset + _pos;
(_cyclicBufferPos - delta) :
(_cyclicBufferPos - delta + _cyclicBufferSize)) << 1;
UInt32 pby1 = _bufferOffset + curMatch; UInt32 hashValue;
UInt32 len = Math.Min(len0, len1);
if (_bufferBase[pby1 + len] == _bufferBase[cur + len])
{
while (++len != lenLimit)
if (_bufferBase[pby1 + len] != _bufferBase[cur + len])
break;
if (len == lenLimit)
{
_son[ptr1] = _son[cyclicPos];
_son[ptr0] = _son[cyclicPos + 1];
break;
}
}
if (_bufferBase[pby1 + len] < _bufferBase[cur + len])
{
_son[ptr1] = curMatch;
ptr1 = cyclicPos + 1;
curMatch = _son[ptr1];
len1 = len;
}
else
{
_son[ptr0] = curMatch;
ptr0 = cyclicPos;
curMatch = _son[ptr0];
len0 = len;
}
}
MovePos();
}
while (--num != 0);
}
void NormalizeLinks(UInt32[] items, UInt32 numItems, UInt32 subValue) if (HASH_ARRAY)
{ {
for (UInt32 i = 0; i < numItems; i++) UInt32 temp = CRC.Table[_bufferBase[cur]] ^ _bufferBase[cur + 1];
{ UInt32 hash2Value = temp & (kHash2Size - 1);
UInt32 value = items[i]; _hash[hash2Value] = _pos;
if (value <= subValue) temp ^= ((UInt32)(_bufferBase[cur + 2]) << 8);
value = kEmptyHashValue; UInt32 hash3Value = temp & (kHash3Size - 1);
else _hash[kHash3Offset + hash3Value] = _pos;
value -= subValue; hashValue = (temp ^ (CRC.Table[_bufferBase[cur + 3]] << 5)) & _hashMask;
items[i] = value; }
} else
} hashValue = _bufferBase[cur] ^ ((UInt32)(_bufferBase[cur + 1]) << 8);
void Normalize() UInt32 curMatch = _hash[kFixHashSize + hashValue];
{ _hash[kFixHashSize + hashValue] = _pos;
UInt32 subValue = _pos - _cyclicBufferSize;
NormalizeLinks(_son, _cyclicBufferSize * 2, subValue);
NormalizeLinks(_hash, _hashSizeSum, subValue);
ReduceOffsets((Int32)subValue);
}
public void SetCutValue(UInt32 cutValue) { _cutValue = cutValue; } UInt32 ptr0 = (_cyclicBufferPos << 1) + 1;
} UInt32 ptr1 = (_cyclicBufferPos << 1);
UInt32 len0, len1;
len0 = len1 = kNumHashDirectBytes;
UInt32 count = _cutValue;
while (true)
{
if (curMatch <= matchMinPos || count-- == 0)
{
_son[ptr0] = _son[ptr1] = kEmptyHashValue;
break;
}
UInt32 delta = _pos - curMatch;
UInt32 cyclicPos = ((delta <= _cyclicBufferPos) ?
(_cyclicBufferPos - delta) :
(_cyclicBufferPos - delta + _cyclicBufferSize)) << 1;
UInt32 pby1 = _bufferOffset + curMatch;
UInt32 len = Math.Min(len0, len1);
if (_bufferBase[pby1 + len] == _bufferBase[cur + len])
{
while (++len != lenLimit)
if (_bufferBase[pby1 + len] != _bufferBase[cur + len])
break;
if (len == lenLimit)
{
_son[ptr1] = _son[cyclicPos];
_son[ptr0] = _son[cyclicPos + 1];
break;
}
}
if (_bufferBase[pby1 + len] < _bufferBase[cur + len])
{
_son[ptr1] = curMatch;
ptr1 = cyclicPos + 1;
curMatch = _son[ptr1];
len1 = len;
}
else
{
_son[ptr0] = curMatch;
ptr0 = cyclicPos;
curMatch = _son[ptr0];
len0 = len;
}
}
MovePos();
}
while (--num != 0);
}
void NormalizeLinks(UInt32[] items, UInt32 numItems, UInt32 subValue)
{
for (UInt32 i = 0; i < numItems; i++)
{
UInt32 value = items[i];
if (value <= subValue)
value = kEmptyHashValue;
else
value -= subValue;
items[i] = value;
}
}
void Normalize()
{
UInt32 subValue = _pos - _cyclicBufferSize;
NormalizeLinks(_son, _cyclicBufferSize * 2, subValue);
NormalizeLinks(_hash, _hashSizeSum, subValue);
ReduceOffsets((Int32)subValue);
}
public void SetCutValue(UInt32 cutValue) { _cutValue = cutValue; }
}
} }
+108 -108
View File
@@ -4,129 +4,129 @@ using System;
namespace SevenZip.Compression.LZ namespace SevenZip.Compression.LZ
{ {
public class InWindow public class InWindow
{ {
public Byte[] _bufferBase = null; // pointer to buffer with data public Byte[] _bufferBase = null; // pointer to buffer with data
System.IO.Stream _stream; System.IO.Stream _stream;
UInt32 _posLimit; // offset (from _buffer) of first byte when new block reading must be done UInt32 _posLimit; // offset (from _buffer) of first byte when new block reading must be done
bool _streamEndWasReached; // if (true) then _streamPos shows real end of stream bool _streamEndWasReached; // if (true) then _streamPos shows real end of stream
UInt32 _pointerToLastSafePosition; UInt32 _pointerToLastSafePosition;
public UInt32 _bufferOffset; public UInt32 _bufferOffset;
public UInt32 _blockSize; // Size of Allocated memory block public UInt32 _blockSize; // Size of Allocated memory block
public UInt32 _pos; // offset (from _buffer) of curent byte public UInt32 _pos; // offset (from _buffer) of curent byte
UInt32 _keepSizeBefore; // how many BYTEs must be kept in buffer before _pos UInt32 _keepSizeBefore; // how many BYTEs must be kept in buffer before _pos
UInt32 _keepSizeAfter; // how many BYTEs must be kept buffer after _pos UInt32 _keepSizeAfter; // how many BYTEs must be kept buffer after _pos
public UInt32 _streamPos; // offset (from _buffer) of first not read byte from Stream public UInt32 _streamPos; // offset (from _buffer) of first not read byte from Stream
public void MoveBlock() public void MoveBlock()
{ {
UInt32 offset = (UInt32)(_bufferOffset) + _pos - _keepSizeBefore; UInt32 offset = (UInt32)(_bufferOffset) + _pos - _keepSizeBefore;
// we need one additional byte, since MovePos moves on 1 byte. // we need one additional byte, since MovePos moves on 1 byte.
if (offset > 0) if (offset > 0)
offset--; offset--;
UInt32 numBytes = (UInt32)(_bufferOffset) + _streamPos - offset;
// check negative offset ???? UInt32 numBytes = (UInt32)(_bufferOffset) + _streamPos - offset;
for (UInt32 i = 0; i < numBytes; i++)
_bufferBase[i] = _bufferBase[offset + i];
_bufferOffset -= offset;
}
public virtual void ReadBlock() // check negative offset ????
{ for (UInt32 i = 0; i < numBytes; i++)
if (_streamEndWasReached) _bufferBase[i] = _bufferBase[offset + i];
return; _bufferOffset -= offset;
while (true) }
{
int size = (int)((0 - _bufferOffset) + _blockSize - _streamPos);
if (size == 0)
return;
int numReadBytes = _stream.Read(_bufferBase, (int)(_bufferOffset + _streamPos), size);
if (numReadBytes == 0)
{
_posLimit = _streamPos;
UInt32 pointerToPostion = _bufferOffset + _posLimit;
if (pointerToPostion > _pointerToLastSafePosition)
_posLimit = (UInt32)(_pointerToLastSafePosition - _bufferOffset);
_streamEndWasReached = true; public virtual void ReadBlock()
return; {
} if (_streamEndWasReached)
_streamPos += (UInt32)numReadBytes; return;
if (_streamPos >= _pos + _keepSizeAfter) while (true)
_posLimit = _streamPos - _keepSizeAfter; {
} int size = (int)((0 - _bufferOffset) + _blockSize - _streamPos);
} if (size == 0)
return;
int numReadBytes = _stream.Read(_bufferBase, (int)(_bufferOffset + _streamPos), size);
if (numReadBytes == 0)
{
_posLimit = _streamPos;
UInt32 pointerToPostion = _bufferOffset + _posLimit;
if (pointerToPostion > _pointerToLastSafePosition)
_posLimit = (UInt32)(_pointerToLastSafePosition - _bufferOffset);
void Free() { _bufferBase = null; } _streamEndWasReached = true;
return;
}
_streamPos += (UInt32)numReadBytes;
if (_streamPos >= _pos + _keepSizeAfter)
_posLimit = _streamPos - _keepSizeAfter;
}
}
public void Create(UInt32 keepSizeBefore, UInt32 keepSizeAfter, UInt32 keepSizeReserv) void Free() { _bufferBase = null; }
{
_keepSizeBefore = keepSizeBefore;
_keepSizeAfter = keepSizeAfter;
UInt32 blockSize = keepSizeBefore + keepSizeAfter + keepSizeReserv;
if (_bufferBase == null || _blockSize != blockSize)
{
Free();
_blockSize = blockSize;
_bufferBase = new Byte[_blockSize];
}
_pointerToLastSafePosition = _blockSize - keepSizeAfter;
}
public void SetStream(System.IO.Stream stream) { _stream = stream; } public void Create(UInt32 keepSizeBefore, UInt32 keepSizeAfter, UInt32 keepSizeReserv)
public void ReleaseStream() { _stream = null; } {
_keepSizeBefore = keepSizeBefore;
_keepSizeAfter = keepSizeAfter;
UInt32 blockSize = keepSizeBefore + keepSizeAfter + keepSizeReserv;
if (_bufferBase == null || _blockSize != blockSize)
{
Free();
_blockSize = blockSize;
_bufferBase = new Byte[_blockSize];
}
_pointerToLastSafePosition = _blockSize - keepSizeAfter;
}
public void Init() public void SetStream(System.IO.Stream stream) { _stream = stream; }
{ public void ReleaseStream() { _stream = null; }
_bufferOffset = 0;
_pos = 0;
_streamPos = 0;
_streamEndWasReached = false;
ReadBlock();
}
public void MovePos() public void Init()
{ {
_pos++; _bufferOffset = 0;
if (_pos > _posLimit) _pos = 0;
{ _streamPos = 0;
UInt32 pointerToPostion = _bufferOffset + _pos; _streamEndWasReached = false;
if (pointerToPostion > _pointerToLastSafePosition) ReadBlock();
MoveBlock(); }
ReadBlock();
}
}
public Byte GetIndexByte(Int32 index) { return _bufferBase[_bufferOffset + _pos + index]; } public void MovePos()
{
_pos++;
if (_pos > _posLimit)
{
UInt32 pointerToPostion = _bufferOffset + _pos;
if (pointerToPostion > _pointerToLastSafePosition)
MoveBlock();
ReadBlock();
}
}
// index + limit have not to exceed _keepSizeAfter; public Byte GetIndexByte(Int32 index) { return _bufferBase[_bufferOffset + _pos + index]; }
public UInt32 GetMatchLen(Int32 index, UInt32 distance, UInt32 limit)
{
if (_streamEndWasReached)
if ((_pos + index) + limit > _streamPos)
limit = _streamPos - (UInt32)(_pos + index);
distance++;
// Byte *pby = _buffer + (size_t)_pos + index;
UInt32 pby = _bufferOffset + _pos + (UInt32)index;
UInt32 i; // index + limit have not to exceed _keepSizeAfter;
for (i = 0; i < limit && _bufferBase[pby + i] == _bufferBase[pby + i - distance]; i++); public UInt32 GetMatchLen(Int32 index, UInt32 distance, UInt32 limit)
return i; {
} if (_streamEndWasReached)
if ((_pos + index) + limit > _streamPos)
limit = _streamPos - (UInt32)(_pos + index);
distance++;
// Byte *pby = _buffer + (size_t)_pos + index;
UInt32 pby = _bufferOffset + _pos + (UInt32)index;
public UInt32 GetNumAvailableBytes() { return _streamPos - _pos; } UInt32 i;
for (i = 0; i < limit && _bufferBase[pby + i] == _bufferBase[pby + i - distance]; i++) ;
return i;
}
public void ReduceOffsets(Int32 subValue) public UInt32 GetNumAvailableBytes() { return _streamPos - _pos; }
{
_bufferOffset += (UInt32)subValue; public void ReduceOffsets(Int32 subValue)
_posLimit -= (UInt32)subValue; {
_pos -= (UInt32)subValue; _bufferOffset += (UInt32)subValue;
_streamPos -= (UInt32)subValue; _posLimit -= (UInt32)subValue;
} _pos -= (UInt32)subValue;
} _streamPos -= (UInt32)subValue;
}
}
} }
+97 -97
View File
@@ -2,109 +2,109 @@
namespace SevenZip.Compression.LZ namespace SevenZip.Compression.LZ
{ {
public class OutWindow public class OutWindow
{ {
byte[] _buffer = null; byte[] _buffer = null;
uint _pos; uint _pos;
uint _windowSize = 0; uint _windowSize = 0;
uint _streamPos; uint _streamPos;
System.IO.Stream _stream; System.IO.Stream _stream;
public uint TrainSize = 0; public uint TrainSize = 0;
public void Create(uint windowSize) public void Create(uint windowSize)
{ {
if (_windowSize != windowSize) if (_windowSize != windowSize)
{ {
// System.GC.Collect(); // System.GC.Collect();
_buffer = new byte[windowSize]; _buffer = new byte[windowSize];
} }
_windowSize = windowSize; _windowSize = windowSize;
_pos = 0; _pos = 0;
_streamPos = 0; _streamPos = 0;
} }
public void Init(System.IO.Stream stream, bool solid) public void Init(System.IO.Stream stream, bool solid)
{ {
ReleaseStream(); ReleaseStream();
_stream = stream; _stream = stream;
if (!solid) if (!solid)
{ {
_streamPos = 0; _streamPos = 0;
_pos = 0; _pos = 0;
TrainSize = 0; TrainSize = 0;
} }
} }
public bool Train(System.IO.Stream stream)
{
long len = stream.Length;
uint size = (len < _windowSize) ? (uint)len : _windowSize;
TrainSize = size;
stream.Position = len - size;
_streamPos = _pos = 0;
while (size > 0)
{
uint curSize = _windowSize - _pos;
if (size < curSize)
curSize = size;
int numReadBytes = stream.Read(_buffer, (int)_pos, (int)curSize);
if (numReadBytes == 0)
return false;
size -= (uint)numReadBytes;
_pos += (uint)numReadBytes;
_streamPos += (uint)numReadBytes;
if (_pos == _windowSize)
_streamPos = _pos = 0;
}
return true;
}
public void ReleaseStream() public bool Train(System.IO.Stream stream)
{ {
Flush(); long len = stream.Length;
_stream = null; uint size = (len < _windowSize) ? (uint)len : _windowSize;
} TrainSize = size;
stream.Position = len - size;
_streamPos = _pos = 0;
while (size > 0)
{
uint curSize = _windowSize - _pos;
if (size < curSize)
curSize = size;
int numReadBytes = stream.Read(_buffer, (int)_pos, (int)curSize);
if (numReadBytes == 0)
return false;
size -= (uint)numReadBytes;
_pos += (uint)numReadBytes;
_streamPos += (uint)numReadBytes;
if (_pos == _windowSize)
_streamPos = _pos = 0;
}
return true;
}
public void Flush() public void ReleaseStream()
{ {
uint size = _pos - _streamPos; Flush();
if (size == 0) _stream = null;
return; }
_stream.Write(_buffer, (int)_streamPos, (int)size);
if (_pos >= _windowSize)
_pos = 0;
_streamPos = _pos;
}
public void CopyBlock(uint distance, uint len) public void Flush()
{ {
uint pos = _pos - distance - 1; uint size = _pos - _streamPos;
if (pos >= _windowSize) if (size == 0)
pos += _windowSize; return;
for (; len > 0; len--) _stream.Write(_buffer, (int)_streamPos, (int)size);
{ if (_pos >= _windowSize)
if (pos >= _windowSize) _pos = 0;
pos = 0; _streamPos = _pos;
_buffer[_pos++] = _buffer[pos++]; }
if (_pos >= _windowSize)
Flush();
}
}
public void PutByte(byte b) public void CopyBlock(uint distance, uint len)
{ {
_buffer[_pos++] = b; uint pos = _pos - distance - 1;
if (_pos >= _windowSize) if (pos >= _windowSize)
Flush(); pos += _windowSize;
} for (; len > 0; len--)
{
if (pos >= _windowSize)
pos = 0;
_buffer[_pos++] = _buffer[pos++];
if (_pos >= _windowSize)
Flush();
}
}
public byte GetByte(uint distance) public void PutByte(byte b)
{ {
uint pos = _pos - distance - 1; _buffer[_pos++] = b;
if (pos >= _windowSize) if (_pos >= _windowSize)
pos += _windowSize; Flush();
return _buffer[pos]; }
}
} public byte GetByte(uint distance)
{
uint pos = _pos - distance - 1;
if (pos >= _windowSize)
pos += _windowSize;
return _buffer[pos];
}
}
} }
+59 -59
View File
@@ -2,75 +2,75 @@
namespace SevenZip.Compression.LZMA namespace SevenZip.Compression.LZMA
{ {
internal abstract class Base internal abstract class Base
{ {
public const uint kNumRepDistances = 4; public const uint kNumRepDistances = 4;
public const uint kNumStates = 12; public const uint kNumStates = 12;
// static byte []kLiteralNextStates = {0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 4, 5}; // static byte []kLiteralNextStates = {0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 4, 5};
// static byte []kMatchNextStates = {7, 7, 7, 7, 7, 7, 7, 10, 10, 10, 10, 10}; // static byte []kMatchNextStates = {7, 7, 7, 7, 7, 7, 7, 10, 10, 10, 10, 10};
// static byte []kRepNextStates = {8, 8, 8, 8, 8, 8, 8, 11, 11, 11, 11, 11}; // static byte []kRepNextStates = {8, 8, 8, 8, 8, 8, 8, 11, 11, 11, 11, 11};
// static byte []kShortRepNextStates = {9, 9, 9, 9, 9, 9, 9, 11, 11, 11, 11, 11}; // static byte []kShortRepNextStates = {9, 9, 9, 9, 9, 9, 9, 11, 11, 11, 11, 11};
public struct State public struct State
{ {
public uint Index; public uint Index;
public void Init() { Index = 0; } public void Init() { Index = 0; }
public void UpdateChar() public void UpdateChar()
{ {
if (Index < 4) Index = 0; if (Index < 4) Index = 0;
else if (Index < 10) Index -= 3; else if (Index < 10) Index -= 3;
else Index -= 6; else Index -= 6;
} }
public void UpdateMatch() { Index = (uint)(Index < 7 ? 7 : 10); } public void UpdateMatch() { Index = (uint)(Index < 7 ? 7 : 10); }
public void UpdateRep() { Index = (uint)(Index < 7 ? 8 : 11); } public void UpdateRep() { Index = (uint)(Index < 7 ? 8 : 11); }
public void UpdateShortRep() { Index = (uint)(Index < 7 ? 9 : 11); } public void UpdateShortRep() { Index = (uint)(Index < 7 ? 9 : 11); }
public bool IsCharState() { return Index < 7; } public bool IsCharState() { return Index < 7; }
} }
public const int kNumPosSlotBits = 6; public const int kNumPosSlotBits = 6;
public const int kDicLogSizeMin = 0; public const int kDicLogSizeMin = 0;
// public const int kDicLogSizeMax = 30; // public const int kDicLogSizeMax = 30;
// public const uint kDistTableSizeMax = kDicLogSizeMax * 2; // public const uint kDistTableSizeMax = kDicLogSizeMax * 2;
public const int kNumLenToPosStatesBits = 2; // it's for speed optimization public const int kNumLenToPosStatesBits = 2; // it's for speed optimization
public const uint kNumLenToPosStates = 1 << kNumLenToPosStatesBits; public const uint kNumLenToPosStates = 1 << kNumLenToPosStatesBits;
public const uint kMatchMinLen = 2; public const uint kMatchMinLen = 2;
public static uint GetLenToPosState(uint len) public static uint GetLenToPosState(uint len)
{ {
len -= kMatchMinLen; len -= kMatchMinLen;
if (len < kNumLenToPosStates) if (len < kNumLenToPosStates)
return len; return len;
return (uint)(kNumLenToPosStates - 1); return (uint)(kNumLenToPosStates - 1);
} }
public const int kNumAlignBits = 4; public const int kNumAlignBits = 4;
public const uint kAlignTableSize = 1 << kNumAlignBits; public const uint kAlignTableSize = 1 << kNumAlignBits;
public const uint kAlignMask = (kAlignTableSize - 1); public const uint kAlignMask = (kAlignTableSize - 1);
public const uint kStartPosModelIndex = 4; public const uint kStartPosModelIndex = 4;
public const uint kEndPosModelIndex = 14; public const uint kEndPosModelIndex = 14;
public const uint kNumPosModels = kEndPosModelIndex - kStartPosModelIndex; public const uint kNumPosModels = kEndPosModelIndex - kStartPosModelIndex;
public const uint kNumFullDistances = 1 << ((int)kEndPosModelIndex / 2); public const uint kNumFullDistances = 1 << ((int)kEndPosModelIndex / 2);
public const uint kNumLitPosStatesBitsEncodingMax = 4; public const uint kNumLitPosStatesBitsEncodingMax = 4;
public const uint kNumLitContextBitsMax = 8; public const uint kNumLitContextBitsMax = 8;
public const int kNumPosStatesBitsMax = 4; public const int kNumPosStatesBitsMax = 4;
public const uint kNumPosStatesMax = (1 << kNumPosStatesBitsMax); public const uint kNumPosStatesMax = (1 << kNumPosStatesBitsMax);
public const int kNumPosStatesBitsEncodingMax = 4; public const int kNumPosStatesBitsEncodingMax = 4;
public const uint kNumPosStatesEncodingMax = (1 << kNumPosStatesBitsEncodingMax); public const uint kNumPosStatesEncodingMax = (1 << kNumPosStatesBitsEncodingMax);
public const int kNumLowLenBits = 3; public const int kNumLowLenBits = 3;
public const int kNumMidLenBits = 3; public const int kNumMidLenBits = 3;
public const int kNumHighLenBits = 8; public const int kNumHighLenBits = 8;
public const uint kNumLowLenSymbols = 1 << kNumLowLenBits; public const uint kNumLowLenSymbols = 1 << kNumLowLenBits;
public const uint kNumMidLenSymbols = 1 << kNumMidLenBits; public const uint kNumMidLenSymbols = 1 << kNumMidLenBits;
public const uint kNumLenSymbols = kNumLowLenSymbols + kNumMidLenSymbols + public const uint kNumLenSymbols = kNumLowLenSymbols + kNumMidLenSymbols +
(1 << kNumHighLenBits); (1 << kNumHighLenBits);
public const uint kMatchMaxLen = kMatchMinLen + kNumLenSymbols - 1; public const uint kMatchMaxLen = kMatchMinLen + kNumLenSymbols - 1;
} }
} }
+333 -333
View File
@@ -4,373 +4,373 @@ using System;
namespace SevenZip.Compression.LZMA namespace SevenZip.Compression.LZMA
{ {
using RangeCoder; using RangeCoder;
public class Decoder : ICoder, ISetDecoderProperties // ,System.IO.Stream public class Decoder : ICoder, ISetDecoderProperties // ,System.IO.Stream
{ {
class LenDecoder class LenDecoder
{ {
BitDecoder m_Choice = new BitDecoder(); BitDecoder m_Choice = new BitDecoder();
BitDecoder m_Choice2 = new BitDecoder(); BitDecoder m_Choice2 = new BitDecoder();
BitTreeDecoder[] m_LowCoder = new BitTreeDecoder[Base.kNumPosStatesMax]; BitTreeDecoder[] m_LowCoder = new BitTreeDecoder[Base.kNumPosStatesMax];
BitTreeDecoder[] m_MidCoder = new BitTreeDecoder[Base.kNumPosStatesMax]; BitTreeDecoder[] m_MidCoder = new BitTreeDecoder[Base.kNumPosStatesMax];
BitTreeDecoder m_HighCoder = new BitTreeDecoder(Base.kNumHighLenBits); BitTreeDecoder m_HighCoder = new BitTreeDecoder(Base.kNumHighLenBits);
uint m_NumPosStates = 0; uint m_NumPosStates = 0;
public void Create(uint numPosStates) public void Create(uint numPosStates)
{ {
for (uint posState = m_NumPosStates; posState < numPosStates; posState++) for (uint posState = m_NumPosStates; posState < numPosStates; posState++)
{ {
m_LowCoder[posState] = new BitTreeDecoder(Base.kNumLowLenBits); m_LowCoder[posState] = new BitTreeDecoder(Base.kNumLowLenBits);
m_MidCoder[posState] = new BitTreeDecoder(Base.kNumMidLenBits); m_MidCoder[posState] = new BitTreeDecoder(Base.kNumMidLenBits);
} }
m_NumPosStates = numPosStates; m_NumPosStates = numPosStates;
} }
public void Init() public void Init()
{ {
m_Choice.Init(); m_Choice.Init();
for (uint posState = 0; posState < m_NumPosStates; posState++) for (uint posState = 0; posState < m_NumPosStates; posState++)
{ {
m_LowCoder[posState].Init(); m_LowCoder[posState].Init();
m_MidCoder[posState].Init(); m_MidCoder[posState].Init();
} }
m_Choice2.Init(); m_Choice2.Init();
m_HighCoder.Init(); m_HighCoder.Init();
} }
public uint Decode(RangeCoder.Decoder rangeDecoder, uint posState) public uint Decode(RangeCoder.Decoder rangeDecoder, uint posState)
{ {
if (m_Choice.Decode(rangeDecoder) == 0) if (m_Choice.Decode(rangeDecoder) == 0)
return m_LowCoder[posState].Decode(rangeDecoder); return m_LowCoder[posState].Decode(rangeDecoder);
else else
{ {
uint symbol = Base.kNumLowLenSymbols; uint symbol = Base.kNumLowLenSymbols;
if (m_Choice2.Decode(rangeDecoder) == 0) if (m_Choice2.Decode(rangeDecoder) == 0)
symbol += m_MidCoder[posState].Decode(rangeDecoder); symbol += m_MidCoder[posState].Decode(rangeDecoder);
else else
{ {
symbol += Base.kNumMidLenSymbols; symbol += Base.kNumMidLenSymbols;
symbol += m_HighCoder.Decode(rangeDecoder); symbol += m_HighCoder.Decode(rangeDecoder);
} }
return symbol; return symbol;
} }
} }
} }
class LiteralDecoder class LiteralDecoder
{ {
struct Decoder2 struct Decoder2
{ {
BitDecoder[] m_Decoders; BitDecoder[] m_Decoders;
public void Create() { m_Decoders = new BitDecoder[0x300]; } public void Create() { m_Decoders = new BitDecoder[0x300]; }
public void Init() { for (int i = 0; i < 0x300; i++) m_Decoders[i].Init(); } public void Init() { for (int i = 0; i < 0x300; i++) m_Decoders[i].Init(); }
public byte DecodeNormal(RangeCoder.Decoder rangeDecoder) public byte DecodeNormal(RangeCoder.Decoder rangeDecoder)
{ {
uint symbol = 1; uint symbol = 1;
do do
symbol = (symbol << 1) | m_Decoders[symbol].Decode(rangeDecoder); symbol = (symbol << 1) | m_Decoders[symbol].Decode(rangeDecoder);
while (symbol < 0x100); while (symbol < 0x100);
return (byte)symbol; return (byte)symbol;
} }
public byte DecodeWithMatchByte(RangeCoder.Decoder rangeDecoder, byte matchByte) public byte DecodeWithMatchByte(RangeCoder.Decoder rangeDecoder, byte matchByte)
{ {
uint symbol = 1; uint symbol = 1;
do do
{ {
uint matchBit = (uint)(matchByte >> 7) & 1; uint matchBit = (uint)(matchByte >> 7) & 1;
matchByte <<= 1; matchByte <<= 1;
uint bit = m_Decoders[((1 + matchBit) << 8) + symbol].Decode(rangeDecoder); uint bit = m_Decoders[((1 + matchBit) << 8) + symbol].Decode(rangeDecoder);
symbol = (symbol << 1) | bit; symbol = (symbol << 1) | bit;
if (matchBit != bit) if (matchBit != bit)
{ {
while (symbol < 0x100) while (symbol < 0x100)
symbol = (symbol << 1) | m_Decoders[symbol].Decode(rangeDecoder); symbol = (symbol << 1) | m_Decoders[symbol].Decode(rangeDecoder);
break; break;
} }
} }
while (symbol < 0x100); while (symbol < 0x100);
return (byte)symbol; return (byte)symbol;
} }
} }
Decoder2[] m_Coders; Decoder2[] m_Coders;
int m_NumPrevBits; int m_NumPrevBits;
int m_NumPosBits; int m_NumPosBits;
uint m_PosMask; uint m_PosMask;
public void Create(int numPosBits, int numPrevBits) public void Create(int numPosBits, int numPrevBits)
{ {
if (m_Coders != null && m_NumPrevBits == numPrevBits && if (m_Coders != null && m_NumPrevBits == numPrevBits &&
m_NumPosBits == numPosBits) m_NumPosBits == numPosBits)
return; return;
m_NumPosBits = numPosBits; m_NumPosBits = numPosBits;
m_PosMask = ((uint)1 << numPosBits) - 1; m_PosMask = ((uint)1 << numPosBits) - 1;
m_NumPrevBits = numPrevBits; m_NumPrevBits = numPrevBits;
uint numStates = (uint)1 << (m_NumPrevBits + m_NumPosBits); uint numStates = (uint)1 << (m_NumPrevBits + m_NumPosBits);
m_Coders = new Decoder2[numStates]; m_Coders = new Decoder2[numStates];
for (uint i = 0; i < numStates; i++) for (uint i = 0; i < numStates; i++)
m_Coders[i].Create(); m_Coders[i].Create();
} }
public void Init() public void Init()
{ {
uint numStates = (uint)1 << (m_NumPrevBits + m_NumPosBits); uint numStates = (uint)1 << (m_NumPrevBits + m_NumPosBits);
for (uint i = 0; i < numStates; i++) for (uint i = 0; i < numStates; i++)
m_Coders[i].Init(); m_Coders[i].Init();
} }
uint GetState(uint pos, byte prevByte) uint GetState(uint pos, byte prevByte)
{ return ((pos & m_PosMask) << m_NumPrevBits) + (uint)(prevByte >> (8 - m_NumPrevBits)); } { return ((pos & m_PosMask) << m_NumPrevBits) + (uint)(prevByte >> (8 - m_NumPrevBits)); }
public byte DecodeNormal(RangeCoder.Decoder rangeDecoder, uint pos, byte prevByte) public byte DecodeNormal(RangeCoder.Decoder rangeDecoder, uint pos, byte prevByte)
{ return m_Coders[GetState(pos, prevByte)].DecodeNormal(rangeDecoder); } { return m_Coders[GetState(pos, prevByte)].DecodeNormal(rangeDecoder); }
public byte DecodeWithMatchByte(RangeCoder.Decoder rangeDecoder, uint pos, byte prevByte, byte matchByte) public byte DecodeWithMatchByte(RangeCoder.Decoder rangeDecoder, uint pos, byte prevByte, byte matchByte)
{ return m_Coders[GetState(pos, prevByte)].DecodeWithMatchByte(rangeDecoder, matchByte); } { return m_Coders[GetState(pos, prevByte)].DecodeWithMatchByte(rangeDecoder, matchByte); }
}; };
LZ.OutWindow m_OutWindow = new LZ.OutWindow(); LZ.OutWindow m_OutWindow = new LZ.OutWindow();
RangeCoder.Decoder m_RangeDecoder = new RangeCoder.Decoder(); RangeCoder.Decoder m_RangeDecoder = new RangeCoder.Decoder();
BitDecoder[] m_IsMatchDecoders = new BitDecoder[Base.kNumStates << Base.kNumPosStatesBitsMax]; BitDecoder[] m_IsMatchDecoders = new BitDecoder[Base.kNumStates << Base.kNumPosStatesBitsMax];
BitDecoder[] m_IsRepDecoders = new BitDecoder[Base.kNumStates]; BitDecoder[] m_IsRepDecoders = new BitDecoder[Base.kNumStates];
BitDecoder[] m_IsRepG0Decoders = new BitDecoder[Base.kNumStates]; BitDecoder[] m_IsRepG0Decoders = new BitDecoder[Base.kNumStates];
BitDecoder[] m_IsRepG1Decoders = new BitDecoder[Base.kNumStates]; BitDecoder[] m_IsRepG1Decoders = new BitDecoder[Base.kNumStates];
BitDecoder[] m_IsRepG2Decoders = new BitDecoder[Base.kNumStates]; BitDecoder[] m_IsRepG2Decoders = new BitDecoder[Base.kNumStates];
BitDecoder[] m_IsRep0LongDecoders = new BitDecoder[Base.kNumStates << Base.kNumPosStatesBitsMax]; BitDecoder[] m_IsRep0LongDecoders = new BitDecoder[Base.kNumStates << Base.kNumPosStatesBitsMax];
BitTreeDecoder[] m_PosSlotDecoder = new BitTreeDecoder[Base.kNumLenToPosStates]; BitTreeDecoder[] m_PosSlotDecoder = new BitTreeDecoder[Base.kNumLenToPosStates];
BitDecoder[] m_PosDecoders = new BitDecoder[Base.kNumFullDistances - Base.kEndPosModelIndex]; BitDecoder[] m_PosDecoders = new BitDecoder[Base.kNumFullDistances - Base.kEndPosModelIndex];
BitTreeDecoder m_PosAlignDecoder = new BitTreeDecoder(Base.kNumAlignBits); BitTreeDecoder m_PosAlignDecoder = new BitTreeDecoder(Base.kNumAlignBits);
LenDecoder m_LenDecoder = new LenDecoder(); LenDecoder m_LenDecoder = new LenDecoder();
LenDecoder m_RepLenDecoder = new LenDecoder(); LenDecoder m_RepLenDecoder = new LenDecoder();
LiteralDecoder m_LiteralDecoder = new LiteralDecoder(); LiteralDecoder m_LiteralDecoder = new LiteralDecoder();
uint m_DictionarySize; uint m_DictionarySize;
uint m_DictionarySizeCheck; uint m_DictionarySizeCheck;
uint m_PosStateMask; uint m_PosStateMask;
public Decoder() public Decoder()
{ {
m_DictionarySize = 0xFFFFFFFF; m_DictionarySize = 0xFFFFFFFF;
for (int i = 0; i < Base.kNumLenToPosStates; i++) for (int i = 0; i < Base.kNumLenToPosStates; i++)
m_PosSlotDecoder[i] = new BitTreeDecoder(Base.kNumPosSlotBits); m_PosSlotDecoder[i] = new BitTreeDecoder(Base.kNumPosSlotBits);
} }
void SetDictionarySize(uint dictionarySize) void SetDictionarySize(uint dictionarySize)
{ {
if (m_DictionarySize != dictionarySize) if (m_DictionarySize != dictionarySize)
{ {
m_DictionarySize = dictionarySize; m_DictionarySize = dictionarySize;
m_DictionarySizeCheck = Math.Max(m_DictionarySize, 1); m_DictionarySizeCheck = Math.Max(m_DictionarySize, 1);
uint blockSize = Math.Max(m_DictionarySizeCheck, (1 << 12)); uint blockSize = Math.Max(m_DictionarySizeCheck, (1 << 12));
m_OutWindow.Create(blockSize); m_OutWindow.Create(blockSize);
} }
} }
void SetLiteralProperties(int lp, int lc) void SetLiteralProperties(int lp, int lc)
{ {
if (lp > 8) if (lp > 8)
throw new InvalidParamException(); throw new InvalidParamException();
if (lc > 8) if (lc > 8)
throw new InvalidParamException(); throw new InvalidParamException();
m_LiteralDecoder.Create(lp, lc); m_LiteralDecoder.Create(lp, lc);
} }
void SetPosBitsProperties(int pb) void SetPosBitsProperties(int pb)
{ {
if (pb > Base.kNumPosStatesBitsMax) if (pb > Base.kNumPosStatesBitsMax)
throw new InvalidParamException(); throw new InvalidParamException();
uint numPosStates = (uint)1 << pb; uint numPosStates = (uint)1 << pb;
m_LenDecoder.Create(numPosStates); m_LenDecoder.Create(numPosStates);
m_RepLenDecoder.Create(numPosStates); m_RepLenDecoder.Create(numPosStates);
m_PosStateMask = numPosStates - 1; m_PosStateMask = numPosStates - 1;
} }
bool _solid = false; bool _solid = false;
void Init(System.IO.Stream inStream, System.IO.Stream outStream) void Init(System.IO.Stream inStream, System.IO.Stream outStream)
{ {
m_RangeDecoder.Init(inStream); m_RangeDecoder.Init(inStream);
m_OutWindow.Init(outStream, _solid); m_OutWindow.Init(outStream, _solid);
uint i; uint i;
for (i = 0; i < Base.kNumStates; i++) for (i = 0; i < Base.kNumStates; i++)
{ {
for (uint j = 0; j <= m_PosStateMask; j++) for (uint j = 0; j <= m_PosStateMask; j++)
{ {
uint index = (i << Base.kNumPosStatesBitsMax) + j; uint index = (i << Base.kNumPosStatesBitsMax) + j;
m_IsMatchDecoders[index].Init(); m_IsMatchDecoders[index].Init();
m_IsRep0LongDecoders[index].Init(); m_IsRep0LongDecoders[index].Init();
} }
m_IsRepDecoders[i].Init(); m_IsRepDecoders[i].Init();
m_IsRepG0Decoders[i].Init(); m_IsRepG0Decoders[i].Init();
m_IsRepG1Decoders[i].Init(); m_IsRepG1Decoders[i].Init();
m_IsRepG2Decoders[i].Init(); m_IsRepG2Decoders[i].Init();
} }
m_LiteralDecoder.Init(); m_LiteralDecoder.Init();
for (i = 0; i < Base.kNumLenToPosStates; i++) for (i = 0; i < Base.kNumLenToPosStates; i++)
m_PosSlotDecoder[i].Init(); m_PosSlotDecoder[i].Init();
// m_PosSpecDecoder.Init(); // m_PosSpecDecoder.Init();
for (i = 0; i < Base.kNumFullDistances - Base.kEndPosModelIndex; i++) for (i = 0; i < Base.kNumFullDistances - Base.kEndPosModelIndex; i++)
m_PosDecoders[i].Init(); m_PosDecoders[i].Init();
m_LenDecoder.Init(); m_LenDecoder.Init();
m_RepLenDecoder.Init(); m_RepLenDecoder.Init();
m_PosAlignDecoder.Init(); m_PosAlignDecoder.Init();
} }
public void Code(System.IO.Stream inStream, System.IO.Stream outStream, public void Code(System.IO.Stream inStream, System.IO.Stream outStream,
Int64 inSize, Int64 outSize, ICodeProgress progress) Int64 inSize, Int64 outSize, ICodeProgress progress)
{ {
Init(inStream, outStream); Init(inStream, outStream);
Base.State state = new Base.State(); Base.State state = new Base.State();
state.Init(); state.Init();
uint rep0 = 0, rep1 = 0, rep2 = 0, rep3 = 0; uint rep0 = 0, rep1 = 0, rep2 = 0, rep3 = 0;
UInt64 nowPos64 = 0; UInt64 nowPos64 = 0;
UInt64 outSize64 = (UInt64)outSize; UInt64 outSize64 = (UInt64)outSize;
if (nowPos64 < outSize64) if (nowPos64 < outSize64)
{ {
if (m_IsMatchDecoders[state.Index << Base.kNumPosStatesBitsMax].Decode(m_RangeDecoder) != 0) if (m_IsMatchDecoders[state.Index << Base.kNumPosStatesBitsMax].Decode(m_RangeDecoder) != 0)
throw new DataErrorException(); throw new DataErrorException();
state.UpdateChar(); state.UpdateChar();
byte b = m_LiteralDecoder.DecodeNormal(m_RangeDecoder, 0, 0); byte b = m_LiteralDecoder.DecodeNormal(m_RangeDecoder, 0, 0);
m_OutWindow.PutByte(b); m_OutWindow.PutByte(b);
nowPos64++; nowPos64++;
} }
while (nowPos64 < outSize64) while (nowPos64 < outSize64)
{ {
// UInt64 next = Math.Min(nowPos64 + (1 << 18), outSize64); // UInt64 next = Math.Min(nowPos64 + (1 << 18), outSize64);
// while(nowPos64 < next) // while(nowPos64 < next)
{ {
uint posState = (uint)nowPos64 & m_PosStateMask; uint posState = (uint)nowPos64 & m_PosStateMask;
if (m_IsMatchDecoders[(state.Index << Base.kNumPosStatesBitsMax) + posState].Decode(m_RangeDecoder) == 0) if (m_IsMatchDecoders[(state.Index << Base.kNumPosStatesBitsMax) + posState].Decode(m_RangeDecoder) == 0)
{ {
byte b; byte b;
byte prevByte = m_OutWindow.GetByte(0); byte prevByte = m_OutWindow.GetByte(0);
if (!state.IsCharState()) if (!state.IsCharState())
b = m_LiteralDecoder.DecodeWithMatchByte(m_RangeDecoder, b = m_LiteralDecoder.DecodeWithMatchByte(m_RangeDecoder,
(uint)nowPos64, prevByte, m_OutWindow.GetByte(rep0)); (uint)nowPos64, prevByte, m_OutWindow.GetByte(rep0));
else else
b = m_LiteralDecoder.DecodeNormal(m_RangeDecoder, (uint)nowPos64, prevByte); b = m_LiteralDecoder.DecodeNormal(m_RangeDecoder, (uint)nowPos64, prevByte);
m_OutWindow.PutByte(b); m_OutWindow.PutByte(b);
state.UpdateChar(); state.UpdateChar();
nowPos64++; nowPos64++;
} }
else else
{ {
uint len; uint len;
if (m_IsRepDecoders[state.Index].Decode(m_RangeDecoder) == 1) if (m_IsRepDecoders[state.Index].Decode(m_RangeDecoder) == 1)
{ {
if (m_IsRepG0Decoders[state.Index].Decode(m_RangeDecoder) == 0) if (m_IsRepG0Decoders[state.Index].Decode(m_RangeDecoder) == 0)
{ {
if (m_IsRep0LongDecoders[(state.Index << Base.kNumPosStatesBitsMax) + posState].Decode(m_RangeDecoder) == 0) if (m_IsRep0LongDecoders[(state.Index << Base.kNumPosStatesBitsMax) + posState].Decode(m_RangeDecoder) == 0)
{ {
state.UpdateShortRep(); state.UpdateShortRep();
m_OutWindow.PutByte(m_OutWindow.GetByte(rep0)); m_OutWindow.PutByte(m_OutWindow.GetByte(rep0));
nowPos64++; nowPos64++;
continue; continue;
} }
} }
else else
{ {
UInt32 distance; UInt32 distance;
if (m_IsRepG1Decoders[state.Index].Decode(m_RangeDecoder) == 0) if (m_IsRepG1Decoders[state.Index].Decode(m_RangeDecoder) == 0)
{ {
distance = rep1; distance = rep1;
} }
else else
{ {
if (m_IsRepG2Decoders[state.Index].Decode(m_RangeDecoder) == 0) if (m_IsRepG2Decoders[state.Index].Decode(m_RangeDecoder) == 0)
distance = rep2; distance = rep2;
else else
{ {
distance = rep3; distance = rep3;
rep3 = rep2; rep3 = rep2;
} }
rep2 = rep1; rep2 = rep1;
} }
rep1 = rep0; rep1 = rep0;
rep0 = distance; rep0 = distance;
} }
len = m_RepLenDecoder.Decode(m_RangeDecoder, posState) + Base.kMatchMinLen; len = m_RepLenDecoder.Decode(m_RangeDecoder, posState) + Base.kMatchMinLen;
state.UpdateRep(); state.UpdateRep();
} }
else else
{ {
rep3 = rep2; rep3 = rep2;
rep2 = rep1; rep2 = rep1;
rep1 = rep0; rep1 = rep0;
len = Base.kMatchMinLen + m_LenDecoder.Decode(m_RangeDecoder, posState); len = Base.kMatchMinLen + m_LenDecoder.Decode(m_RangeDecoder, posState);
state.UpdateMatch(); state.UpdateMatch();
uint posSlot = m_PosSlotDecoder[Base.GetLenToPosState(len)].Decode(m_RangeDecoder); uint posSlot = m_PosSlotDecoder[Base.GetLenToPosState(len)].Decode(m_RangeDecoder);
if (posSlot >= Base.kStartPosModelIndex) if (posSlot >= Base.kStartPosModelIndex)
{ {
int numDirectBits = (int)((posSlot >> 1) - 1); int numDirectBits = (int)((posSlot >> 1) - 1);
rep0 = ((2 | (posSlot & 1)) << numDirectBits); rep0 = ((2 | (posSlot & 1)) << numDirectBits);
if (posSlot < Base.kEndPosModelIndex) if (posSlot < Base.kEndPosModelIndex)
rep0 += BitTreeDecoder.ReverseDecode(m_PosDecoders, rep0 += BitTreeDecoder.ReverseDecode(m_PosDecoders,
rep0 - posSlot - 1, m_RangeDecoder, numDirectBits); rep0 - posSlot - 1, m_RangeDecoder, numDirectBits);
else else
{ {
rep0 += (m_RangeDecoder.DecodeDirectBits( rep0 += (m_RangeDecoder.DecodeDirectBits(
numDirectBits - Base.kNumAlignBits) << Base.kNumAlignBits); numDirectBits - Base.kNumAlignBits) << Base.kNumAlignBits);
rep0 += m_PosAlignDecoder.ReverseDecode(m_RangeDecoder); rep0 += m_PosAlignDecoder.ReverseDecode(m_RangeDecoder);
} }
} }
else else
rep0 = posSlot; rep0 = posSlot;
} }
if (rep0 >= m_OutWindow.TrainSize + nowPos64 || rep0 >= m_DictionarySizeCheck) if (rep0 >= m_OutWindow.TrainSize + nowPos64 || rep0 >= m_DictionarySizeCheck)
{ {
if (rep0 == 0xFFFFFFFF) if (rep0 == 0xFFFFFFFF)
break; break;
throw new DataErrorException(); throw new DataErrorException();
} }
m_OutWindow.CopyBlock(rep0, len); m_OutWindow.CopyBlock(rep0, len);
nowPos64 += len; nowPos64 += len;
} }
} }
} }
m_OutWindow.Flush(); m_OutWindow.Flush();
m_OutWindow.ReleaseStream(); m_OutWindow.ReleaseStream();
m_RangeDecoder.ReleaseStream(); m_RangeDecoder.ReleaseStream();
} }
public void SetDecoderProperties(byte[] properties) public void SetDecoderProperties(byte[] properties)
{ {
if (properties.Length < 5) if (properties.Length < 5)
throw new InvalidParamException(); throw new InvalidParamException();
int lc = properties[0] % 9; int lc = properties[0] % 9;
int remainder = properties[0] / 9; int remainder = properties[0] / 9;
int lp = remainder % 5; int lp = remainder % 5;
int pb = remainder / 5; int pb = remainder / 5;
if (pb > Base.kNumPosStatesBitsMax) if (pb > Base.kNumPosStatesBitsMax)
throw new InvalidParamException(); throw new InvalidParamException();
UInt32 dictionarySize = 0; UInt32 dictionarySize = 0;
for (int i = 0; i < 4; i++) for (int i = 0; i < 4; i++)
dictionarySize += ((UInt32)(properties[1 + i])) << (i * 8); dictionarySize += ((UInt32)(properties[1 + i])) << (i * 8);
SetDictionarySize(dictionarySize); SetDictionarySize(dictionarySize);
SetLiteralProperties(lp, lc); SetLiteralProperties(lp, lc);
SetPosBitsProperties(pb); SetPosBitsProperties(pb);
} }
public bool Train(System.IO.Stream stream) public bool Train(System.IO.Stream stream)
{ {
_solid = true; _solid = true;
return m_OutWindow.Train(stream); return m_OutWindow.Train(stream);
} }
/* /*
public override bool CanRead { get { return true; }} public override bool CanRead { get { return true; }}
public override bool CanWrite { get { return true; }} public override bool CanWrite { get { return true; }}
public override bool CanSeek { get { return true; }} public override bool CanSeek { get { return true; }}
@@ -394,5 +394,5 @@ namespace SevenZip.Compression.LZMA
} }
public override void SetLength(long value) {} public override void SetLength(long value) {}
*/ */
} }
} }
File diff suppressed because it is too large Load Diff
+194 -194
View File
@@ -2,192 +2,192 @@ using System;
namespace SevenZip.Compression.RangeCoder namespace SevenZip.Compression.RangeCoder
{ {
class Encoder class Encoder
{ {
public const uint kTopValue = (1 << 24); public const uint kTopValue = (1 << 24);
System.IO.Stream Stream; System.IO.Stream Stream;
public UInt64 Low; public UInt64 Low;
public uint Range; public uint Range;
uint _cacheSize; uint _cacheSize;
byte _cache; byte _cache;
long StartPosition; long StartPosition;
public void SetStream(System.IO.Stream stream) public void SetStream(System.IO.Stream stream)
{ {
Stream = stream; Stream = stream;
} }
public void ReleaseStream() public void ReleaseStream()
{ {
Stream = null; Stream = null;
} }
public void Init() public void Init()
{ {
StartPosition = Stream.Position; StartPosition = Stream.Position;
Low = 0; Low = 0;
Range = 0xFFFFFFFF; Range = 0xFFFFFFFF;
_cacheSize = 1; _cacheSize = 1;
_cache = 0; _cache = 0;
} }
public void FlushData() public void FlushData()
{ {
for (int i = 0; i < 5; i++) for (int i = 0; i < 5; i++)
ShiftLow(); ShiftLow();
} }
public void FlushStream() public void FlushStream()
{ {
Stream.Flush(); Stream.Flush();
} }
public void CloseStream() public void CloseStream()
{ {
Stream.Close(); Stream.Close();
} }
public void Encode(uint start, uint size, uint total) public void Encode(uint start, uint size, uint total)
{ {
Low += start * (Range /= total); Low += start * (Range /= total);
Range *= size; Range *= size;
while (Range < kTopValue) while (Range < kTopValue)
{ {
Range <<= 8; Range <<= 8;
ShiftLow(); ShiftLow();
} }
} }
public void ShiftLow() public void ShiftLow()
{ {
if ((uint)Low < (uint)0xFF000000 || (uint)(Low >> 32) == 1) if ((uint)Low < (uint)0xFF000000 || (uint)(Low >> 32) == 1)
{ {
byte temp = _cache; byte temp = _cache;
do do
{ {
Stream.WriteByte((byte)(temp + (Low >> 32))); Stream.WriteByte((byte)(temp + (Low >> 32)));
temp = 0xFF; temp = 0xFF;
} }
while (--_cacheSize != 0); while (--_cacheSize != 0);
_cache = (byte)(((uint)Low) >> 24); _cache = (byte)(((uint)Low) >> 24);
} }
_cacheSize++; _cacheSize++;
Low = ((uint)Low) << 8; Low = ((uint)Low) << 8;
} }
public void EncodeDirectBits(uint v, int numTotalBits) public void EncodeDirectBits(uint v, int numTotalBits)
{ {
for (int i = numTotalBits - 1; i >= 0; i--) for (int i = numTotalBits - 1; i >= 0; i--)
{ {
Range >>= 1; Range >>= 1;
if (((v >> i) & 1) == 1) if (((v >> i) & 1) == 1)
Low += Range; Low += Range;
if (Range < kTopValue) if (Range < kTopValue)
{ {
Range <<= 8; Range <<= 8;
ShiftLow(); ShiftLow();
} }
} }
} }
public void EncodeBit(uint size0, int numTotalBits, uint symbol) public void EncodeBit(uint size0, int numTotalBits, uint symbol)
{ {
uint newBound = (Range >> numTotalBits) * size0; uint newBound = (Range >> numTotalBits) * size0;
if (symbol == 0) if (symbol == 0)
Range = newBound; Range = newBound;
else else
{ {
Low += newBound; Low += newBound;
Range -= newBound; Range -= newBound;
} }
while (Range < kTopValue) while (Range < kTopValue)
{ {
Range <<= 8; Range <<= 8;
ShiftLow(); ShiftLow();
} }
} }
public long GetProcessedSizeAdd() public long GetProcessedSizeAdd()
{ {
return _cacheSize + return _cacheSize +
Stream.Position - StartPosition + 4; Stream.Position - StartPosition + 4;
// (long)Stream.GetProcessedSize(); // (long)Stream.GetProcessedSize();
} }
} }
class Decoder class Decoder
{ {
public const uint kTopValue = (1 << 24); public const uint kTopValue = (1 << 24);
public uint Range; public uint Range;
public uint Code; public uint Code;
// public Buffer.InBuffer Stream = new Buffer.InBuffer(1 << 16); // public Buffer.InBuffer Stream = new Buffer.InBuffer(1 << 16);
public System.IO.Stream Stream; public System.IO.Stream Stream;
public void Init(System.IO.Stream stream) public void Init(System.IO.Stream stream)
{ {
// Stream.Init(stream); // Stream.Init(stream);
Stream = stream; Stream = stream;
Code = 0; Code = 0;
Range = 0xFFFFFFFF; Range = 0xFFFFFFFF;
for (int i = 0; i < 5; i++) for (int i = 0; i < 5; i++)
Code = (Code << 8) | (byte)Stream.ReadByte(); Code = (Code << 8) | (byte)Stream.ReadByte();
} }
public void ReleaseStream() public void ReleaseStream()
{ {
// Stream.ReleaseStream(); // Stream.ReleaseStream();
Stream = null; Stream = null;
} }
public void CloseStream() public void CloseStream()
{ {
Stream.Close(); Stream.Close();
} }
public void Normalize() public void Normalize()
{ {
while (Range < kTopValue) while (Range < kTopValue)
{ {
Code = (Code << 8) | (byte)Stream.ReadByte(); Code = (Code << 8) | (byte)Stream.ReadByte();
Range <<= 8; Range <<= 8;
} }
} }
public void Normalize2() public void Normalize2()
{ {
if (Range < kTopValue) if (Range < kTopValue)
{ {
Code = (Code << 8) | (byte)Stream.ReadByte(); Code = (Code << 8) | (byte)Stream.ReadByte();
Range <<= 8; Range <<= 8;
} }
} }
public uint GetThreshold(uint total) public uint GetThreshold(uint total)
{ {
return Code / (Range /= total); return Code / (Range /= total);
} }
public void Decode(uint start, uint size, uint total) public void Decode(uint start, uint size, uint total)
{ {
Code -= start * Range; Code -= start * Range;
Range *= size; Range *= size;
Normalize(); Normalize();
} }
public uint DecodeDirectBits(int numTotalBits) public uint DecodeDirectBits(int numTotalBits)
{ {
uint range = Range; uint range = Range;
uint code = Code; uint code = Code;
uint result = 0; uint result = 0;
for (int i = numTotalBits; i > 0; i--) for (int i = numTotalBits; i > 0; i--)
{ {
range >>= 1; range >>= 1;
/* /*
result <<= 1; result <<= 1;
if (code >= range) if (code >= range)
{ {
@@ -195,40 +195,40 @@ namespace SevenZip.Compression.RangeCoder
result |= 1; result |= 1;
} }
*/ */
uint t = (code - range) >> 31; uint t = (code - range) >> 31;
code -= range & (t - 1); code -= range & (t - 1);
result = (result << 1) | (1 - t); result = (result << 1) | (1 - t);
if (range < kTopValue) if (range < kTopValue)
{ {
code = (code << 8) | (byte)Stream.ReadByte(); code = (code << 8) | (byte)Stream.ReadByte();
range <<= 8; range <<= 8;
} }
} }
Range = range; Range = range;
Code = code; Code = code;
return result; return result;
} }
public uint DecodeBit(uint size0, int numTotalBits) public uint DecodeBit(uint size0, int numTotalBits)
{ {
uint newBound = (Range >> numTotalBits) * size0; uint newBound = (Range >> numTotalBits) * size0;
uint symbol; uint symbol;
if (Code < newBound) if (Code < newBound)
{ {
symbol = 0; symbol = 0;
Range = newBound; Range = newBound;
} }
else else
{ {
symbol = 1; symbol = 1;
Code -= newBound; Code -= newBound;
Range -= newBound; Range -= newBound;
} }
Normalize(); Normalize();
return symbol; return symbol;
} }
// ulong GetProcessedSize() {return Stream.GetProcessedSize(); } // ulong GetProcessedSize() {return Stream.GetProcessedSize(); }
} }
} }
+100 -100
View File
@@ -2,116 +2,116 @@ using System;
namespace SevenZip.Compression.RangeCoder namespace SevenZip.Compression.RangeCoder
{ {
struct BitEncoder struct BitEncoder
{ {
public const int kNumBitModelTotalBits = 11; public const int kNumBitModelTotalBits = 11;
public const uint kBitModelTotal = (1 << kNumBitModelTotalBits); public const uint kBitModelTotal = (1 << kNumBitModelTotalBits);
const int kNumMoveBits = 5; const int kNumMoveBits = 5;
const int kNumMoveReducingBits = 2; const int kNumMoveReducingBits = 2;
public const int kNumBitPriceShiftBits = 6; public const int kNumBitPriceShiftBits = 6;
uint Prob; uint Prob;
public void Init() { Prob = kBitModelTotal >> 1; } public void Init() { Prob = kBitModelTotal >> 1; }
public void UpdateModel(uint symbol) public void UpdateModel(uint symbol)
{ {
if (symbol == 0) if (symbol == 0)
Prob += (kBitModelTotal - Prob) >> kNumMoveBits; Prob += (kBitModelTotal - Prob) >> kNumMoveBits;
else else
Prob -= (Prob) >> kNumMoveBits; Prob -= (Prob) >> kNumMoveBits;
} }
public void Encode(Encoder encoder, uint symbol) public void Encode(Encoder encoder, uint symbol)
{ {
// encoder.EncodeBit(Prob, kNumBitModelTotalBits, symbol); // encoder.EncodeBit(Prob, kNumBitModelTotalBits, symbol);
// UpdateModel(symbol); // UpdateModel(symbol);
uint newBound = (encoder.Range >> kNumBitModelTotalBits) * Prob; uint newBound = (encoder.Range >> kNumBitModelTotalBits) * Prob;
if (symbol == 0) if (symbol == 0)
{ {
encoder.Range = newBound; encoder.Range = newBound;
Prob += (kBitModelTotal - Prob) >> kNumMoveBits; Prob += (kBitModelTotal - Prob) >> kNumMoveBits;
} }
else else
{ {
encoder.Low += newBound; encoder.Low += newBound;
encoder.Range -= newBound; encoder.Range -= newBound;
Prob -= (Prob) >> kNumMoveBits; Prob -= (Prob) >> kNumMoveBits;
} }
if (encoder.Range < Encoder.kTopValue) if (encoder.Range < Encoder.kTopValue)
{ {
encoder.Range <<= 8; encoder.Range <<= 8;
encoder.ShiftLow(); encoder.ShiftLow();
} }
} }
private static UInt32[] ProbPrices = new UInt32[kBitModelTotal >> kNumMoveReducingBits]; private static UInt32[] ProbPrices = new UInt32[kBitModelTotal >> kNumMoveReducingBits];
static BitEncoder() static BitEncoder()
{ {
const int kNumBits = (kNumBitModelTotalBits - kNumMoveReducingBits); const int kNumBits = (kNumBitModelTotalBits - kNumMoveReducingBits);
for (int i = kNumBits - 1; i >= 0; i--) for (int i = kNumBits - 1; i >= 0; i--)
{ {
UInt32 start = (UInt32)1 << (kNumBits - i - 1); UInt32 start = (UInt32)1 << (kNumBits - i - 1);
UInt32 end = (UInt32)1 << (kNumBits - i); UInt32 end = (UInt32)1 << (kNumBits - i);
for (UInt32 j = start; j < end; j++) for (UInt32 j = start; j < end; j++)
ProbPrices[j] = ((UInt32)i << kNumBitPriceShiftBits) + ProbPrices[j] = ((UInt32)i << kNumBitPriceShiftBits) +
(((end - j) << kNumBitPriceShiftBits) >> (kNumBits - i - 1)); (((end - j) << kNumBitPriceShiftBits) >> (kNumBits - i - 1));
} }
} }
public uint GetPrice(uint symbol) public uint GetPrice(uint symbol)
{ {
return ProbPrices[(((Prob - symbol) ^ ((-(int)symbol))) & (kBitModelTotal - 1)) >> kNumMoveReducingBits]; return ProbPrices[(((Prob - symbol) ^ ((-(int)symbol))) & (kBitModelTotal - 1)) >> kNumMoveReducingBits];
} }
public uint GetPrice0() { return ProbPrices[Prob >> kNumMoveReducingBits]; } public uint GetPrice0() { return ProbPrices[Prob >> kNumMoveReducingBits]; }
public uint GetPrice1() { return ProbPrices[(kBitModelTotal - Prob) >> kNumMoveReducingBits]; } public uint GetPrice1() { return ProbPrices[(kBitModelTotal - Prob) >> kNumMoveReducingBits]; }
} }
struct BitDecoder struct BitDecoder
{ {
public const int kNumBitModelTotalBits = 11; public const int kNumBitModelTotalBits = 11;
public const uint kBitModelTotal = (1 << kNumBitModelTotalBits); public const uint kBitModelTotal = (1 << kNumBitModelTotalBits);
const int kNumMoveBits = 5; const int kNumMoveBits = 5;
uint Prob; uint Prob;
public void UpdateModel(int numMoveBits, uint symbol) public void UpdateModel(int numMoveBits, uint symbol)
{ {
if (symbol == 0) if (symbol == 0)
Prob += (kBitModelTotal - Prob) >> numMoveBits; Prob += (kBitModelTotal - Prob) >> numMoveBits;
else else
Prob -= (Prob) >> numMoveBits; Prob -= (Prob) >> numMoveBits;
} }
public void Init() { Prob = kBitModelTotal >> 1; } public void Init() { Prob = kBitModelTotal >> 1; }
public uint Decode(RangeCoder.Decoder rangeDecoder) public uint Decode(RangeCoder.Decoder rangeDecoder)
{ {
uint newBound = (uint)(rangeDecoder.Range >> kNumBitModelTotalBits) * (uint)Prob; uint newBound = (uint)(rangeDecoder.Range >> kNumBitModelTotalBits) * (uint)Prob;
if (rangeDecoder.Code < newBound) if (rangeDecoder.Code < newBound)
{ {
rangeDecoder.Range = newBound; rangeDecoder.Range = newBound;
Prob += (kBitModelTotal - Prob) >> kNumMoveBits; Prob += (kBitModelTotal - Prob) >> kNumMoveBits;
if (rangeDecoder.Range < Decoder.kTopValue) if (rangeDecoder.Range < Decoder.kTopValue)
{ {
rangeDecoder.Code = (rangeDecoder.Code << 8) | (byte)rangeDecoder.Stream.ReadByte(); rangeDecoder.Code = (rangeDecoder.Code << 8) | (byte)rangeDecoder.Stream.ReadByte();
rangeDecoder.Range <<= 8; rangeDecoder.Range <<= 8;
} }
return 0; return 0;
} }
else else
{ {
rangeDecoder.Range -= newBound; rangeDecoder.Range -= newBound;
rangeDecoder.Code -= newBound; rangeDecoder.Code -= newBound;
Prob -= (Prob) >> kNumMoveBits; Prob -= (Prob) >> kNumMoveBits;
if (rangeDecoder.Range < Decoder.kTopValue) if (rangeDecoder.Range < Decoder.kTopValue)
{ {
rangeDecoder.Code = (rangeDecoder.Code << 8) | (byte)rangeDecoder.Stream.ReadByte(); rangeDecoder.Code = (rangeDecoder.Code << 8) | (byte)rangeDecoder.Stream.ReadByte();
rangeDecoder.Range <<= 8; rangeDecoder.Range <<= 8;
} }
return 1; return 1;
} }
} }
} }
} }
+138 -138
View File
@@ -2,156 +2,156 @@ using System;
namespace SevenZip.Compression.RangeCoder namespace SevenZip.Compression.RangeCoder
{ {
struct BitTreeEncoder struct BitTreeEncoder
{ {
BitEncoder[] Models; BitEncoder[] Models;
int NumBitLevels; int NumBitLevels;
public BitTreeEncoder(int numBitLevels) public BitTreeEncoder(int numBitLevels)
{ {
NumBitLevels = numBitLevels; NumBitLevels = numBitLevels;
Models = new BitEncoder[1 << numBitLevels]; Models = new BitEncoder[1 << numBitLevels];
} }
public void Init() public void Init()
{ {
for (uint i = 1; i < (1 << NumBitLevels); i++) for (uint i = 1; i < (1 << NumBitLevels); i++)
Models[i].Init(); Models[i].Init();
} }
public void Encode(Encoder rangeEncoder, UInt32 symbol) public void Encode(Encoder rangeEncoder, UInt32 symbol)
{ {
UInt32 m = 1; UInt32 m = 1;
for (int bitIndex = NumBitLevels; bitIndex > 0; ) for (int bitIndex = NumBitLevels; bitIndex > 0;)
{ {
bitIndex--; bitIndex--;
UInt32 bit = (symbol >> bitIndex) & 1; UInt32 bit = (symbol >> bitIndex) & 1;
Models[m].Encode(rangeEncoder, bit); Models[m].Encode(rangeEncoder, bit);
m = (m << 1) | bit; m = (m << 1) | bit;
} }
} }
public void ReverseEncode(Encoder rangeEncoder, UInt32 symbol) public void ReverseEncode(Encoder rangeEncoder, UInt32 symbol)
{ {
UInt32 m = 1; UInt32 m = 1;
for (UInt32 i = 0; i < NumBitLevels; i++) for (UInt32 i = 0; i < NumBitLevels; i++)
{ {
UInt32 bit = symbol & 1; UInt32 bit = symbol & 1;
Models[m].Encode(rangeEncoder, bit); Models[m].Encode(rangeEncoder, bit);
m = (m << 1) | bit; m = (m << 1) | bit;
symbol >>= 1; symbol >>= 1;
} }
} }
public UInt32 GetPrice(UInt32 symbol) public UInt32 GetPrice(UInt32 symbol)
{ {
UInt32 price = 0; UInt32 price = 0;
UInt32 m = 1; UInt32 m = 1;
for (int bitIndex = NumBitLevels; bitIndex > 0; ) for (int bitIndex = NumBitLevels; bitIndex > 0;)
{ {
bitIndex--; bitIndex--;
UInt32 bit = (symbol >> bitIndex) & 1; UInt32 bit = (symbol >> bitIndex) & 1;
price += Models[m].GetPrice(bit); price += Models[m].GetPrice(bit);
m = (m << 1) + bit; m = (m << 1) + bit;
} }
return price; return price;
} }
public UInt32 ReverseGetPrice(UInt32 symbol) public UInt32 ReverseGetPrice(UInt32 symbol)
{ {
UInt32 price = 0; UInt32 price = 0;
UInt32 m = 1; UInt32 m = 1;
for (int i = NumBitLevels; i > 0; i--) for (int i = NumBitLevels; i > 0; i--)
{ {
UInt32 bit = symbol & 1; UInt32 bit = symbol & 1;
symbol >>= 1; symbol >>= 1;
price += Models[m].GetPrice(bit); price += Models[m].GetPrice(bit);
m = (m << 1) | bit; m = (m << 1) | bit;
} }
return price; return price;
} }
public static UInt32 ReverseGetPrice(BitEncoder[] Models, UInt32 startIndex, public static UInt32 ReverseGetPrice(BitEncoder[] Models, UInt32 startIndex,
int NumBitLevels, UInt32 symbol) int NumBitLevels, UInt32 symbol)
{ {
UInt32 price = 0; UInt32 price = 0;
UInt32 m = 1; UInt32 m = 1;
for (int i = NumBitLevels; i > 0; i--) for (int i = NumBitLevels; i > 0; i--)
{ {
UInt32 bit = symbol & 1; UInt32 bit = symbol & 1;
symbol >>= 1; symbol >>= 1;
price += Models[startIndex + m].GetPrice(bit); price += Models[startIndex + m].GetPrice(bit);
m = (m << 1) | bit; m = (m << 1) | bit;
} }
return price; return price;
} }
public static void ReverseEncode(BitEncoder[] Models, UInt32 startIndex, public static void ReverseEncode(BitEncoder[] Models, UInt32 startIndex,
Encoder rangeEncoder, int NumBitLevels, UInt32 symbol) Encoder rangeEncoder, int NumBitLevels, UInt32 symbol)
{ {
UInt32 m = 1; UInt32 m = 1;
for (int i = 0; i < NumBitLevels; i++) for (int i = 0; i < NumBitLevels; i++)
{ {
UInt32 bit = symbol & 1; UInt32 bit = symbol & 1;
Models[startIndex + m].Encode(rangeEncoder, bit); Models[startIndex + m].Encode(rangeEncoder, bit);
m = (m << 1) | bit; m = (m << 1) | bit;
symbol >>= 1; symbol >>= 1;
} }
} }
} }
struct BitTreeDecoder struct BitTreeDecoder
{ {
BitDecoder[] Models; BitDecoder[] Models;
int NumBitLevels; int NumBitLevels;
public BitTreeDecoder(int numBitLevels) public BitTreeDecoder(int numBitLevels)
{ {
NumBitLevels = numBitLevels; NumBitLevels = numBitLevels;
Models = new BitDecoder[1 << numBitLevels]; Models = new BitDecoder[1 << numBitLevels];
} }
public void Init() public void Init()
{ {
for (uint i = 1; i < (1 << NumBitLevels); i++) for (uint i = 1; i < (1 << NumBitLevels); i++)
Models[i].Init(); Models[i].Init();
} }
public uint Decode(RangeCoder.Decoder rangeDecoder) public uint Decode(RangeCoder.Decoder rangeDecoder)
{ {
uint m = 1; uint m = 1;
for (int bitIndex = NumBitLevels; bitIndex > 0; bitIndex--) for (int bitIndex = NumBitLevels; bitIndex > 0; bitIndex--)
m = (m << 1) + Models[m].Decode(rangeDecoder); m = (m << 1) + Models[m].Decode(rangeDecoder);
return m - ((uint)1 << NumBitLevels); return m - ((uint)1 << NumBitLevels);
} }
public uint ReverseDecode(RangeCoder.Decoder rangeDecoder) public uint ReverseDecode(RangeCoder.Decoder rangeDecoder)
{ {
uint m = 1; uint m = 1;
uint symbol = 0; uint symbol = 0;
for (int bitIndex = 0; bitIndex < NumBitLevels; bitIndex++) for (int bitIndex = 0; bitIndex < NumBitLevels; bitIndex++)
{ {
uint bit = Models[m].Decode(rangeDecoder); uint bit = Models[m].Decode(rangeDecoder);
m <<= 1; m <<= 1;
m += bit; m += bit;
symbol |= (bit << bitIndex); symbol |= (bit << bitIndex);
} }
return symbol; return symbol;
} }
public static uint ReverseDecode(BitDecoder[] Models, UInt32 startIndex, public static uint ReverseDecode(BitDecoder[] Models, UInt32 startIndex,
RangeCoder.Decoder rangeDecoder, int NumBitLevels) RangeCoder.Decoder rangeDecoder, int NumBitLevels)
{ {
uint m = 1; uint m = 1;
uint symbol = 0; uint symbol = 0;
for (int bitIndex = 0; bitIndex < NumBitLevels; bitIndex++) for (int bitIndex = 0; bitIndex < NumBitLevels; bitIndex++)
{ {
uint bit = Models[startIndex + m].Decode(rangeDecoder); uint bit = Models[startIndex + m].Decode(rangeDecoder);
m <<= 1; m <<= 1;
m += bit; m += bit;
symbol |= (bit << bitIndex); symbol |= (bit << bitIndex);
} }
return symbol; return symbol;
} }
} }
} }
+132 -132
View File
@@ -4,64 +4,64 @@ using System;
namespace SevenZip namespace SevenZip
{ {
/// <summary> /// <summary>
/// The exception that is thrown when an error in input stream occurs during decoding. /// The exception that is thrown when an error in input stream occurs during decoding.
/// </summary> /// </summary>
class DataErrorException : ApplicationException class DataErrorException : ApplicationException
{ {
public DataErrorException(): base("Data Error") { } public DataErrorException() : base("Data Error") { }
} }
/// <summary> /// <summary>
/// The exception that is thrown when the value of an argument is outside the allowable range. /// The exception that is thrown when the value of an argument is outside the allowable range.
/// </summary> /// </summary>
class InvalidParamException : ApplicationException class InvalidParamException : ApplicationException
{ {
public InvalidParamException(): base("Invalid Parameter") { } public InvalidParamException() : base("Invalid Parameter") { }
} }
public interface ICodeProgress public interface ICodeProgress
{ {
/// <summary> /// <summary>
/// Callback progress. /// Callback progress.
/// </summary> /// </summary>
/// <param name="inSize"> /// <param name="inSize">
/// input size. -1 if unknown. /// input size. -1 if unknown.
/// </param> /// </param>
/// <param name="outSize"> /// <param name="outSize">
/// output size. -1 if unknown. /// output size. -1 if unknown.
/// </param> /// </param>
void SetProgress(Int64 inSize, Int64 outSize); void SetProgress(Int64 inSize, Int64 outSize);
}; };
public interface ICoder public interface ICoder
{ {
/// <summary> /// <summary>
/// Codes streams. /// Codes streams.
/// </summary> /// </summary>
/// <param name="inStream"> /// <param name="inStream">
/// input Stream. /// input Stream.
/// </param> /// </param>
/// <param name="outStream"> /// <param name="outStream">
/// output Stream. /// output Stream.
/// </param> /// </param>
/// <param name="inSize"> /// <param name="inSize">
/// input Size. -1 if unknown. /// input Size. -1 if unknown.
/// </param> /// </param>
/// <param name="outSize"> /// <param name="outSize">
/// output Size. -1 if unknown. /// output Size. -1 if unknown.
/// </param> /// </param>
/// <param name="progress"> /// <param name="progress">
/// callback progress reference. /// callback progress reference.
/// </param> /// </param>
/// <exception cref="SevenZip.DataErrorException"> /// <exception cref="SevenZip.DataErrorException">
/// if input stream is not valid /// if input stream is not valid
/// </exception> /// </exception>
void Code(System.IO.Stream inStream, System.IO.Stream outStream, void Code(System.IO.Stream inStream, System.IO.Stream outStream,
Int64 inSize, Int64 outSize, ICodeProgress progress); Int64 inSize, Int64 outSize, ICodeProgress progress);
}; };
/* /*
public interface ICoder2 public interface ICoder2
{ {
void Code(ISequentialInStream []inStreams, void Code(ISequentialInStream []inStreams,
@@ -72,86 +72,86 @@ namespace SevenZip
}; };
*/ */
/// <summary> /// <summary>
/// Provides the fields that represent properties idenitifiers for compressing. /// Provides the fields that represent properties idenitifiers for compressing.
/// </summary> /// </summary>
public enum CoderPropID public enum CoderPropID
{ {
/// <summary> /// <summary>
/// Specifies default property. /// Specifies default property.
/// </summary> /// </summary>
DefaultProp = 0, DefaultProp = 0,
/// <summary> /// <summary>
/// Specifies size of dictionary. /// Specifies size of dictionary.
/// </summary> /// </summary>
DictionarySize, DictionarySize,
/// <summary> /// <summary>
/// Specifies size of memory for PPM*. /// Specifies size of memory for PPM*.
/// </summary> /// </summary>
UsedMemorySize, UsedMemorySize,
/// <summary> /// <summary>
/// Specifies order for PPM methods. /// Specifies order for PPM methods.
/// </summary> /// </summary>
Order, Order,
/// <summary> /// <summary>
/// Specifies Block Size. /// Specifies Block Size.
/// </summary> /// </summary>
BlockSize, BlockSize,
/// <summary> /// <summary>
/// Specifies number of postion state bits for LZMA (0 <= x <= 4). /// Specifies number of postion state bits for LZMA (0 <= x <= 4).
/// </summary> /// </summary>
PosStateBits, PosStateBits,
/// <summary> /// <summary>
/// Specifies number of literal context bits for LZMA (0 <= x <= 8). /// Specifies number of literal context bits for LZMA (0 <= x <= 8).
/// </summary> /// </summary>
LitContextBits, LitContextBits,
/// <summary> /// <summary>
/// Specifies number of literal position bits for LZMA (0 <= x <= 4). /// Specifies number of literal position bits for LZMA (0 <= x <= 4).
/// </summary> /// </summary>
LitPosBits, LitPosBits,
/// <summary> /// <summary>
/// Specifies number of fast bytes for LZ*. /// Specifies number of fast bytes for LZ*.
/// </summary> /// </summary>
NumFastBytes, NumFastBytes,
/// <summary> /// <summary>
/// Specifies match finder. LZMA: "BT2", "BT4" or "BT4B". /// Specifies match finder. LZMA: "BT2", "BT4" or "BT4B".
/// </summary> /// </summary>
MatchFinder, MatchFinder,
/// <summary> /// <summary>
/// Specifies the number of match finder cyckes. /// Specifies the number of match finder cyckes.
/// </summary> /// </summary>
MatchFinderCycles, MatchFinderCycles,
/// <summary> /// <summary>
/// Specifies number of passes. /// Specifies number of passes.
/// </summary> /// </summary>
NumPasses, NumPasses,
/// <summary> /// <summary>
/// Specifies number of algorithm. /// Specifies number of algorithm.
/// </summary> /// </summary>
Algorithm, Algorithm,
/// <summary> /// <summary>
/// Specifies the number of threads. /// Specifies the number of threads.
/// </summary> /// </summary>
NumThreads, NumThreads,
/// <summary> /// <summary>
/// Specifies mode with end marker. /// Specifies mode with end marker.
/// </summary> /// </summary>
EndMarker EndMarker
}; };
public interface ISetCoderProperties public interface ISetCoderProperties
{ {
void SetCoderProperties(CoderPropID[] propIDs, object[] properties); void SetCoderProperties(CoderPropID[] propIDs, object[] properties);
}; };
public interface IWriteCoderProperties public interface IWriteCoderProperties
{ {
void WriteCoderProperties(System.IO.Stream outStream); void WriteCoderProperties(System.IO.Stream outStream);
} }
public interface ISetDecoderProperties public interface ISetDecoderProperties
{ {
void SetDecoderProperties(byte[] properties); void SetDecoderProperties(byte[] properties);
} }
} }
+2 -2
View File
@@ -19,10 +19,10 @@
// DEALINGS IN THE SOFTWARE. // DEALINGS IN THE SOFTWARE.
using System; using System;
using System.Linq;
using System.Windows;
using System.IO; using System.IO;
using System.Linq;
using System.Threading; using System.Threading;
using System.Windows;
namespace WPinternals namespace WPinternals
{ {
+1 -1
View File
@@ -27,7 +27,7 @@ namespace DiscUtils
public Block() public Block()
{ {
} }
public long Position { get; set; } public long Position { get; set; }
public byte[] Data { get; set; } public byte[] Data { get; set; }
-2
View File
@@ -22,9 +22,7 @@
namespace DiscUtils namespace DiscUtils
{ {
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text;
internal class BlockCache<T> internal class BlockCache<T>
where T : Block, new() where T : Block, new()
@@ -22,10 +22,10 @@
namespace DiscUtils.BootConfig namespace DiscUtils.BootConfig
{ {
using DiscUtils.Registry;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Globalization; using System.Globalization;
using DiscUtils.Registry;
internal class DiscUtilsRegistryStorage : BaseStorage internal class DiscUtilsRegistryStorage : BaseStorage
{ {
-1
View File
@@ -23,7 +23,6 @@
namespace DiscUtils.BootConfig namespace DiscUtils.BootConfig
{ {
using System; using System;
using System.Globalization;
/// <summary> /// <summary>
/// The value of an element. /// The value of an element.
-4
View File
@@ -22,10 +22,6 @@
namespace DiscUtils.BootConfig namespace DiscUtils.BootConfig
{ {
using System;
using System.Collections.Generic;
using System.Text;
/// <summary> /// <summary>
/// Indicates the type of objects that can inherit from an object. /// Indicates the type of objects that can inherit from an object.
/// </summary> /// </summary>
+1 -1
View File
@@ -22,9 +22,9 @@
namespace DiscUtils.BootConfig namespace DiscUtils.BootConfig
{ {
using DiscUtils.Registry;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using DiscUtils.Registry;
/// <summary> /// <summary>
/// Represents a Boot Configuration Database store (i.e. a BCD file). /// Represents a Boot Configuration Database store (i.e. a BCD file).
-2
View File
@@ -22,9 +22,7 @@
namespace DiscUtils namespace DiscUtils
{ {
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text;
internal class BuilderSparseStreamExtent : BuilderExtent internal class BuilderSparseStreamExtent : BuilderExtent
{ {
+3 -4
View File
@@ -24,7 +24,6 @@ namespace DiscUtils
{ {
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text;
/// <summary> /// <summary>
/// Enumeration of possible cluster roles. /// Enumeration of possible cluster roles.
@@ -36,12 +35,12 @@ namespace DiscUtils
/// <summary> /// <summary>
/// Unknown, or unspecified role. /// Unknown, or unspecified role.
/// </summary> /// </summary>
None = 0x00, None = 0x00,
/// <summary> /// <summary>
/// Cluster is free. /// Cluster is free.
/// </summary> /// </summary>
Free = 0x01, Free = 0x01,
/// <summary> /// <summary>
/// Cluster is in use by a normal file. /// Cluster is in use by a normal file.
@@ -69,7 +68,7 @@ namespace DiscUtils
/// <summary> /// <summary>
/// Cluster is marked bad. /// Cluster is marked bad.
/// </summary> /// </summary>
Bad = 0x20, Bad = 0x20,
} }
/// <summary> /// <summary>
-1
View File
@@ -24,7 +24,6 @@ namespace DiscUtils.Fat
{ {
using System; using System;
using System.IO; using System.IO;
using System.Text;
internal class DirectoryEntry internal class DirectoryEntry
{ {
-1
View File
@@ -22,7 +22,6 @@
namespace DiscUtils.Fat namespace DiscUtils.Fat
{ {
using System;
using System.IO; using System.IO;
internal class FileAllocationTable internal class FileAllocationTable
+1 -1
View File
@@ -22,8 +22,8 @@
namespace DiscUtils.Fat namespace DiscUtils.Fat
{ {
using System.IO;
using DiscUtils.Vfs; using DiscUtils.Vfs;
using System.IO;
[VfsFileSystemFactory] [VfsFileSystemFactory]
internal class FileSystemFactory : VfsFileSystemFactory internal class FileSystemFactory : VfsFileSystemFactory
+1 -1
View File
@@ -22,9 +22,9 @@
namespace DiscUtils.LogicalDiskManager namespace DiscUtils.LogicalDiskManager
{ {
using DiscUtils.Partitions;
using System; using System;
using System.IO; using System.IO;
using DiscUtils.Partitions;
internal class DynamicDisk : IDiagnosticTraceable internal class DynamicDisk : IDiagnosticTraceable
{ {
@@ -22,11 +22,11 @@
namespace DiscUtils.LogicalDiskManager namespace DiscUtils.LogicalDiskManager
{ {
using DiscUtils.Partitions;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Globalization; using System.Globalization;
using System.IO; using System.IO;
using DiscUtils.Partitions;
internal class DynamicDiskGroup : IDiagnosticTraceable internal class DynamicDiskGroup : IDiagnosticTraceable
{ {
@@ -22,9 +22,9 @@
namespace DiscUtils.LogicalDiskManager namespace DiscUtils.LogicalDiskManager
{ {
using DiscUtils.Partitions;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using DiscUtils.Partitions;
/// <summary> /// <summary>
/// A class that understands Windows LDM structures, mapping physical volumes to logical volumes. /// A class that understands Windows LDM structures, mapping physical volumes to logical volumes.
-2
View File
@@ -22,8 +22,6 @@
namespace DiscUtils.LogicalDiskManager namespace DiscUtils.LogicalDiskManager
{ {
using System;
internal class TocBlock internal class TocBlock
{ {
public string Signature; // TOCBLOCK public string Signature; // TOCBLOCK
-1
View File
@@ -22,7 +22,6 @@
namespace DiscUtils namespace DiscUtils
{ {
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
+13 -13
View File
@@ -27,25 +27,25 @@ namespace DiscUtils.Ntfs
internal enum AttributeCollationRule : int internal enum AttributeCollationRule : int
{ {
Binary = 0x00000000, Binary = 0x00000000,
Filename = 0x00000001, Filename = 0x00000001,
UnicodeString = 0x00000002, UnicodeString = 0x00000002,
UnsignedLong = 0x00000010, UnsignedLong = 0x00000010,
Sid = 0x00000011, Sid = 0x00000011,
SecurityHash = 0x00000012, SecurityHash = 0x00000012,
MultipleUnsignedLongs = 0x00000013 MultipleUnsignedLongs = 0x00000013
} }
[Flags] [Flags]
internal enum AttributeTypeFlags : int internal enum AttributeTypeFlags : int
{ {
None = 0x00, None = 0x00,
Indexed = 0x02, Indexed = 0x02,
Multiple = 0x04, Multiple = 0x04,
NotZero = 0x08, NotZero = 0x08,
IndexedUnique = 0x10, IndexedUnique = 0x10,
NamedUnique = 0x20, NamedUnique = 0x20,
MustBeResident = 0x40, MustBeResident = 0x40,
CanBeNonResident = 0x80 CanBeNonResident = 0x80
} }
+1 -1
View File
@@ -22,10 +22,10 @@
namespace DiscUtils.Ntfs namespace DiscUtils.Ntfs
{ {
using DiscUtils.Compression;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using DiscUtils.Compression;
internal sealed class CompressedClusterStream : ClusterStream internal sealed class CompressedClusterStream : ClusterStream
{ {
-1
View File
@@ -23,7 +23,6 @@
namespace DiscUtils.Ntfs namespace DiscUtils.Ntfs
{ {
using System; using System;
using System.Collections.Generic;
internal class CookedDataRun internal class CookedDataRun
{ {
-1
View File
@@ -23,7 +23,6 @@
namespace DiscUtils.Ntfs namespace DiscUtils.Ntfs
{ {
using System.Globalization; using System.Globalization;
using System.IO;
internal class DataRun internal class DataRun
{ {
+1 -1
View File
@@ -809,7 +809,7 @@ namespace DiscUtils.Ntfs
return SplitAttribute(record, (NonResidentAttributeRecord)record.FirstAttribute, false); return SplitAttribute(record, (NonResidentAttributeRecord)record.FirstAttribute, false);
} }
private bool SplitAttribute(FileRecord record, NonResidentAttributeRecord targetAttr, bool atStart) private bool SplitAttribute(FileRecord record, NonResidentAttributeRecord targetAttr, bool atStart)
{ {
if (targetAttr.DataRuns.Count <= 1) if (targetAttr.DataRuns.Count <= 1)
-1
View File
@@ -24,7 +24,6 @@ namespace DiscUtils.Ntfs
{ {
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO; using System.IO;
[Flags] [Flags]
+1 -1
View File
@@ -22,8 +22,8 @@
namespace DiscUtils.Ntfs namespace DiscUtils.Ntfs
{ {
using System.IO;
using DiscUtils.Vfs; using DiscUtils.Vfs;
using System.IO;
[VfsFileSystemFactory] [VfsFileSystemFactory]
internal class FileSystemFactory : VfsFileSystemFactory internal class FileSystemFactory : VfsFileSystemFactory
-1
View File
@@ -22,7 +22,6 @@
namespace DiscUtils.Ntfs namespace DiscUtils.Ntfs
{ {
using System;
using System.IO; using System.IO;
internal abstract class FixupRecordBase internal abstract class FixupRecordBase
+1 -1
View File
@@ -474,7 +474,7 @@ namespace DiscUtils.Ntfs
{ {
writer.WriteLine(prefix + " " + EntryAsString(entry, _file.BestName, _name)); writer.WriteLine(prefix + " " + EntryAsString(entry, _file.BestName, _name));
} }
if ((entry.Flags & IndexEntryFlags.Node) != 0) if ((entry.Flags & IndexEntryFlags.Node) != 0)
{ {
NodeAsString(writer, prefix + " ", GetSubBlock(entry).Node, ":i" + entry.ChildrenVirtualCluster); NodeAsString(writer, prefix + " ", GetSubBlock(entry).Node, ":i" + entry.ChildrenVirtualCluster);
-1
View File
@@ -23,7 +23,6 @@
namespace DiscUtils.Ntfs namespace DiscUtils.Ntfs
{ {
using System; using System;
using System.Collections.Generic;
using System.IO; using System.IO;
internal class IndexBlock : FixupRecordBase internal class IndexBlock : FixupRecordBase
+1 -1
View File
@@ -404,7 +404,7 @@ namespace DiscUtils.Ntfs
} }
return null; return null;
} }
private IndexEntry PopulateEnd() private IndexEntry PopulateEnd()
{ {
@@ -1,9 +1,5 @@
namespace DiscUtils.Ntfs.Internals namespace DiscUtils.Ntfs.Internals
{ {
using System;
using System.Collections.Generic;
using System.Text;
public sealed class MasterFileTableAttribute public sealed class MasterFileTableAttribute
{ {
} }
@@ -22,10 +22,6 @@
namespace DiscUtils.Ntfs.Internals namespace DiscUtils.Ntfs.Internals
{ {
using System.Collections;
using System.Collections.Generic;
using System.IO;
public sealed class MasterFileTableRecord public sealed class MasterFileTableRecord
{ {
private FileRecord _fileRecord; private FileRecord _fileRecord;
@@ -22,8 +22,6 @@
namespace DiscUtils.Ntfs.Internals namespace DiscUtils.Ntfs.Internals
{ {
using System;
/// <summary> /// <summary>
/// The known NTFS namespaces. /// The known NTFS namespaces.
/// </summary> /// </summary>
+1 -1
View File
@@ -30,8 +30,8 @@
namespace DiscUtils.Ntfs namespace DiscUtils.Ntfs
{ {
using System;
using DiscUtils.Compression; using DiscUtils.Compression;
using System;
/// <summary> /// <summary>
/// Implementation of the LZNT1 algorithm used for compressing NTFS files. /// Implementation of the LZNT1 algorithm used for compressing NTFS files.
-1
View File
@@ -25,7 +25,6 @@ namespace DiscUtils.Ntfs
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using DiscUtils.Compression;
internal class NonResidentDataBuffer : DiscUtils.Buffer, IMappedBuffer internal class NonResidentDataBuffer : DiscUtils.Buffer, IMappedBuffer
{ {
-1
View File
@@ -22,7 +22,6 @@
namespace DiscUtils.Ntfs namespace DiscUtils.Ntfs
{ {
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Globalization; using System.Globalization;
using System.IO; using System.IO;
+6 -6
View File
@@ -1097,7 +1097,7 @@ namespace DiscUtils.Ntfs
} }
} }
UpdateStandardInformation(dirEntry, file, delegate(StandardInformation si) { si.FileAttributes = FileNameRecord.SetAttributes(newValue, si.FileAttributes); }); UpdateStandardInformation(dirEntry, file, delegate (StandardInformation si) { si.FileAttributes = FileNameRecord.SetAttributes(newValue, si.FileAttributes); });
} }
} }
@@ -1131,7 +1131,7 @@ namespace DiscUtils.Ntfs
{ {
using (new NtfsTransaction()) using (new NtfsTransaction())
{ {
UpdateStandardInformation(path, delegate(StandardInformation si) { si.CreationTime = newTime; }); UpdateStandardInformation(path, delegate (StandardInformation si) { si.CreationTime = newTime; });
} }
} }
@@ -1165,7 +1165,7 @@ namespace DiscUtils.Ntfs
{ {
using (new NtfsTransaction()) using (new NtfsTransaction())
{ {
UpdateStandardInformation(path, delegate(StandardInformation si) { si.LastAccessTime = newTime; }); UpdateStandardInformation(path, delegate (StandardInformation si) { si.LastAccessTime = newTime; });
} }
} }
@@ -1199,7 +1199,7 @@ namespace DiscUtils.Ntfs
{ {
using (new NtfsTransaction()) using (new NtfsTransaction())
{ {
UpdateStandardInformation(path, delegate(StandardInformation si) { si.ModificationTime = newTime; }); UpdateStandardInformation(path, delegate (StandardInformation si) { si.ModificationTime = newTime; });
} }
} }
@@ -1763,7 +1763,7 @@ namespace DiscUtils.Ntfs
{ {
UpdateStandardInformation( UpdateStandardInformation(
path, path,
delegate(StandardInformation si) delegate (StandardInformation si)
{ {
si.CreationTime = info.CreationTime; si.CreationTime = info.CreationTime;
si.LastAccessTime = info.LastAccessTime; si.LastAccessTime = info.LastAccessTime;
@@ -1813,7 +1813,7 @@ namespace DiscUtils.Ntfs
DirectoryEntry dirEntry = GetDirectoryEntry(path); DirectoryEntry dirEntry = GetDirectoryEntry(path);
if (dirEntry == null) if (dirEntry == null)
{ {
throw new FileNotFoundException("File not found", path); throw new FileNotFoundException("File not found", path);
} }
File file = GetFile(dirEntry.Reference); File file = GetFile(dirEntry.Reference);
+2 -2
View File
@@ -137,8 +137,8 @@ namespace DiscUtils.Ntfs
SetSecurityAttribute(volumeFile, "O:" + localAdminString + "G:BAD:(A;;0x12019f;;;SY)(A;;0x12019f;;;BA)"); SetSecurityAttribute(volumeFile, "O:" + localAdminString + "G:BAD:(A;;0x12019f;;;SY)(A;;0x12019f;;;BA)");
volumeFile.UpdateRecordInMft(); volumeFile.UpdateRecordInMft();
_context.GetFileByIndex = delegate(long index) { return new File(_context, _context.Mft.GetRecord(index, false)); }; _context.GetFileByIndex = delegate (long index) { return new File(_context, _context.Mft.GetRecord(index, false)); };
_context.AllocateFile = delegate(FileRecordFlags frf) { return new File(_context, _context.Mft.AllocateRecord(frf, false)); }; _context.AllocateFile = delegate (FileRecordFlags frf) { return new File(_context, _context.Mft.AllocateRecord(frf, false)); };
File attrDefFile = CreateSystemFile(MasterFileTable.AttrDefIndex); File attrDefFile = CreateSystemFile(MasterFileTable.AttrDefIndex);
_context.AttributeDefinitions.WriteTo(attrDefFile); _context.AttributeDefinitions.WriteTo(attrDefFile);
+1 -2
View File
@@ -22,7 +22,6 @@
namespace DiscUtils.Ntfs namespace DiscUtils.Ntfs
{ {
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
@@ -70,7 +69,7 @@ namespace DiscUtils.Ntfs
value.ReadFrom(buffer, 0); value.ReadFrom(buffer, 0);
return value; return value;
} }
/// <summary> /// <summary>
/// Sets the content of a stream. /// Sets the content of a stream.
/// </summary> /// </summary>
-2
View File
@@ -23,8 +23,6 @@
namespace DiscUtils.Ntfs namespace DiscUtils.Ntfs
{ {
using System; using System;
using System.Collections.Generic;
using System.Text;
internal sealed class NtfsTransaction : IDisposable internal sealed class NtfsTransaction : IDisposable
{ {
+1 -1
View File
@@ -22,11 +22,11 @@
namespace DiscUtils.Ntfs namespace DiscUtils.Ntfs
{ {
using DiscUtils;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Globalization; using System.Globalization;
using System.IO; using System.IO;
using DiscUtils;
/// <summary> /// <summary>
/// Low-level non-resident attribute operations. /// Low-level non-resident attribute operations.
-2
View File
@@ -22,10 +22,8 @@
namespace DiscUtils.Ntfs namespace DiscUtils.Ntfs
{ {
using System;
using System.IO; using System.IO;
using System.Security.AccessControl; using System.Security.AccessControl;
using System.Security.Principal;
internal sealed class SecurityDescriptor : IByteArraySerializable, IDiagnosticTraceable internal sealed class SecurityDescriptor : IByteArraySerializable, IDiagnosticTraceable
{ {
-4
View File
@@ -22,10 +22,6 @@
namespace DiscUtils.Ntfs namespace DiscUtils.Ntfs
{ {
using System;
using System.Collections.Generic;
using System.Text;
/// <summary> /// <summary>
/// Controls whether short file names are created automatically. /// Controls whether short file names are created automatically.
/// </summary> /// </summary>
+3 -3
View File
@@ -93,9 +93,9 @@ namespace DiscUtils.Ntfs
{ {
using (Stream s = Open(FileAccess.Read)) using (Stream s = Open(FileAccess.Read))
{ {
byte[] buffer = Utilities.ReadFully(s, (int)Length); byte[] buffer = Utilities.ReadFully(s, (int)Length);
_structure.ReadFrom(buffer, 0); _structure.ReadFrom(buffer, 0);
_hasContent = s.Length != 0; _hasContent = s.Length != 0;
} }
_initialized = true; _initialized = true;
-1
View File
@@ -22,7 +22,6 @@
namespace DiscUtils.Ntfs namespace DiscUtils.Ntfs
{ {
using System;
using System.IO; using System.IO;
internal sealed class VolumeInformation : IByteArraySerializable, IDiagnosticTraceable internal sealed class VolumeInformation : IByteArraySerializable, IDiagnosticTraceable
-1
View File
@@ -22,7 +22,6 @@
namespace DiscUtils.Ntfs namespace DiscUtils.Ntfs
{ {
using System;
using System.IO; using System.IO;
using System.Text; using System.Text;
-1
View File
@@ -23,7 +23,6 @@
namespace DiscUtils namespace DiscUtils
{ {
using System; using System;
using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
/// <summary> /// <summary>
-4
View File
@@ -22,10 +22,6 @@
namespace DiscUtils namespace DiscUtils
{ {
using System;
using System.Collections.Generic;
using System.Text;
/// <summary> /// <summary>
/// Enumeration used to indicate transfer of disposable objects. /// Enumeration used to indicate transfer of disposable objects.
/// </summary> /// </summary>
@@ -23,7 +23,6 @@
namespace DiscUtils.Partitions namespace DiscUtils.Partitions
{ {
using System; using System;
using System.IO;
/// <summary> /// <summary>
/// Provides access to partition records in a BIOS (MBR) partition table. /// Provides access to partition records in a BIOS (MBR) partition table.
@@ -24,7 +24,6 @@ namespace DiscUtils.Partitions
{ {
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO;
/// <summary> /// <summary>
/// Builds a stream with the contents of a BIOS partitioned disk. /// Builds a stream with the contents of a BIOS partitioned disk.
@@ -23,7 +23,6 @@
namespace DiscUtils.Partitions namespace DiscUtils.Partitions
{ {
using System; using System;
using System.IO;
/// <summary> /// <summary>
/// Provides access to partition records in a GUID partition table. /// Provides access to partition records in a GUID partition table.
-1
View File
@@ -24,7 +24,6 @@ namespace DiscUtils.Partitions
{ {
using System; using System;
using System.Globalization; using System.Globalization;
using System.IO;
/// <summary> /// <summary>
/// Base class representing a disk partition. /// Base class representing a disk partition.
+1 -1
View File
@@ -22,9 +22,9 @@
namespace DiscUtils namespace DiscUtils
{ {
using DiscUtils.Partitions;
using System; using System;
using System.Globalization; using System.Globalization;
using DiscUtils.Partitions;
/// <summary> /// <summary>
/// Enumeration of possible types of physical volume. /// Enumeration of possible types of physical volume.
-1
View File
@@ -24,7 +24,6 @@ namespace DiscUtils
{ {
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text;
/// <summary> /// <summary>
/// Represents a range of values. /// Represents a range of values.
-1
View File
@@ -23,7 +23,6 @@
namespace DiscUtils.Raw namespace DiscUtils.Raw
{ {
using System; using System;
using System.Collections.Generic;
using System.IO; using System.IO;
[VirtualDiskFactory("RAW", ".img,.ima,.vfd,.flp,.bif")] [VirtualDiskFactory("RAW", ".img,.ima,.vfd,.flp,.bif")]
+1 -1
View File
@@ -22,9 +22,9 @@
namespace DiscUtils.Raw namespace DiscUtils.Raw
{ {
using DiscUtils.Partitions;
using System; using System;
using System.IO; using System.IO;
using DiscUtils.Partitions;
/// <summary> /// <summary>
/// Represents a single raw disk image file. /// Represents a single raw disk image file.
-1
View File
@@ -22,7 +22,6 @@
namespace DiscUtils.Registry namespace DiscUtils.Registry
{ {
using System;
using System.IO; using System.IO;
internal sealed class BinHeader : IByteArraySerializable internal sealed class BinHeader : IByteArraySerializable
-1
View File
@@ -22,7 +22,6 @@
namespace DiscUtils namespace DiscUtils
{ {
using System.Collections.Generic;
using System.IO; using System.IO;
/// <summary> /// <summary>
-2
View File
@@ -22,8 +22,6 @@
namespace DiscUtils namespace DiscUtils
{ {
using System;
internal abstract class Tuple internal abstract class Tuple
{ {
public abstract object this[int i] public abstract object this[int i]
-2
View File
@@ -22,8 +22,6 @@
namespace DiscUtils namespace DiscUtils
{ {
using System;
/// <summary> /// <summary>
/// Standard Unix-style file type. /// Standard Unix-style file type.
/// </summary> /// </summary>
+1 -1
View File
@@ -29,7 +29,7 @@ namespace DiscUtils
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
internal delegate TResult Func<T, TResult>(T arg); internal delegate TResult Func<T, TResult>(T arg);
internal static class Utilities internal static class Utilities
{ {
/// <summary> /// <summary>
@@ -23,8 +23,6 @@
namespace DiscUtils.Vfs namespace DiscUtils.Vfs
{ {
using System; using System;
using System.Collections.Generic;
using System.Text;
/// <summary> /// <summary>
/// Attribute identifying file system factory classes. /// Attribute identifying file system factory classes.
+1 -1
View File
@@ -22,11 +22,11 @@
namespace DiscUtils namespace DiscUtils
{ {
using DiscUtils.Partitions;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Globalization; using System.Globalization;
using System.IO; using System.IO;
using DiscUtils.Partitions;
/// <summary> /// <summary>
/// Base class representing virtual hard disks. /// Base class representing virtual hard disks.
+1 -1
View File
@@ -22,11 +22,11 @@
namespace DiscUtils namespace DiscUtils
{ {
using DiscUtils.Partitions;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Globalization; using System.Globalization;
using System.IO; using System.IO;
using DiscUtils.Partitions;
/// <summary> /// <summary>
/// VolumeManager interprets partitions and other on-disk structures (possibly combining multiple disks). /// VolumeManager interprets partitions and other on-disk structures (possibly combining multiple disks).
+2 -2
View File
@@ -27,7 +27,7 @@ using System.Windows.Media;
namespace WPinternals namespace WPinternals
{ {
public class PathChangedEventArgs: EventArgs public class PathChangedEventArgs : EventArgs
{ {
public PathChangedEventArgs(string NewPath) public PathChangedEventArgs(string NewPath)
: base() : base()
@@ -110,7 +110,7 @@ namespace WPinternals
{ {
return (string)GetValue(PathProperty); return (string)GetValue(PathProperty);
} }
set set
{ {
if ((string)GetValue(PathProperty) != value) if ((string)GetValue(PathProperty) != value)
{ {
+38 -39
View File
@@ -22,25 +22,24 @@
// Where possible the original authors are referenced. // Where possible the original authors are referenced.
using System; using System;
using System.IO; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Globalization; using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq; using System.Linq;
using System.Reflection;
using System.Text; using System.Text;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows; using System.Windows;
using System.Windows.Controls; using System.Windows.Controls;
using System.Windows.Data; using System.Windows.Data;
using System.Windows.Documents; using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media.Animation; using System.Windows.Media.Animation;
using System.Windows.Media.Imaging; using System.Windows.Media.Imaging;
using System.Threading;
using System.Windows.Input;
using System.Windows.Threading; using System.Windows.Threading;
using System.IO.Compression;
using System.Collections;
using System.Reflection;
using System.Net;
namespace WPinternals namespace WPinternals
{ {
@@ -226,11 +225,11 @@ namespace WPinternals
public Boolean IsVisible public Boolean IsVisible
{ {
get get
{ {
return (Boolean)this.GetValue(IsVisibleProperty); return (Boolean)this.GetValue(IsVisibleProperty);
} }
set set
{ {
this.SetValue(IsVisibleProperty, value); this.SetValue(IsVisibleProperty, value);
} }
@@ -1061,7 +1060,7 @@ namespace WPinternals
{ {
} }
public DelegateCommand(Action executeMethod, Func<bool> canExecuteMethod): base(o => executeMethod(), f => canExecuteMethod()) public DelegateCommand(Action executeMethod, Func<bool> canExecuteMethod) : base(o => executeMethod(), f => canExecuteMethod())
{ {
} }
@@ -1076,7 +1075,7 @@ namespace WPinternals
} }
} }
internal class FlowDocumentScrollViewerNoMouseWheel: FlowDocumentScrollViewer internal class FlowDocumentScrollViewerNoMouseWheel : FlowDocumentScrollViewer
{ {
protected override void OnMouseWheel(MouseWheelEventArgs e) protected override void OnMouseWheel(MouseWheelEventArgs e)
{ {
@@ -1167,7 +1166,7 @@ namespace WPinternals
} }
} }
internal class WPinternalsException: Exception internal class WPinternalsException : Exception
{ {
// Message and SubMessaage are always printable // Message and SubMessaage are always printable
internal string SubMessage = null; internal string SubMessage = null;
@@ -1423,7 +1422,7 @@ namespace WPinternals
internal DecompressedStream(Stream InputStream) internal DecompressedStream(Stream InputStream)
{ {
UnderlyingStream = new ReadSeekableStream(InputStream, 0x100); UnderlyingStream = new ReadSeekableStream(InputStream, 0x100);
byte[] Signature = new byte["CompressedPartition".Length + 2]; byte[] Signature = new byte["CompressedPartition".Length + 2];
Signature[0x00] = 0xFF; Signature[0x00] = 0xFF;
Buffer.BlockCopy(Encoding.ASCII.GetBytes("CompressedPartition"), 0, Signature, 0x01, "CompressedPartition".Length); Buffer.BlockCopy(Encoding.ASCII.GetBytes("CompressedPartition"), 0, Signature, 0x01, "CompressedPartition".Length);
@@ -1469,7 +1468,7 @@ namespace WPinternals
public override bool CanRead { get { return true; } } public override bool CanRead { get { return true; } }
public override bool CanSeek { get { return false; } } public override bool CanSeek { get { return false; } }
public override int Read(byte[] buffer, int offset, int count) public override int Read(byte[] buffer, int offset, int count)
{ {
int RealCount = UnderlyingStream.Read(buffer, offset, count); int RealCount = UnderlyingStream.Read(buffer, offset, count);
ReadPosition += RealCount; ReadPosition += RealCount;
@@ -1483,18 +1482,18 @@ namespace WPinternals
} }
public override bool CanTimeout { get { return UnderlyingStream.CanTimeout; } } public override bool CanTimeout { get { return UnderlyingStream.CanTimeout; } }
public override bool CanWrite { get { return true; } } public override bool CanWrite { get { return true; } }
public override long Length public override long Length
{ {
get get
{ {
if (IsSourceCompressed) if (IsSourceCompressed)
return (long)DecompressedLength; return (long)DecompressedLength;
else else
return UnderlyingStream.Length; return UnderlyingStream.Length;
} }
} }
public override void SetLength(long value) { throw new NotSupportedException(); } public override void SetLength(long value) { throw new NotSupportedException(); }
public override void Write(byte[] buffer, int offset, int count) {throw new NotSupportedException(); } public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); }
public override void Flush() { UnderlyingStream.Flush(); } public override void Flush() { UnderlyingStream.Flush(); }
public override void Close() { UnderlyingStream.Close(); } public override void Close() { UnderlyingStream.Close(); }
protected override void Dispose(bool disposing) protected override void Dispose(bool disposing)
@@ -1507,7 +1506,7 @@ namespace WPinternals
} }
// For writing a compressed stream // For writing a compressed stream
internal class CompressedStream: Stream internal class CompressedStream : Stream
{ {
private UInt32 HeaderSize; private UInt32 HeaderSize;
private UInt64 WritePosition; private UInt64 WritePosition;
@@ -1541,7 +1540,7 @@ namespace WPinternals
public override bool CanWrite { get { return true; } } public override bool CanWrite { get { return true; } }
public override long Length { get { return (long)WritePosition; } } public override long Length { get { return (long)WritePosition; } }
public override void SetLength(long value) { throw new NotSupportedException(); } public override void SetLength(long value) { throw new NotSupportedException(); }
public override void Write(byte[] buffer, int offset, int count) public override void Write(byte[] buffer, int offset, int count)
{ {
WritePosition += (UInt64)count; WritePosition += (UInt64)count;
UnderlyingStream.Write(buffer, offset, count); UnderlyingStream.Write(buffer, offset, count);
@@ -1558,7 +1557,7 @@ namespace WPinternals
} }
} }
internal class SeekableStream: Stream internal class SeekableStream : Stream
{ {
private Stream UnderlyingStream; private Stream UnderlyingStream;
private Int64 ReadPosition = 0; private Int64 ReadPosition = 0;
@@ -1579,7 +1578,7 @@ namespace WPinternals
UnderlyingStreamLength = UnderlyingStream.Length; UnderlyingStreamLength = UnderlyingStream.Length;
} }
catch catch
{ {
throw new ArgumentException("Unknown stream length"); throw new ArgumentException("Unknown stream length");
} }
} }
@@ -1587,7 +1586,7 @@ namespace WPinternals
public override bool CanRead { get { return true; } } public override bool CanRead { get { return true; } }
public override bool CanSeek { get { return true; } } public override bool CanSeek { get { return true; } }
public override int Read(byte[] buffer, int offset, int count) public override int Read(byte[] buffer, int offset, int count)
{ {
int RealCount = UnderlyingStream.Read(buffer, offset, count); int RealCount = UnderlyingStream.Read(buffer, offset, count);
ReadPosition += RealCount; ReadPosition += RealCount;
@@ -1642,19 +1641,19 @@ namespace WPinternals
{ {
return ReadPosition; return ReadPosition;
} }
set set
{ {
Seek(value, SeekOrigin.Begin); Seek(value, SeekOrigin.Begin);
} }
} }
public override bool CanTimeout { get { return UnderlyingStream.CanTimeout; } } public override bool CanTimeout { get { return UnderlyingStream.CanTimeout; } }
public override bool CanWrite { get { return false; } } public override bool CanWrite { get { return false; } }
public override long Length public override long Length
{ {
get get
{ {
return UnderlyingStreamLength; return UnderlyingStreamLength;
} }
} }
public override void SetLength(long value) { throw new NotSupportedException(); } public override void SetLength(long value) { throw new NotSupportedException(); }
public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); }
@@ -1929,7 +1928,7 @@ namespace WPinternals
/// </summary> /// </summary>
public static class GridViewColumnResize public static class GridViewColumnResize
{ {
#region DependencyProperties #region DependencyProperties
public static readonly DependencyProperty WidthProperty = public static readonly DependencyProperty WidthProperty =
DependencyProperty.RegisterAttached("Width", typeof(string), typeof(GridViewColumnResize), DependencyProperty.RegisterAttached("Width", typeof(string), typeof(GridViewColumnResize),
@@ -1948,7 +1947,7 @@ namespace WPinternals
DependencyProperty.RegisterAttached("ListViewResizeBehaviorProperty", DependencyProperty.RegisterAttached("ListViewResizeBehaviorProperty",
typeof(ListViewResizeBehavior), typeof(GridViewColumnResize), null); typeof(ListViewResizeBehavior), typeof(GridViewColumnResize), null);
#endregion #endregion
public static string GetWidth(DependencyObject obj) public static string GetWidth(DependencyObject obj)
{ {
@@ -1970,7 +1969,7 @@ namespace WPinternals
obj.SetValue(EnabledProperty, value); obj.SetValue(EnabledProperty, value);
} }
#region CallBack #region CallBack
private static void OnSetWidthCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e) private static void OnSetWidthCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
{ {
@@ -2025,10 +2024,10 @@ namespace WPinternals
return behavior; return behavior;
} }
#endregion #endregion
#region Nested type: GridViewColumnResizeBehavior
#region Nested type: GridViewColumnResizeBehavior
// This class was written by: Rolf Wessels // This class was written by: Rolf Wessels
// https://github.com/rolfwessels/lazycowprojects/tree/master/Wpf // https://github.com/rolfwessels/lazycowprojects/tree/master/Wpf
@@ -2103,13 +2102,13 @@ namespace WPinternals
} }
} }
#endregion #endregion
#region Nested type: ListViewResizeBehavior #region Nested type: ListViewResizeBehavior
// This class was written by: Rolf Wessels // This class was written by: Rolf Wessels
// https://github.com/rolfwessels/lazycowprojects/tree/master/Wpf // https://github.com/rolfwessels/lazycowprojects/tree/master/Wpf
/// <summary> /// <summary>
/// ListViewResizeBehavior class that gets attached to the ListView control /// ListViewResizeBehavior class that gets attached to the ListView control
/// </summary> /// </summary>
@@ -2211,7 +2210,7 @@ namespace WPinternals
} }
} }
#endregion #endregion
} }
internal static class ExtensionMethods internal static class ExtensionMethods
+1 -1
View File
@@ -365,7 +365,7 @@ namespace WPinternals
uint crc = (uint)(((uint)0) ^ (-1)); uint crc = (uint)(((uint)0) ^ (-1));
for (var i = Offset; i < (Offset + Length); i++) for (var i = Offset; i < (Offset + Length); i++)
{ {
crc = (crc >> 8) ^ CRC32Table[ (crc ^ Input[i]) & 0xFF ]; crc = (crc >> 8) ^ CRC32Table[(crc ^ Input[i]) & 0xFF];
} }
crc = (uint)(crc ^ (-1)); crc = (uint)(crc ^ (-1));
+1 -1
View File
@@ -442,7 +442,7 @@ namespace WPinternals
byte[] mobilestartup = msms.ToArray(); byte[] mobilestartup = msms.ToArray();
Version OSVersion = PE.GetProductVersion(mobilestartup); Version OSVersion = PE.GetProductVersion(mobilestartup);
s.Close(); s.Close();
return OSVersion.ToString(); return OSVersion.ToString();
} }
} }
+1 -1
View File
@@ -39,7 +39,7 @@ namespace WPinternals
Buffer.BlockCopy(Input, (int)Offset, Properties, 0, 5); Buffer.BlockCopy(Input, (int)Offset, Properties, 0, 5);
UInt64 OutputSize = ByteOperations.ReadUInt64(Input, Offset + 5); UInt64 OutputSize = ByteOperations.ReadUInt64(Input, Offset + 5);
SevenZip.Compression.LZMA.Decoder Coder = new SevenZip.Compression.LZMA.Decoder(); SevenZip.Compression.LZMA.Decoder Coder = new SevenZip.Compression.LZMA.Decoder();
Coder.SetDecoderProperties(Properties); Coder.SetDecoderProperties(Properties);
+14 -14
View File
@@ -20,15 +20,15 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO;
using System.Linq; using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Net; using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Net.Http.Headers; using System.Net.Http.Headers;
using System.IO; using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
using System.Xml; using System.Xml;
using System.Xml.Serialization; using System.Xml.Serialization;
@@ -202,13 +202,13 @@ namespace WPinternals
if (SoftwarePackages != null) if (SoftwarePackages != null)
{ {
foreach (SoftwarePackage pkg in SoftwarePackages.softwarePackages) foreach (SoftwarePackage pkg in SoftwarePackages.softwarePackages)
Package = SoftwarePackages.softwarePackages.FirstOrDefault<SoftwarePackage>(); Package = SoftwarePackages.softwarePackages.FirstOrDefault<SoftwarePackage>();
} }
} }
if (Package == null) if (Package == null)
throw new WPinternalsException("ENOSW package not found"); throw new WPinternalsException("ENOSW package not found");
SoftwareFile FileInfo = Package.files.Where(f => f.fileName.EndsWith(".secwim", StringComparison.OrdinalIgnoreCase)).First(); SoftwareFile FileInfo = Package.files.Where(f => f.fileName.EndsWith(".secwim", StringComparison.OrdinalIgnoreCase)).First();
SoftwareFile DPLF = Package.files.Where(f => f.fileName.EndsWith(".dpl", StringComparison.OrdinalIgnoreCase)).First(); SoftwareFile DPLF = Package.files.Where(f => f.fileName.EndsWith(".dpl", StringComparison.OrdinalIgnoreCase)).First();
@@ -231,11 +231,11 @@ namespace WPinternals
if (DPLUrl == "") if (DPLUrl == "")
throw new WPinternalsException("DPL not found"); throw new WPinternalsException("DPL not found");
Task<string> GetDPLStrTask = HttpClient.GetStringAsync(DPLUrl); Task<string> GetDPLStrTask = HttpClient.GetStringAsync(DPLUrl);
GetDPLStrTask.Wait(); GetDPLStrTask.Wait();
string DPLStrString = GetDPLStrTask.Result; string DPLStrString = GetDPLStrTask.Result;
DPL.Package dpl; DPL.Package dpl;
XmlSerializer serializer = new XmlSerializer(typeof(DPL.Package)); XmlSerializer serializer = new XmlSerializer(typeof(DPL.Package));
using (StringReader reader = new StringReader(DPLStrString.Replace("ft:", "").Replace("dpl:", "").Replace("typedes:", ""))) using (StringReader reader = new StringReader(DPLStrString.Replace("ft:", "").Replace("dpl:", "").Replace("typedes:", "")))
@@ -246,9 +246,9 @@ namespace WPinternals
foreach (DPL.File file in dpl.Content.Files.File) foreach (DPL.File file in dpl.Content.Files.File)
{ {
string name = file.Name; string name = file.Name;
DPL.Range range = file.Extensions.MmosWimFile.UseCaseCompatibilities.Compatibility.FirstOrDefault().Range; DPL.Range range = file.Extensions.MmosWimFile.UseCaseCompatibilities.Compatibility.FirstOrDefault().Range;
if (IsFirmwareBetween(PhoneFirmwareRevision, range.From, range.To)) if (IsFirmwareBetween(PhoneFirmwareRevision, range.From, range.To))
FileInfo = Package.files.Where(f => f.fileName.EndsWith(name, StringComparison.OrdinalIgnoreCase)).First(); FileInfo = Package.files.Where(f => f.fileName.EndsWith(name, StringComparison.OrdinalIgnoreCase)).First();
} }
@@ -363,7 +363,7 @@ namespace WPinternals
} }
} }
#pragma warning disable 0649 #pragma warning disable 0649
[DataContract] [DataContract]
internal class FileUrlResult internal class FileUrlResult
{ {
@@ -379,7 +379,7 @@ namespace WPinternals
[DataMember] [DataMember]
internal List<SoftwareFileChecksum> checksum; internal List<SoftwareFileChecksum> checksum;
} }
#pragma warning restore 0649 #pragma warning restore 0649
[DataContract] [DataContract]
public class DiscoveryQueryParameters public class DiscoveryQueryParameters
@@ -454,7 +454,7 @@ namespace WPinternals
[DataMember] [DataMember]
public List<string> response; public List<string> response;
public DiscoveryParameters(): this(DiscoveryCondition.Default) public DiscoveryParameters() : this(DiscoveryCondition.Default)
{ {
} }
+8 -8
View File
@@ -26,7 +26,7 @@ using System.Runtime.InteropServices;
namespace WPinternals namespace WPinternals
{ {
internal class MassStorage: NokiaPhoneModel internal class MassStorage : NokiaPhoneModel
{ {
internal string Drive = null; internal string Drive = null;
internal string PhysicalDrive = null; internal string PhysicalDrive = null;
@@ -36,8 +36,8 @@ namespace WPinternals
private bool OpenWithWriteAccess; private bool OpenWithWriteAccess;
private QualcommSerial Serial; private QualcommSerial Serial;
internal MassStorage(string DevicePath): base(DevicePath) internal MassStorage(string DevicePath) : base(DevicePath)
{ {
try try
{ {
@@ -288,7 +288,7 @@ namespace WPinternals
ProgressUpdater Progress = UpdaterPerSector; ProgressUpdater Progress = UpdaterPerSector;
if ((Progress == null) && (ProgressUpdateCallback != null)) if ((Progress == null) && (ProgressUpdateCallback != null))
Progress = new ProgressUpdater(SectorCount, ProgressUpdateCallback); Progress = new ProgressUpdater(SectorCount, ProgressUpdateCallback);
byte[] Buffer; byte[] Buffer;
if (SectorCount >= 0x80) if (SectorCount >= 0x80)
Buffer = new byte[0x10000]; Buffer = new byte[0x10000];
@@ -425,13 +425,13 @@ namespace WPinternals
OpenVolume(true); OpenVolume(true);
SetSectorPosition(StartSector); SetSectorPosition(StartSector);
byte[] Buffer; byte[] Buffer;
using (BinaryReader Reader = new BinaryReader(File.Open(Path, FileMode.Open))) using (BinaryReader Reader = new BinaryReader(File.Open(Path, FileMode.Open)))
{ {
ProgressUpdater Progress = UpdaterPerSector; ProgressUpdater Progress = UpdaterPerSector;
if ((Progress == null) && (ProgressUpdateCallback != null)) if ((Progress == null) && (ProgressUpdateCallback != null))
Progress = new ProgressUpdater((UInt64)(Reader.BaseStream.Length / 0x200), ProgressUpdateCallback); Progress = new ProgressUpdater((UInt64)(Reader.BaseStream.Length / 0x200), ProgressUpdateCallback);
if (Reader.BaseStream.Length >= 0x10000) if (Reader.BaseStream.Length >= 0x10000)
@@ -443,9 +443,9 @@ namespace WPinternals
for (UInt64 i = 0; i < (UInt64)(Reader.BaseStream.Length / 0x200); i += 0x80) for (UInt64 i = 0; i < (UInt64)(Reader.BaseStream.Length / 0x200); i += 0x80)
{ {
Count = Reader.Read(Buffer, 0, Buffer.Length); Count = Reader.Read(Buffer, 0, Buffer.Length);
WriteSectors(Buffer, (uint)Count); WriteSectors(Buffer, (uint)Count);
if (Progress != null) if (Progress != null)
Progress.IncreaseProgress((ulong)Count / 0x200); Progress.IncreaseProgress((ulong)Count / 0x200);
} }
+3 -3
View File
@@ -18,10 +18,10 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE. // DEALINGS IN THE SOFTWARE.
using System;
using System.Runtime.InteropServices;
using System.Runtime.ConstrainedExecution;
using Microsoft.Win32.SafeHandles; using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Security; using System.Security;
namespace WPinternals namespace WPinternals
+12 -12
View File
@@ -100,7 +100,7 @@ namespace WPinternals
uint? flags = ReadSecurityFlags(); uint? flags = ReadSecurityFlags();
if (!flags.HasValue) if (!flags.HasValue)
return null; return null;
var finalconfig = (Fuse)flags.Value; var finalconfig = (Fuse)flags.Value;
return finalconfig.HasFlag(fuse); return finalconfig.HasFlag(fuse);
} }
@@ -186,7 +186,7 @@ namespace WPinternals
public void SendFfuHeaderV1(byte[] FfuHeader, byte Options = 0) public void SendFfuHeaderV1(byte[] FfuHeader, byte Options = 0)
{ {
byte[] Request = new byte[FfuHeader.Length + 0x20]; byte[] Request = new byte[FfuHeader.Length + 0x20];
string Header = "NOKXFS"; string Header = "NOKXFS";
System.Buffer.BlockCopy(System.Text.Encoding.ASCII.GetBytes(Header), 0, Request, 0, Header.Length); System.Buffer.BlockCopy(System.Text.Encoding.ASCII.GetBytes(Header), 0, Request, 0, Header.Length);
System.Buffer.BlockCopy(BigEndian.GetBytes(0x0001, 2), 0, Request, 0x06, 2); // Protocol version = 0x0001 System.Buffer.BlockCopy(BigEndian.GetBytes(0x0001, 2), 0, Request, 0x06, 2); // Protocol version = 0x0001
@@ -279,7 +279,7 @@ namespace WPinternals
System.Buffer.BlockCopy(BigEndian.GetBytes(0x0000001B, 4), 0, Request, 0x0C, 4); // Subblock type for Payload v2 = 0x1B System.Buffer.BlockCopy(BigEndian.GetBytes(0x0000001B, 4), 0, Request, 0x0C, 4); // Subblock type for Payload v2 = 0x1B
System.Buffer.BlockCopy(BigEndian.GetBytes(FfuChunk.Length + 0x0C, 4), 0, Request, 0x10, 4); // Subblock length = length of chunk + 0x08 System.Buffer.BlockCopy(BigEndian.GetBytes(FfuChunk.Length + 0x0C, 4), 0, Request, 0x10, 4); // Subblock length = length of chunk + 0x08
System.Buffer.BlockCopy(BigEndian.GetBytes(FfuChunk.Length, 4), 0, Request, 0x14, 4); // Payload length = length of chunk System.Buffer.BlockCopy(BigEndian.GetBytes(FfuChunk.Length, 4), 0, Request, 0x14, 4); // Payload length = length of chunk
Request[0x18] = Options; // Data options = 0 (1 = verify) Request[0x18] = Options; // Data options = 0 (1 = verify)
@@ -368,18 +368,18 @@ namespace WPinternals
if (ResultCode != 0) if (ResultCode != 0)
ThrowFlashError(ResultCode); ThrowFlashError(ResultCode);
} }
internal void SwitchToMmosContext() internal void SwitchToMmosContext()
{ {
byte[] Request = new byte[7]; byte[] Request = new byte[7];
ByteOperations.WriteAsciiString(Request, 0, "NOKXCBA"); ByteOperations.WriteAsciiString(Request, 0, "NOKXCBA");
ExecuteRawVoidMethod(Request); ExecuteRawVoidMethod(Request);
ResetDevice(); ResetDevice();
Dispose(true); Dispose(true);
} }
private void ThrowFlashError(int ErrorCode) private void ThrowFlashError(int ErrorCode)
{ {
string SubMessage; string SubMessage;
@@ -549,11 +549,11 @@ namespace WPinternals
MMOSFile.Read(data, 0, (int)(length - offset)); MMOSFile.Read(data, 0, (int)(length - offset));
LoadMmosBinary(length, (uint)offset, false, data); LoadMmosBinary(length, (uint)offset, false, data);
} }
SwitchToMmosContext(); SwitchToMmosContext();
ResetPhone(); ResetPhone();
} }
LogFile.EndAction("FlashMMOS"); LogFile.EndAction("FlashMMOS");
} }
@@ -613,9 +613,9 @@ namespace WPinternals
// If this function is used with a locked BootMgr v1, // If this function is used with a locked BootMgr v1,
// then the mode-switching should be done outside this function, // then the mode-switching should be done outside this function,
// because the context-switches that are used here are not supported on BootMgr v1. // because the context-switches that are used here are not supported on BootMgr v1.
// Only works in BootLoader-mode or on unlocked bootloaders in Flash-mode!! // Only works in BootLoader-mode or on unlocked bootloaders in Flash-mode!!
PhoneInfo Info = ReadPhoneInfo(ExtendedInfo: false); PhoneInfo Info = ReadPhoneInfo(ExtendedInfo: false);
FlashAppType OriginalAppType = Info.App; FlashAppType OriginalAppType = Info.App;
bool Switch = ((Info.App != FlashAppType.BootManager) && Info.SecureFfuEnabled && !Info.Authenticated && !Info.RdcPresent); bool Switch = ((Info.App != FlashAppType.BootManager) && Info.SecureFfuEnabled && !Info.Authenticated && !Info.RdcPresent);
@@ -1112,7 +1112,7 @@ namespace WPinternals
ExecuteRawMethod(Request); ExecuteRawMethod(Request);
} }
internal enum SecureBootKeyType: byte internal enum SecureBootKeyType : byte
{ {
Retail = 0, Retail = 0,
Engineering = 1 Engineering = 1
@@ -1154,7 +1154,7 @@ namespace WPinternals
public string Imei; // Extended info public string Imei; // Extended info
public string Firmware; // Extended info public string Firmware; // Extended info
public byte[] RKH; // Extended info public byte[] RKH; // Extended info
public FlashAppType App; public FlashAppType App;
public byte FlashAppVersionMajor; public byte FlashAppVersionMajor;
+1 -1
View File
@@ -27,7 +27,7 @@ using System.Linq;
namespace WPinternals namespace WPinternals
{ {
internal class NokiaPhoneModel: IDisposable internal class NokiaPhoneModel : IDisposable
{ {
protected bool Disposed = false; protected bool Disposed = false;
private USBDevice Device = null; private USBDevice Device = null;
+2 -2
View File
@@ -21,15 +21,15 @@
using System; using System;
using System.Collections.Specialized; using System.Collections.Specialized;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.ConstrainedExecution; using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Threading; using System.Threading;
namespace WPinternals namespace WPinternals
{ {
using Luid = NativeMethods.LUID; using Luid = NativeMethods.LUID;
using Win32Exception = System.ComponentModel.Win32Exception;
using PrivilegeNotHeldException = System.Security.AccessControl.PrivilegeNotHeldException; using PrivilegeNotHeldException = System.Security.AccessControl.PrivilegeNotHeldException;
using Win32Exception = System.ComponentModel.Win32Exception;
internal delegate void PrivilegedCallback(object state); internal delegate void PrivilegedCallback(object state);
+1 -1
View File
@@ -47,7 +47,7 @@ namespace WPinternals
internal uint CertificatesOffset; internal uint CertificatesOffset;
internal byte[] RootKeyHash = null; internal byte[] RootKeyHash = null;
internal QualcommPartition(string Path): this(File.ReadAllBytes(Path)) { } internal QualcommPartition(string Path) : this(File.ReadAllBytes(Path)) { }
internal QualcommPartition(byte[] Binary, uint Offset = 0) internal QualcommPartition(byte[] Binary, uint Offset = 0)
{ {
+3 -3
View File
@@ -23,7 +23,7 @@ using System.Threading.Tasks;
namespace WPinternals namespace WPinternals
{ {
internal enum SaharaMode: uint internal enum SaharaMode : uint
{ {
ImageTransferPending = 0x00, ImageTransferPending = 0x00,
ImagetransferComplete = 0x01, ImagetransferComplete = 0x01,
@@ -154,7 +154,7 @@ namespace WPinternals
LogFile.Log("MaxLength: 0x" + ByteOperations.ReadUInt32(Hello, 0x10).ToString("X8"), LogType.FileOnly); LogFile.Log("MaxLength: 0x" + ByteOperations.ReadUInt32(Hello, 0x10).ToString("X8"), LogType.FileOnly);
LogFile.Log("Mode: 0x" + ByteOperations.ReadUInt32(Hello, 0x14).ToString("X8"), LogType.FileOnly); LogFile.Log("Mode: 0x" + ByteOperations.ReadUInt32(Hello, 0x14).ToString("X8"), LogType.FileOnly);
byte[] HelloResponse = new byte[] { byte[] HelloResponse = new byte[] {
0x02, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
@@ -233,7 +233,7 @@ namespace WPinternals
Incoming = System.Text.Encoding.ASCII.GetString(Serial.GetResponse(null)); Incoming = System.Text.Encoding.ASCII.GetString(Serial.GetResponse(null));
LogFile.Log("In: " + Incoming, LogType.FileOnly); LogFile.Log("In: " + Incoming, LogType.FileOnly);
}; };
LogFile.Log("Incoming Hello-response received", LogType.FileOnly); LogFile.Log("Incoming Hello-response received", LogType.FileOnly);
HandshakeCompleted = true; HandshakeCompleted = true;
} }
+4 -4
View File
@@ -24,7 +24,7 @@ using System.IO.Ports;
namespace WPinternals namespace WPinternals
{ {
internal class QualcommSerial: IDisposable internal class QualcommSerial : IDisposable
{ {
private bool Disposed = false; private bool Disposed = false;
private SerialPort Port = null; private SerialPort Port = null;
@@ -37,7 +37,7 @@ namespace WPinternals
public QualcommSerial(string DevicePath) public QualcommSerial(string DevicePath)
{ {
CRC16 = new CRC16(0x1189, 0xFFFF, 0xFFFF); CRC16 = new CRC16(0x1189, 0xFFFF, 0xFFFF);
string[] DevicePathElements = DevicePath.Split(new char[] { '#' }); string[] DevicePathElements = DevicePath.Split(new char[] { '#' });
if (string.Compare(DevicePathElements[3], "{86E0D1E0-8089-11D0-9CE4-08003E301F73}", true) == 0) if (string.Compare(DevicePathElements[3], "{86E0D1E0-8089-11D0-9CE4-08003E301F73}", true) == 0)
{ {
@@ -132,7 +132,7 @@ namespace WPinternals
for (int i = 0; i < ResponsePattern.Length; i++) for (int i = 0; i < ResponsePattern.Length; i++)
if (DecodedResponse[i] != ResponsePattern[i]) if (DecodedResponse[i] != ResponsePattern[i])
{ {
byte[] LogResponse = new byte[DecodedResponse.Length < 0x10 ? DecodedResponse.Length: 0x10]; byte[] LogResponse = new byte[DecodedResponse.Length < 0x10 ? DecodedResponse.Length : 0x10];
LogFile.Log("Qualcomm serial response: " + Converter.ConvertHexToString(LogResponse, ""), LogType.FileOnly); LogFile.Log("Qualcomm serial response: " + Converter.ConvertHexToString(LogResponse, ""), LogType.FileOnly);
LogFile.Log("Expected: " + Converter.ConvertHexToString(ResponsePattern, ""), LogType.FileOnly); LogFile.Log("Expected: " + Converter.ConvertHexToString(ResponsePattern, ""), LogType.FileOnly);
throw new BadMessageException(); throw new BadMessageException();
@@ -292,7 +292,7 @@ namespace WPinternals
public class CRC16 public class CRC16
{ {
private UInt16[] ChecksumTable = private UInt16[] ChecksumTable =
new UInt16[] { new UInt16[] {
0x0000, 0x1189, 0x2312, 0x329b, 0x4624, 0x57ad, 0x6536, 0x74bf, 0x0000, 0x1189, 0x2312, 0x329b, 0x4624, 0x57ad, 0x6536, 0x74bf,
0x8c48, 0x9dc1, 0xaf5a, 0xbed3, 0xca6c, 0xdbe5, 0xe97e, 0xf8f7, 0x8c48, 0x9dc1, 0xaf5a, 0xbed3, 0xca6c, 0xdbe5, 0xe97e, 0xf8f7,
+4 -4
View File
@@ -22,14 +22,14 @@ using System;
namespace WPinternals namespace WPinternals
{ {
internal class SBL1: QualcommPartition internal class SBL1 : QualcommPartition
{ {
internal SBL1(byte[] Binary): base(Binary, 0x2800) { } internal SBL1(byte[] Binary) : base(Binary, 0x2800) { }
internal byte[] GenerateExtraSector(byte[] PartitionHeader) internal byte[] GenerateExtraSector(byte[] PartitionHeader)
{ {
UInt32? Offset = ByteOperations.FindPattern(Binary, UInt32? Offset = ByteOperations.FindPattern(Binary,
new byte[] { new byte[] {
0x15, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x15, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x05, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
@@ -56,7 +56,7 @@ namespace WPinternals
Offset = ByteOperations.FindPattern(Binary, Offset = ByteOperations.FindPattern(Binary,
new byte[] { new byte[] {
0x01, 0xFF, 0xA0, 0xE3, 0xFF, 0xFF, 0xA0, 0xE1, 0x1C, 0xD0, 0x8D, 0xE2, 0xF0, 0x4F, 0xBD, 0xE8, 0x01, 0xFF, 0xA0, 0xE3, 0xFF, 0xFF, 0xA0, 0xE1, 0x1C, 0xD0, 0x8D, 0xE2, 0xF0, 0x4F, 0xBD, 0xE8,
0x1E, 0xFF, 0x2F, 0xE1 0x1E, 0xFF, 0x2F, 0xE1
}, },
new byte[] { new byte[] {
+1 -1
View File
@@ -42,7 +42,7 @@ namespace WPinternals
0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
}, },
null); null);
if (PatchOffset == null) if (PatchOffset == null)
throw new BadImageFormatException(); throw new BadImageFormatException();
+2 -2
View File
@@ -35,7 +35,7 @@ namespace WPinternals
internal SBL3(string FileName) internal SBL3(string FileName)
{ {
Binary = null; Binary = null;
// First try to parse as FFU // First try to parse as FFU
try try
{ {
@@ -52,7 +52,7 @@ namespace WPinternals
{ {
byte[] SBL3Header; byte[] SBL3Header;
byte[] SBL3Pattern = new byte[] { 0x18, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x8F, 0xFF, 0xFF, 0xFF, 0xFF }; byte[] SBL3Pattern = new byte[] { 0x18, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x8F, 0xFF, 0xFF, 0xFF, 0xFF };
byte[] SBL3Mask = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF }; byte[] SBL3Mask = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF };
UInt32? Offset = ByteOperations.FindPatternInFile(FileName, SBL3Pattern, SBL3Mask, out SBL3Header); UInt32? Offset = ByteOperations.FindPatternInFile(FileName, SBL3Pattern, SBL3Mask, out SBL3Header);
+7 -7
View File
@@ -324,7 +324,7 @@ namespace WPinternals
Buffer.BlockCopy( Buffer.BlockCopy(
DecompressedImage, DecompressedImage,
(int)(File.BinaryOffset + OldBinarySize + OldSectionPadding), (int)(File.BinaryOffset + OldBinarySize + OldSectionPadding),
NewImage, NewImage,
(int)(File.BinaryOffset + NewBinarySize + NewSectionPadding), (int)(File.BinaryOffset + NewBinarySize + NewSectionPadding),
(int)(File.FileOffset + OldFileSize - File.BinaryOffset - OldBinarySize - OldSectionPadding)); (int)(File.FileOffset + OldFileSize - File.BinaryOffset - OldBinarySize - OldSectionPadding));
@@ -334,8 +334,8 @@ namespace WPinternals
// Copy volume-tail // Copy volume-tail
Buffer.BlockCopy( Buffer.BlockCopy(
DecompressedImage, DecompressedImage,
(int)(File.FileOffset + OldFileSize + OldFilePadding), (int)(File.FileOffset + OldFileSize + OldFilePadding),
NewImage, NewImage,
(int)(File.FileOffset + NewFileSize + NewFilePadding), (int)(File.FileOffset + NewFileSize + NewFilePadding),
(int)(DecompressedImage.Length - File.FileOffset - OldFileSize - OldFilePadding)); (int)(DecompressedImage.Length - File.FileOffset - OldFileSize - OldFilePadding));
@@ -386,7 +386,7 @@ namespace WPinternals
// The new binary will include the Qualcomm header, but not the signature and certificates, because they won't match anyway. // The new binary will include the Qualcomm header, but not the signature and certificates, because they won't match anyway.
byte[] NewBinary = new byte[Binary.Length]; byte[] NewBinary = new byte[Binary.Length];
Buffer.BlockCopy(Binary, 0, NewBinary, 0, (int)CompressedSubImageOffset); Buffer.BlockCopy(Binary, 0, NewBinary, 0, (int)CompressedSubImageOffset);
ByteOperations.WriteUInt32(NewBinary, 0x10, ByteOperations.ReadUInt32(NewBinary, 0x14)); // Complete image size - does not include signature and certs anymore ByteOperations.WriteUInt32(NewBinary, 0x10, ByteOperations.ReadUInt32(NewBinary, 0x14)); // Complete image size - does not include signature and certs anymore
ByteOperations.WriteUInt32(NewBinary, 0x18, 0x00000000); // Address of signature ByteOperations.WriteUInt32(NewBinary, 0x18, 0x00000000); // Address of signature
ByteOperations.WriteUInt32(NewBinary, 0x1C, 0x00000000); // Signature length ByteOperations.WriteUInt32(NewBinary, 0x1C, 0x00000000); // Signature length
@@ -433,7 +433,7 @@ namespace WPinternals
if (NewCompressedImage.Length > CompressedSubImageSize) if (NewCompressedImage.Length > CompressedSubImageSize)
{ {
Buffer.BlockCopy(Binary, (int)(FileHeaderOffset + OldFileSize + OldFilePadding), NewBinary, (int)(FileHeaderOffset + NewFileSize + NewFilePadding), Buffer.BlockCopy(Binary, (int)(FileHeaderOffset + OldFileSize + OldFilePadding), NewBinary, (int)(FileHeaderOffset + NewFileSize + NewFilePadding),
(int)(VolumeHeaderOffset + VolumeSize - FileHeaderOffset - NewFileSize - NewFilePadding)); (int)(VolumeHeaderOffset + VolumeSize - FileHeaderOffset - NewFileSize - NewFilePadding));
} }
else else
@@ -548,8 +548,8 @@ namespace WPinternals
byte[] SecurityDxe = GetFile("SecurityDxe"); byte[] SecurityDxe = GetFile("SecurityDxe");
ClearEfiChecksum(SecurityDxe); ClearEfiChecksum(SecurityDxe);
UInt32? PatchOffset = ByteOperations.FindPattern(SecurityDxe, UInt32? PatchOffset = ByteOperations.FindPattern(SecurityDxe,
new byte[] { 0xF0, 0x41, 0x2D, 0xE9, 0xFF, 0xFF, 0xB0, 0xE1, 0x28, 0xD0, 0x4D, 0xE2, 0xFF, 0xFF, 0xA0, 0xE1, 0x00, 0x00, 0xFF, 0x13, 0x20, 0xFF, 0xA0, 0xE3 }, new byte[] { 0xF0, 0x41, 0x2D, 0xE9, 0xFF, 0xFF, 0xB0, 0xE1, 0x28, 0xD0, 0x4D, 0xE2, 0xFF, 0xFF, 0xA0, 0xE1, 0x00, 0x00, 0xFF, 0x13, 0x20, 0xFF, 0xA0, 0xE3 },
new byte[] { 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0xFF, 0x00, 0x00 }, new byte[] { 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0xFF, 0x00, 0x00 },
null); null);
+4 -6
View File
@@ -1,6 +1,4 @@
using System.Reflection; using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Windows; using System.Windows;
@@ -33,11 +31,11 @@ using System.Windows;
[assembly: ThemeInfo( [assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page, //(used if a resource is not found in the page,
// or application resource dictionaries) // or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page, //(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries) // app, or any theme specific resource dictionaries)
)] )]
+1 -1
View File
@@ -20,7 +20,7 @@
namespace WPinternals namespace WPinternals
{ {
internal class AboutViewModel: ContextViewModel internal class AboutViewModel : ContextViewModel
{ {
internal AboutViewModel() : base() { } internal AboutViewModel() : base() { }
+1 -1
View File
@@ -23,7 +23,7 @@ using System.Threading;
namespace WPinternals namespace WPinternals
{ {
internal class BackupTargetSelectionViewModel: ContextViewModel internal class BackupTargetSelectionViewModel : ContextViewModel
{ {
private PhoneNotifierViewModel PhoneNotifier; private PhoneNotifierViewModel PhoneNotifier;
private Action<string, string, string> BackupCallback; private Action<string, string, string> BackupCallback;
+2 -2
View File
@@ -26,7 +26,7 @@ using System.Threading;
namespace WPinternals namespace WPinternals
{ {
internal class BackupViewModel: ContextViewModel internal class BackupViewModel : ContextViewModel
{ {
private PhoneNotifierViewModel PhoneNotifier; private PhoneNotifierViewModel PhoneNotifier;
private Action Callback; private Action Callback;
@@ -413,7 +413,7 @@ namespace WPinternals
{ {
Partition = GPT.Partitions.Where(p => p.Name == "BACKUP_BS_NV").First(); Partition = GPT.Partitions.Where(p => p.Name == "BACKUP_BS_NV").First();
} }
TotalSizeSectors += Partition.SizeInSectors; TotalSizeSectors += Partition.SizeInSectors;
PartitionCount++; PartitionCount++;
} }
+2 -2
View File
@@ -103,7 +103,7 @@ namespace WPinternals
OnPropertyChanged("SubMessage"); OnPropertyChanged("SubMessage");
} }
} }
private int? _ProgressPercentage = null; private int? _ProgressPercentage = null;
public int? ProgressPercentage public int? ProgressPercentage
{ {
@@ -148,7 +148,7 @@ namespace WPinternals
{ {
NewText = "Progress: " + ((int)ProgressPercentage).ToString() + "%"; NewText = "Progress: " + ((int)ProgressPercentage).ToString() + "%";
} }
if (TimeRemaining != null) if (TimeRemaining != null)
{ {
if (NewText == null) if (NewText == null)
NewText = ""; NewText = "";

Some files were not shown because too many files have changed in this diff Show More