[pylzma] remove pylzma from sources, not needed here

This commit is contained in:
Fabio Erculiani
2009-09-30 19:34:27 +02:00
parent 85e92ea500
commit 376495b6b2
107 changed files with 0 additions and 13774 deletions

View File

@@ -8,10 +8,6 @@ all:
clean:
for d in $(SUBDIRS); do make -C $$d clean; done
cd pylzma && $(PYTHON) setup.py clean --all
pylzma:
cd pylzma && $(PYTHON) setup.py build
entropy-install:
@@ -120,11 +116,6 @@ sulfur-install:
make DESTDIR="$(DESTDIR)" -C sulfur install
pylzma-install:
mkdir -p $(DESTDIR)/$(LIBDIR)/entropy/libraries/pylzma/
cd pylzma && $(PYTHON) setup.py install --root="$(DESTDIR)" --install-lib="$(LIBDIR)/entropy/libraries/pylzma/"
pycompile-all:
$(PYTHON) -c "import compileall; compileall.compile_dir('$(DESTDIR)/$(LIBDIR)/entropy', force = True, quiet = True)"

View File

@@ -1,76 +0,0 @@
// InBuffer.h
#ifndef __INBUFFER_H
#define __INBUFFER_H
#include "../IStream.h"
#include "../../Common/MyCom.h"
#ifndef _NO_EXCEPTIONS
class CInBufferException
{
public:
HRESULT ErrorCode;
CInBufferException(HRESULT errorCode): ErrorCode(errorCode) {}
};
#endif
class CInBuffer
{
Byte *_buffer;
Byte *_bufferLimit;
Byte *_bufferBase;
CMyComPtr<ISequentialInStream> _stream;
UInt64 _processedSize;
UInt32 _bufferSize;
bool _wasFinished;
bool ReadBlock();
Byte ReadBlock2();
public:
#ifdef _NO_EXCEPTIONS
HRESULT ErrorCode;
#endif
CInBuffer();
~CInBuffer() { Free(); }
bool Create(UInt32 bufferSize);
void Free();
void SetStream(ISequentialInStream *stream);
void Init();
void ReleaseStream() { _stream.Release(); }
bool ReadByte(Byte &b)
{
if(_buffer >= _bufferLimit)
if(!ReadBlock())
return false;
b = *_buffer++;
return true;
}
Byte ReadByte()
{
if(_buffer >= _bufferLimit)
return ReadBlock2();
return *_buffer++;
}
void ReadBytes(void *data, UInt32 size, UInt32 &processedSize)
{
for(processedSize = 0; processedSize < size; processedSize++)
if (!ReadByte(((Byte *)data)[processedSize]))
return;
}
bool ReadBytes(void *data, UInt32 size)
{
UInt32 processedSize;
ReadBytes(data, size, processedSize);
return (processedSize == size);
}
UInt64 GetProcessedSize() const { return _processedSize + (_buffer - _bufferBase); }
bool WasFinished() const { return _wasFinished; }
};
#endif

View File

@@ -1,116 +0,0 @@
// OutByte.cpp
#include "StdAfx.h"
#include "OutBuffer.h"
#include "../../Common/Alloc.h"
bool COutBuffer::Create(UInt32 bufferSize)
{
const UInt32 kMinBlockSize = 1;
if (bufferSize < kMinBlockSize)
bufferSize = kMinBlockSize;
if (_buffer != 0 && _bufferSize == bufferSize)
return true;
Free();
_bufferSize = bufferSize;
_buffer = (Byte *)::MidAlloc(bufferSize);
return (_buffer != 0);
}
void COutBuffer::Free()
{
::MidFree(_buffer);
_buffer = 0;
}
void COutBuffer::SetStream(ISequentialOutStream *stream)
{
_stream = stream;
}
void COutBuffer::Init()
{
_streamPos = 0;
_limitPos = _bufferSize;
_pos = 0;
_processedSize = 0;
_overDict = false;
#ifdef _NO_EXCEPTIONS
ErrorCode = S_OK;
#endif
}
UInt64 COutBuffer::GetProcessedSize() const
{
UInt64 res = _processedSize + _pos - _streamPos;
if (_streamPos > _pos)
res += _bufferSize;
return res;
}
HRESULT COutBuffer::FlushPart()
{
// _streamPos < _bufferSize
UInt32 size = (_streamPos >= _pos) ? (_bufferSize - _streamPos) : (_pos - _streamPos);
HRESULT result = S_OK;
#ifdef _NO_EXCEPTIONS
result = ErrorCode;
#endif
if (_buffer2 != 0)
{
memmove(_buffer2, _buffer + _streamPos, size);
_buffer2 += size;
}
if (_stream != 0
#ifdef _NO_EXCEPTIONS
&& (ErrorCode == S_OK)
#endif
)
{
UInt32 processedSize = 0;
result = _stream->Write(_buffer + _streamPos, size, &processedSize);
size = processedSize;
}
_streamPos += size;
if (_streamPos == _bufferSize)
_streamPos = 0;
if (_pos == _bufferSize)
{
_overDict = true;
_pos = 0;
}
_limitPos = (_streamPos > _pos) ? _streamPos : _bufferSize;
_processedSize += size;
return result;
}
HRESULT COutBuffer::Flush()
{
#ifdef _NO_EXCEPTIONS
if (ErrorCode != S_OK)
return ErrorCode;
#endif
while(_streamPos != _pos)
{
HRESULT result = FlushPart();
if (result != S_OK)
return result;
}
return S_OK;
}
void COutBuffer::FlushWithCheck()
{
HRESULT result = FlushPart();
#ifdef _NO_EXCEPTIONS
ErrorCode = result;
#else
if (result != S_OK)
throw COutBufferException(result);
#endif
}

View File

@@ -1,64 +0,0 @@
// OutBuffer.h
#ifndef __OUTBUFFER_H
#define __OUTBUFFER_H
#include "../IStream.h"
#include "../../Common/MyCom.h"
#ifndef _NO_EXCEPTIONS
struct COutBufferException
{
HRESULT ErrorCode;
COutBufferException(HRESULT errorCode): ErrorCode(errorCode) {}
};
#endif
class COutBuffer
{
protected:
Byte *_buffer;
UInt32 _pos;
UInt32 _limitPos;
UInt32 _streamPos;
UInt32 _bufferSize;
CMyComPtr<ISequentialOutStream> _stream;
UInt64 _processedSize;
Byte *_buffer2;
bool _overDict;
HRESULT FlushPart();
void FlushWithCheck();
public:
#ifdef _NO_EXCEPTIONS
HRESULT ErrorCode;
#endif
COutBuffer(): _buffer(0), _pos(0), _stream(0), _buffer2(0) {}
~COutBuffer() { Free(); }
bool Create(UInt32 bufferSize);
void Free();
void SetMemStream(Byte *buffer) { _buffer2 = buffer; }
void SetStream(ISequentialOutStream *stream);
void Init();
HRESULT Flush();
void ReleaseStream() { _stream.Release(); }
void WriteByte(Byte b)
{
_buffer[_pos++] = b;
if(_pos == _limitPos)
FlushWithCheck();
}
void WriteBytes(const void *data, size_t size)
{
for (size_t i = 0; i < size; i++)
WriteByte(((const Byte *)data)[i]);
}
UInt64 GetProcessedSize() const;
};
#endif

View File

@@ -1,9 +0,0 @@
// StdAfx.h
#ifndef __STDAFX_H
#define __STDAFX_H
#include "../../Common/MyWindows.h"
#include "../../Common/NewHandler.h"
#endif

View File

@@ -1,44 +0,0 @@
// StreamUtils.cpp
#include "StdAfx.h"
#include "../../Common/MyCom.h"
#include "StreamUtils.h"
HRESULT ReadStream(ISequentialInStream *stream, void *data, UInt32 size, UInt32 *processedSize)
{
if (processedSize != 0)
*processedSize = 0;
while(size != 0)
{
UInt32 processedSizeLoc;
HRESULT res = stream->Read(data, size, &processedSizeLoc);
if (processedSize != 0)
*processedSize += processedSizeLoc;
data = (Byte *)((Byte *)data + processedSizeLoc);
size -= processedSizeLoc;
RINOK(res);
if (processedSizeLoc == 0)
return S_OK;
}
return S_OK;
}
HRESULT WriteStream(ISequentialOutStream *stream, const void *data, UInt32 size, UInt32 *processedSize)
{
if (processedSize != 0)
*processedSize = 0;
while(size != 0)
{
UInt32 processedSizeLoc;
HRESULT res = stream->Write(data, size, &processedSizeLoc);
if (processedSize != 0)
*processedSize += processedSizeLoc;
data = (const void *)((const Byte *)data + processedSizeLoc);
size -= processedSizeLoc;
RINOK(res);
if (processedSizeLoc == 0)
break;
}
return S_OK;
}

View File

@@ -1,11 +0,0 @@
// StreamUtils.h
#ifndef __STREAMUTILS_H
#define __STREAMUTILS_H
#include "../IStream.h"
HRESULT ReadStream(ISequentialInStream *stream, void *data, UInt32 size, UInt32 *processedSize);
HRESULT WriteStream(ISequentialOutStream *stream, const void *data, UInt32 size, UInt32 *processedSize);
#endif

View File

@@ -1,54 +0,0 @@
// BinTree.h
#include "../LZInWindow.h"
#include "../IMatchFinder.h"
namespace BT_NAMESPACE {
typedef UInt32 CIndex;
const UInt32 kMaxValForNormalize = (UInt32(1) << 31) - 1;
class CMatchFinder:
public IMatchFinder,
public CLZInWindow,
public CMyUnknownImp,
public IMatchFinderSetNumPasses
{
UInt32 _cyclicBufferPos;
UInt32 _cyclicBufferSize; // it must be historySize + 1
UInt32 _matchMaxLen;
CIndex *_hash;
CIndex *_son;
UInt32 _hashMask;
UInt32 _cutValue;
UInt32 _hashSizeSum;
void Normalize();
void FreeThisClassMemory();
void FreeMemory();
MY_UNKNOWN_IMP
STDMETHOD(SetStream)(ISequentialInStream *inStream);
STDMETHOD_(void, ReleaseStream)();
STDMETHOD(Init)();
HRESULT MovePos();
STDMETHOD_(Byte, GetIndexByte)(Int32 index);
STDMETHOD_(UInt32, GetMatchLen)(Int32 index, UInt32 back, UInt32 limit);
STDMETHOD_(UInt32, GetNumAvailableBytes)();
STDMETHOD_(const Byte *, GetPointerToCurrentPos)();
STDMETHOD_(Int32, NeedChangeBufferPos)(UInt32 numCheckBytes);
STDMETHOD_(void, ChangeBufferPos)();
STDMETHOD(Create)(UInt32 historySize, UInt32 keepAddBufferBefore,
UInt32 matchMaxLen, UInt32 keepAddBufferAfter);
STDMETHOD(GetMatches)(UInt32 *distances);
STDMETHOD(Skip)(UInt32 num);
public:
CMatchFinder();
virtual ~CMatchFinder();
virtual void SetNumPasses(UInt32 numPasses) { _cutValue = numPasses; }
};
}

View File

@@ -1,12 +0,0 @@
// BinTree2.h
#ifndef __BINTREE2_H
#define __BINTREE2_H
#define BT_NAMESPACE NBT2
#include "BinTreeMain.h"
#undef BT_NAMESPACE
#endif

View File

@@ -1,16 +0,0 @@
// BinTree3.h
#ifndef __BINTREE3_H
#define __BINTREE3_H
#define BT_NAMESPACE NBT3
#define HASH_ARRAY_2
#include "BinTreeMain.h"
#undef HASH_ARRAY_2
#undef BT_NAMESPACE
#endif

View File

@@ -1,16 +0,0 @@
// BinTree3Z.h
#ifndef __BINTREE3Z_H
#define __BINTREE3Z_H
#define BT_NAMESPACE NBT3Z
#define HASH_ZIP
#include "BinTreeMain.h"
#undef HASH_ZIP
#undef BT_NAMESPACE
#endif

View File

@@ -1,18 +0,0 @@
// BinTree4.h
#ifndef __BINTREE4_H
#define __BINTREE4_H
#define BT_NAMESPACE NBT4
#define HASH_ARRAY_2
#define HASH_ARRAY_3
#include "BinTreeMain.h"
#undef HASH_ARRAY_2
#undef HASH_ARRAY_3
#undef BT_NAMESPACE
#endif

View File

@@ -1,531 +0,0 @@
// BinTreeMain.h
#include "../../../../Common/Defs.h"
#include "../../../../Common/CRC.h"
#include "../../../../Common/Alloc.h"
#include "BinTree.h"
// #include <xmmintrin.h>
// It's for prefetch
// But prefetch doesn't give big gain in K8.
namespace BT_NAMESPACE {
#ifdef HASH_ARRAY_2
static const UInt32 kHash2Size = 1 << 10;
#define kNumHashDirectBytes 0
#ifdef HASH_ARRAY_3
static const UInt32 kNumHashBytes = 4;
static const UInt32 kHash3Size = 1 << 16;
#else
static const UInt32 kNumHashBytes = 3;
#endif
static const UInt32 kHashSize = 0;
static const UInt32 kMinMatchCheck = kNumHashBytes;
static const UInt32 kStartMaxLen = 1;
#else
#ifdef HASH_ZIP
#define kNumHashDirectBytes 0
static const UInt32 kNumHashBytes = 3;
static const UInt32 kHashSize = 1 << 16;
static const UInt32 kMinMatchCheck = kNumHashBytes;
static const UInt32 kStartMaxLen = 1;
#else
#define kNumHashDirectBytes 2
static const UInt32 kNumHashBytes = 2;
static const UInt32 kHashSize = 1 << (8 * kNumHashBytes);
static const UInt32 kMinMatchCheck = kNumHashBytes + 1;
static const UInt32 kStartMaxLen = 1;
#endif
#endif
#ifdef HASH_ARRAY_2
#ifdef HASH_ARRAY_3
static const UInt32 kHash3Offset = kHash2Size;
#endif
#endif
static const UInt32 kFixHashSize = 0
#ifdef HASH_ARRAY_2
+ kHash2Size
#ifdef HASH_ARRAY_3
+ kHash3Size
#endif
#endif
;
CMatchFinder::CMatchFinder():
_hash(0)
{
}
void CMatchFinder::FreeThisClassMemory()
{
BigFree(_hash);
_hash = 0;
}
void CMatchFinder::FreeMemory()
{
FreeThisClassMemory();
CLZInWindow::Free();
}
CMatchFinder::~CMatchFinder()
{
FreeMemory();
}
STDMETHODIMP CMatchFinder::Create(UInt32 historySize, UInt32 keepAddBufferBefore,
UInt32 matchMaxLen, UInt32 keepAddBufferAfter)
{
if (historySize > kMaxValForNormalize - 256)
{
FreeMemory();
return E_INVALIDARG;
}
_cutValue =
#ifdef _HASH_CHAIN
8 + (matchMaxLen >> 2);
#else
16 + (matchMaxLen >> 1);
#endif
UInt32 sizeReserv = (historySize + keepAddBufferBefore +
matchMaxLen + keepAddBufferAfter) / 2 + 256;
if (CLZInWindow::Create(historySize + keepAddBufferBefore,
matchMaxLen + keepAddBufferAfter, sizeReserv))
{
_matchMaxLen = matchMaxLen;
UInt32 newCyclicBufferSize = historySize + 1;
if (_hash != 0 && newCyclicBufferSize == _cyclicBufferSize)
return S_OK;
FreeThisClassMemory();
_cyclicBufferSize = newCyclicBufferSize; // don't change it
UInt32 hs = kHashSize;
#ifdef HASH_ARRAY_2
hs = historySize - 1;
hs |= (hs >> 1);
hs |= (hs >> 2);
hs |= (hs >> 4);
hs |= (hs >> 8);
hs >>= 1;
hs |= 0xFFFF;
if (hs > (1 << 24))
{
#ifdef HASH_ARRAY_3
hs >>= 1;
#else
hs = (1 << 24) - 1;
#endif
}
_hashMask = hs;
hs++;
#endif
_hashSizeSum = hs + kFixHashSize;
UInt32 numItems = _hashSizeSum + _cyclicBufferSize
#ifndef _HASH_CHAIN
* 2
#endif
;
size_t sizeInBytes = (size_t)numItems * sizeof(CIndex);
if (sizeInBytes / sizeof(CIndex) != numItems)
return E_OUTOFMEMORY;
_hash = (CIndex *)BigAlloc(sizeInBytes);
_son = _hash + _hashSizeSum;
if (_hash != 0)
return S_OK;
}
FreeMemory();
return E_OUTOFMEMORY;
}
static const UInt32 kEmptyHashValue = 0;
STDMETHODIMP CMatchFinder::SetStream(ISequentialInStream *stream)
{
CLZInWindow::SetStream(stream);
return S_OK;
}
STDMETHODIMP CMatchFinder::Init()
{
RINOK(CLZInWindow::Init());
for(UInt32 i = 0; i < _hashSizeSum; i++)
_hash[i] = kEmptyHashValue;
_cyclicBufferPos = 0;
ReduceOffsets(-1);
return S_OK;
}
STDMETHODIMP_(void) CMatchFinder::ReleaseStream()
{
// ReleaseStream();
}
#ifdef HASH_ARRAY_2
#ifdef HASH_ARRAY_3
#define HASH_CALC { \
UInt32 temp = CCRC::Table[cur[0]] ^ cur[1]; \
hash2Value = temp & (kHash2Size - 1); \
hash3Value = (temp ^ (UInt32(cur[2]) << 8)) & (kHash3Size - 1); \
hashValue = (temp ^ (UInt32(cur[2]) << 8) ^ (CCRC::Table[cur[3]] << 5)) & _hashMask; }
#else // no HASH_ARRAY_3
#define HASH_CALC { \
UInt32 temp = CCRC::Table[cur[0]] ^ cur[1]; \
hash2Value = temp & (kHash2Size - 1); \
hashValue = (temp ^ (UInt32(cur[2]) << 8)) & _hashMask; }
#endif // HASH_ARRAY_3
#else // no HASH_ARRAY_2
#ifdef HASH_ZIP
inline UInt32 Hash(const Byte *pointer)
{
return ((UInt32(pointer[0]) << 8) ^ CCRC::Table[pointer[1]] ^ pointer[2]) & (kHashSize - 1);
}
#else // no HASH_ZIP
inline UInt32 Hash(const Byte *pointer)
{
return pointer[0] ^ (UInt32(pointer[1]) << 8);
}
#endif // HASH_ZIP
#endif // HASH_ARRAY_2
STDMETHODIMP CMatchFinder::GetMatches(UInt32 *distances)
{
UInt32 lenLimit;
if (_pos + _matchMaxLen <= _streamPos)
lenLimit = _matchMaxLen;
else
{
lenLimit = _streamPos - _pos;
if(lenLimit < kMinMatchCheck)
{
distances[0] = 0;
return MovePos();
}
}
int offset = 1;
UInt32 matchMinPos = (_pos > _cyclicBufferSize) ? (_pos - _cyclicBufferSize) : 0;
const Byte *cur = _buffer + _pos;
UInt32 maxLen = kStartMaxLen; // to avoid items for len < hashSize;
#ifdef HASH_ARRAY_2
UInt32 hash2Value;
#ifdef HASH_ARRAY_3
UInt32 hash3Value;
#endif
UInt32 hashValue;
HASH_CALC;
#else
UInt32 hashValue = Hash(cur);
#endif
UInt32 curMatch = _hash[kFixHashSize + hashValue];
#ifdef HASH_ARRAY_2
UInt32 curMatch2 = _hash[hash2Value];
#ifdef HASH_ARRAY_3
UInt32 curMatch3 = _hash[kHash3Offset + hash3Value];
#endif
_hash[hash2Value] = _pos;
if(curMatch2 > matchMinPos)
if (_buffer[curMatch2] == cur[0])
{
distances[offset++] = maxLen = 2;
distances[offset++] = _pos - curMatch2 - 1;
}
#ifdef HASH_ARRAY_3
_hash[kHash3Offset + hash3Value] = _pos;
if(curMatch3 > matchMinPos)
if (_buffer[curMatch3] == cur[0])
{
if (curMatch3 == curMatch2)
offset -= 2;
distances[offset++] = maxLen = 3;
distances[offset++] = _pos - curMatch3 - 1;
curMatch2 = curMatch3;
}
#endif
if (offset != 1 && curMatch2 == curMatch)
{
offset -= 2;
maxLen = kStartMaxLen;
}
#endif
_hash[kFixHashSize + hashValue] = _pos;
CIndex *son = _son;
#ifdef _HASH_CHAIN
son[_cyclicBufferPos] = curMatch;
#else
CIndex *ptr0 = son + (_cyclicBufferPos << 1) + 1;
CIndex *ptr1 = son + (_cyclicBufferPos << 1);
UInt32 len0, len1;
len0 = len1 = kNumHashDirectBytes;
#endif
#if kNumHashDirectBytes != 0
if(curMatch > matchMinPos)
{
if (_buffer[curMatch + kNumHashDirectBytes] != cur[kNumHashDirectBytes])
{
distances[offset++] = maxLen = kNumHashDirectBytes;
distances[offset++] = _pos - curMatch - 1;
}
}
#endif
UInt32 count = _cutValue;
while(true)
{
if(curMatch <= matchMinPos || count-- == 0)
{
#ifndef _HASH_CHAIN
*ptr0 = *ptr1 = kEmptyHashValue;
#endif
break;
}
UInt32 delta = _pos - curMatch;
UInt32 cyclicPos = (delta <= _cyclicBufferPos) ?
(_cyclicBufferPos - delta):
(_cyclicBufferPos - delta + _cyclicBufferSize);
CIndex *pair = son +
#ifdef _HASH_CHAIN
cyclicPos;
#else
(cyclicPos << 1);
#endif
// _mm_prefetch((const char *)pair, _MM_HINT_T0);
const Byte *pb = _buffer + curMatch;
UInt32 len =
#ifdef _HASH_CHAIN
kNumHashDirectBytes;
if (pb[maxLen] == cur[maxLen])
#else
MyMin(len0, len1);
#endif
if (pb[len] == cur[len])
{
while(++len != lenLimit)
if (pb[len] != cur[len])
break;
if (maxLen < len)
{
distances[offset++] = maxLen = len;
distances[offset++] = delta - 1;
if (len == lenLimit)
{
#ifndef _HASH_CHAIN
*ptr1 = pair[0];
*ptr0 = pair[1];
#endif
break;
}
}
}
#ifdef _HASH_CHAIN
curMatch = *pair;
#else
if (pb[len] < cur[len])
{
*ptr1 = curMatch;
ptr1 = pair + 1;
curMatch = *ptr1;
len1 = len;
}
else
{
*ptr0 = curMatch;
ptr0 = pair;
curMatch = *ptr0;
len0 = len;
}
#endif
}
distances[0] = offset - 1;
if (++_cyclicBufferPos == _cyclicBufferSize)
_cyclicBufferPos = 0;
RINOK(CLZInWindow::MovePos());
if (_pos == kMaxValForNormalize)
Normalize();
return S_OK;
}
STDMETHODIMP CMatchFinder::Skip(UInt32 num)
{
do
{
#ifdef _HASH_CHAIN
if (_streamPos - _pos < kNumHashBytes)
{
RINOK(MovePos());
continue;
}
#else
UInt32 lenLimit;
if (_pos + _matchMaxLen <= _streamPos)
lenLimit = _matchMaxLen;
else
{
lenLimit = _streamPos - _pos;
if(lenLimit < kMinMatchCheck)
{
RINOK(MovePos());
continue;
}
}
UInt32 matchMinPos = (_pos > _cyclicBufferSize) ? (_pos - _cyclicBufferSize) : 0;
#endif
const Byte *cur = _buffer + _pos;
#ifdef HASH_ARRAY_2
UInt32 hash2Value;
#ifdef HASH_ARRAY_3
UInt32 hash3Value;
UInt32 hashValue;
HASH_CALC;
_hash[kHash3Offset + hash3Value] = _pos;
#else
UInt32 hashValue;
HASH_CALC;
#endif
_hash[hash2Value] = _pos;
#else
UInt32 hashValue = Hash(cur);
#endif
UInt32 curMatch = _hash[kFixHashSize + hashValue];
_hash[kFixHashSize + hashValue] = _pos;
#ifdef _HASH_CHAIN
_son[_cyclicBufferPos] = curMatch;
#else
CIndex *son = _son;
CIndex *ptr0 = son + (_cyclicBufferPos << 1) + 1;
CIndex *ptr1 = son + (_cyclicBufferPos << 1);
UInt32 len0, len1;
len0 = len1 = kNumHashDirectBytes;
UInt32 count = _cutValue;
while(true)
{
if(curMatch <= matchMinPos || count-- == 0)
{
*ptr0 = *ptr1 = kEmptyHashValue;
break;
}
UInt32 delta = _pos - curMatch;
UInt32 cyclicPos = (delta <= _cyclicBufferPos) ?
(_cyclicBufferPos - delta):
(_cyclicBufferPos - delta + _cyclicBufferSize);
CIndex *pair = son + (cyclicPos << 1);
// _mm_prefetch((const char *)pair, _MM_HINT_T0);
const Byte *pb = _buffer + curMatch;
UInt32 len = MyMin(len0, len1);
if (pb[len] == cur[len])
{
while(++len != lenLimit)
if (pb[len] != cur[len])
break;
if (len == lenLimit)
{
*ptr1 = pair[0];
*ptr0 = pair[1];
break;
}
}
if (pb[len] < cur[len])
{
*ptr1 = curMatch;
ptr1 = pair + 1;
curMatch = *ptr1;
len1 = len;
}
else
{
*ptr0 = curMatch;
ptr0 = pair;
curMatch = *ptr0;
len0 = len;
}
}
#endif
if (++_cyclicBufferPos == _cyclicBufferSize)
_cyclicBufferPos = 0;
RINOK(CLZInWindow::MovePos());
if (_pos == kMaxValForNormalize)
Normalize();
}
while(--num != 0);
return S_OK;
}
void CMatchFinder::Normalize()
{
UInt32 subValue = _pos - _cyclicBufferSize;
CIndex *items = _hash;
UInt32 numItems = (_hashSizeSum + _cyclicBufferSize
#ifndef _HASH_CHAIN
* 2
#endif
);
for (UInt32 i = 0; i < numItems; i++)
{
UInt32 value = items[i];
if (value <= subValue)
value = kEmptyHashValue;
else
value -= subValue;
items[i] = value;
}
ReduceOffsets(subValue);
}
HRESULT CMatchFinder::MovePos()
{
if (++_cyclicBufferPos == _cyclicBufferSize)
_cyclicBufferPos = 0;
RINOK(CLZInWindow::MovePos());
if (_pos == kMaxValForNormalize)
Normalize();
return S_OK;
}
STDMETHODIMP_(Byte) CMatchFinder::GetIndexByte(Int32 index)
{ return CLZInWindow::GetIndexByte(index); }
STDMETHODIMP_(UInt32) CMatchFinder::GetMatchLen(Int32 index,
UInt32 back, UInt32 limit)
{ return CLZInWindow::GetMatchLen(index, back, limit); }
STDMETHODIMP_(UInt32) CMatchFinder::GetNumAvailableBytes()
{ return CLZInWindow::GetNumAvailableBytes(); }
STDMETHODIMP_(const Byte *) CMatchFinder::GetPointerToCurrentPos()
{ return CLZInWindow::GetPointerToCurrentPos(); }
STDMETHODIMP_(Int32) CMatchFinder::NeedChangeBufferPos(UInt32 numCheckBytes)
{ return CLZInWindow::NeedMove(numCheckBytes) ? 1: 0; }
STDMETHODIMP_(void) CMatchFinder::ChangeBufferPos()
{ CLZInWindow::MoveBlock();}
#undef HASH_CALC
#undef kNumHashDirectBytes
}

View File

@@ -1,13 +0,0 @@
// HC2.h
#ifndef __HC2_H
#define __HC2_H
#define BT_NAMESPACE NHC2
#include "HCMain.h"
#undef BT_NAMESPACE
#endif

View File

@@ -1,16 +0,0 @@
// HC3.h
#ifndef __HC3_H
#define __HC3_H
#define BT_NAMESPACE NHC3
#define HASH_ARRAY_2
#include "HCMain.h"
#undef HASH_ARRAY_2
#undef BT_NAMESPACE
#endif

View File

@@ -1,19 +0,0 @@
// HC4.h
#ifndef __HC4_H
#define __HC4_H
#define BT_NAMESPACE NHC4
#define HASH_ARRAY_2
#define HASH_ARRAY_3
#include "HCMain.h"
#undef HASH_ARRAY_2
#undef HASH_ARRAY_3
#undef BT_NAMESPACE
#endif

View File

@@ -1,6 +0,0 @@
// HCMain.h
#define _HASH_CHAIN
#include "../BinTree/BinTreeMain.h"
#undef _HASH_CHAIN

View File

@@ -1,32 +0,0 @@
// MatchFinders/IMatchFinder.h
#ifndef __IMATCHFINDER_H
#define __IMATCHFINDER_H
struct IInWindowStream: public IUnknown
{
STDMETHOD(SetStream)(ISequentialInStream *inStream) PURE;
STDMETHOD_(void, ReleaseStream)() PURE;
STDMETHOD(Init)() PURE;
STDMETHOD_(Byte, GetIndexByte)(Int32 index) PURE;
STDMETHOD_(UInt32, GetMatchLen)(Int32 index, UInt32 distance, UInt32 limit) PURE;
STDMETHOD_(UInt32, GetNumAvailableBytes)() PURE;
STDMETHOD_(const Byte *, GetPointerToCurrentPos)() PURE;
STDMETHOD_(Int32, NeedChangeBufferPos)(UInt32 numCheckBytes) PURE;
STDMETHOD_(void, ChangeBufferPos)() PURE;
};
struct IMatchFinder: public IInWindowStream
{
STDMETHOD(Create)(UInt32 historySize, UInt32 keepAddBufferBefore,
UInt32 matchMaxLen, UInt32 keepAddBufferAfter) PURE;
STDMETHOD(GetMatches)(UInt32 *distances) PURE;
STDMETHOD(Skip)(UInt32 num) PURE;
};
struct IMatchFinderSetNumPasses
{
virtual void SetNumPasses(UInt32 numPasses) PURE;
};
#endif

View File

@@ -1,105 +0,0 @@
// LZInWindow.cpp
#include "StdAfx.h"
#include "LZInWindow.h"
#include "../../../Common/MyCom.h"
#include "../../../Common/Alloc.h"
void CLZInWindow::Free()
{
::BigFree(_bufferBase);
_bufferBase = 0;
}
bool CLZInWindow::Create(UInt32 keepSizeBefore, UInt32 keepSizeAfter, UInt32 keepSizeReserv)
{
_keepSizeBefore = keepSizeBefore;
_keepSizeAfter = keepSizeAfter;
UInt32 blockSize = keepSizeBefore + keepSizeAfter + keepSizeReserv;
if (_bufferBase == 0 || _blockSize != blockSize)
{
Free();
_blockSize = blockSize;
if (_blockSize != 0)
_bufferBase = (Byte *)::BigAlloc(_blockSize);
}
_pointerToLastSafePosition = _bufferBase + _blockSize - keepSizeAfter;
if (_blockSize == 0)
return true;
return (_bufferBase != 0);
}
void CLZInWindow::SetStream(ISequentialInStream *stream)
{
_stream = stream;
}
HRESULT CLZInWindow::Init()
{
_buffer = _bufferBase;
_pos = 0;
_streamPos = 0;
_streamEndWasReached = false;
return ReadBlock();
}
/*
void CLZInWindow::ReleaseStream()
{
_stream.Release();
}
*/
///////////////////////////////////////////
// ReadBlock
// In State:
// (_buffer + _streamPos) <= (_bufferBase + _blockSize)
// Out State:
// _posLimit <= _blockSize - _keepSizeAfter;
// if(_streamEndWasReached == false):
// _streamPos >= _pos + _keepSizeAfter
// _posLimit = _streamPos - _keepSizeAfter;
// else
//
HRESULT CLZInWindow::ReadBlock()
{
if(_streamEndWasReached)
return S_OK;
while(true)
{
UInt32 size = (UInt32)(_bufferBase - _buffer) + _blockSize - _streamPos;
if(size == 0)
return S_OK;
UInt32 numReadBytes;
RINOK(_stream->Read(_buffer + _streamPos, size, &numReadBytes));
if(numReadBytes == 0)
{
_posLimit = _streamPos;
const Byte *pointerToPostion = _buffer + _posLimit;
if(pointerToPostion > _pointerToLastSafePosition)
_posLimit = (UInt32)(_pointerToLastSafePosition - _buffer);
_streamEndWasReached = true;
return S_OK;
}
_streamPos += numReadBytes;
if(_streamPos >= _pos + _keepSizeAfter)
{
_posLimit = _streamPos - _keepSizeAfter;
return S_OK;
}
}
}
void CLZInWindow::MoveBlock()
{
UInt32 offset = (UInt32)(_buffer - _bufferBase) + _pos - _keepSizeBefore;
// we need one additional byte, since MovePos moves on 1 byte.
if (offset > 0)
offset--;
UInt32 numBytes = (UInt32)(_buffer - _bufferBase) + _streamPos - offset;
memmove(_bufferBase, _bufferBase + offset, numBytes);
_buffer -= offset;
}

View File

@@ -1,87 +0,0 @@
// LZInWindow.h
#ifndef __LZ_IN_WINDOW_H
#define __LZ_IN_WINDOW_H
#include "../../IStream.h"
class CLZInWindow
{
Byte *_bufferBase; // pointer to buffer with data
ISequentialInStream *_stream;
UInt32 _posLimit; // offset (from _buffer) when new block reading must be done
bool _streamEndWasReached; // if (true) then _streamPos shows real end of stream
const Byte *_pointerToLastSafePosition;
protected:
Byte *_buffer; // Pointer to virtual Buffer begin
UInt32 _blockSize; // Size of Allocated memory block
UInt32 _pos; // offset (from _buffer) of curent byte
UInt32 _keepSizeBefore; // how many BYTEs must be kept in buffer before _pos
UInt32 _keepSizeAfter; // how many BYTEs must be kept buffer after _pos
UInt32 _streamPos; // offset (from _buffer) of first not read byte from Stream
void MoveBlock();
HRESULT ReadBlock();
void Free();
public:
CLZInWindow(): _bufferBase(0) {}
virtual ~CLZInWindow() { Free(); }
// keepSizeBefore + keepSizeAfter + keepSizeReserv < 4G)
bool Create(UInt32 keepSizeBefore, UInt32 keepSizeAfter, UInt32 keepSizeReserv = (1<<17));
void SetStream(ISequentialInStream *stream);
HRESULT Init();
// void ReleaseStream();
Byte *GetBuffer() const { return _buffer; }
const Byte *GetPointerToCurrentPos() const { return _buffer + _pos; }
HRESULT MovePos()
{
_pos++;
if (_pos > _posLimit)
{
const Byte *pointerToPostion = _buffer + _pos;
if(pointerToPostion > _pointerToLastSafePosition)
MoveBlock();
return ReadBlock();
}
else
return S_OK;
}
Byte GetIndexByte(Int32 index) const { return _buffer[(size_t)_pos + index]; }
// index + limit have not to exceed _keepSizeAfter;
// -2G <= index < 2G
UInt32 GetMatchLen(Int32 index, UInt32 distance, UInt32 limit) const
{
if(_streamEndWasReached)
if ((_pos + index) + limit > _streamPos)
limit = _streamPos - (_pos + index);
distance++;
const Byte *pby = _buffer + (size_t)_pos + index;
UInt32 i;
for(i = 0; i < limit && pby[i] == pby[(size_t)i - distance]; i++);
return i;
}
UInt32 GetNumAvailableBytes() const { return _streamPos - _pos; }
void ReduceOffsets(Int32 subValue)
{
_buffer += subValue;
_posLimit -= subValue;
_pos -= subValue;
_streamPos -= subValue;
}
bool NeedMove(UInt32 numCheckBytes)
{
UInt32 reserv = _pointerToLastSafePosition - (_buffer + _pos);
return (reserv <= numCheckBytes);
}
};
#endif

View File

@@ -1,295 +0,0 @@
// MT.cpp
#include "StdAfx.h"
#include "../../../../Common/Alloc.h"
#include "MT.h"
static const UInt32 kBlockSize = (1 << 14);
static DWORD WINAPI MFThread(void *threadCoderInfo)
{
return ((CMatchFinderMT *)threadCoderInfo)->ThreadFunc();
}
CMatchFinderMT::CMatchFinderMT():
m_Buffer(0),
m_NeedStart(true)
{
m_BlockIndex = kNumMTBlocks - 1;
m_CS[m_BlockIndex].Enter();
if (!m_Thread.Create(MFThread, this))
throw 271826;
}
CMatchFinderMT::~CMatchFinderMT()
{
m_Exit = true;
m_CS[m_BlockIndex].Leave();
m_CanChangeBufferPos.Set();
if (m_NeedStart)
m_MtCanStart.Set();
m_Thread.Wait();
FreeMem();
}
void CMatchFinderMT::FreeMem()
{
::MyFree(m_Buffer);
m_Buffer = 0;
}
STDMETHODIMP CMatchFinderMT::Create(UInt32 sizeHistory, UInt32 keepAddBufferBefore,
UInt32 matchMaxLen, UInt32 keepAddBufferAfter)
{
FreeMem();
m_MatchMaxLen = matchMaxLen;
if (kBlockSize <= matchMaxLen * 4)
return E_INVALIDARG;
UInt32 bufferSize = kBlockSize * kNumMTBlocks;
m_Buffer = (UInt32 *)::MyAlloc(bufferSize * sizeof(UInt32));
if (m_Buffer == 0)
return E_OUTOFMEMORY;
keepAddBufferBefore += bufferSize;
keepAddBufferAfter += (kBlockSize + 1);
return m_MatchFinder->Create(sizeHistory, keepAddBufferBefore, matchMaxLen, keepAddBufferAfter);
}
// UInt32 blockSizeMult = 800
HRESULT CMatchFinderMT::SetMatchFinder(IMatchFinder *matchFinder)
{
m_MatchFinder = matchFinder;
return S_OK;
}
STDMETHODIMP CMatchFinderMT::SetStream(ISequentialInStream *s)
{
return m_MatchFinder->SetStream(s);
}
// Call it after ReleaseStream / SetStream
STDMETHODIMP CMatchFinderMT::Init()
{
m_NeedStart = true;
m_Pos = 0;
m_PosLimit = 0;
HRESULT result = m_MatchFinder->Init();
if (result == S_OK)
m_DataCurrentPos = m_MatchFinder->GetPointerToCurrentPos();
m_NumAvailableBytes = m_MatchFinder->GetNumAvailableBytes();
return result;
}
// ReleaseStream is required to finish multithreading
STDMETHODIMP_(void) CMatchFinderMT::ReleaseStream()
{
m_StopWriting = true;
m_CS[m_BlockIndex].Leave();
if (!m_NeedStart)
{
m_CanChangeBufferPos.Set();
m_MtWasStopped.Lock();
m_NeedStart = true;
}
m_MatchFinder->ReleaseStream();
m_BlockIndex = kNumMTBlocks - 1;
m_CS[m_BlockIndex].Enter();
}
STDMETHODIMP_(Byte) CMatchFinderMT::GetIndexByte(Int32 index)
{
return m_DataCurrentPos[index];
}
STDMETHODIMP_(UInt32) CMatchFinderMT::GetMatchLen(Int32 index, UInt32 distance, UInt32 limit)
{
if ((Int32)(index + limit) > m_NumAvailableBytes)
limit = m_NumAvailableBytes - (index);
distance++;
const Byte *pby = m_DataCurrentPos + index;
UInt32 i;
for(i = 0; i < limit && pby[i] == pby[(size_t)i - distance]; i++);
return i;
}
STDMETHODIMP_(const Byte *) CMatchFinderMT::GetPointerToCurrentPos()
{
return m_DataCurrentPos;
}
STDMETHODIMP_(UInt32) CMatchFinderMT::GetNumAvailableBytes()
{
return m_NumAvailableBytes;
}
void CMatchFinderMT::GetNextBlock()
{
if (m_NeedStart)
{
m_NeedStart = false;
for (UInt32 i = 0; i < kNumMTBlocks; i++)
m_StopReading[i] = false;
m_StopWriting = false;
m_Exit = false;
m_MtWasStarted.Reset();
m_MtWasStopped.Reset();
m_CanChangeBufferPos.Reset();
m_BufferPosWasChanged.Reset();
m_MtCanStart.Set();
m_MtWasStarted.Lock();
m_Result = S_OK;
}
while (true)
{
UInt32 nextIndex = (m_BlockIndex == kNumMTBlocks - 1) ? 0 : m_BlockIndex + 1;
m_CS[nextIndex].Enter();
if (!m_StopReading[nextIndex])
{
m_CS[m_BlockIndex].Leave();
m_BlockIndex = nextIndex;
break;
}
m_StopReading[nextIndex] = false;
m_CS[nextIndex].Leave();
m_CanChangeBufferPos.Set();
m_BufferPosWasChanged.Lock();
m_CS[nextIndex].Enter();
m_CS[m_BlockIndex].Leave();
m_BlockIndex = nextIndex;
}
m_Pos = m_BlockIndex * kBlockSize;
m_PosLimit = m_Buffer[m_Pos++];
m_NumAvailableBytes = m_Buffer[m_Pos++];
m_Result = m_Results[m_BlockIndex];
}
STDMETHODIMP CMatchFinderMT::GetMatches(UInt32 *distances)
{
if (m_Pos == m_PosLimit)
GetNextBlock();
if (m_Result != S_OK)
return m_Result;
m_NumAvailableBytes--;
m_DataCurrentPos++;
const UInt32 *buffer = m_Buffer + m_Pos;
UInt32 len = *buffer++;
*distances++ = len;
m_Pos += 1 + len;
for (UInt32 i = 0; i != len; i += 2)
{
distances[i] = buffer[i];
distances[i + 1] = buffer[i + 1];
}
return S_OK;
}
STDMETHODIMP CMatchFinderMT::Skip(UInt32 num)
{
do
{
if (m_Pos == m_PosLimit)
GetNextBlock();
if (m_Result != S_OK)
return m_Result;
m_NumAvailableBytes--;
m_DataCurrentPos++;
UInt32 len = m_Buffer[m_Pos++];
m_Pos += len;
}
while(--num != 0);
return S_OK;
}
STDMETHODIMP_(Int32) CMatchFinderMT::NeedChangeBufferPos(UInt32 numCheckBytes)
{
throw 1;
}
STDMETHODIMP_(void) CMatchFinderMT::ChangeBufferPos()
{
throw 1;
}
DWORD CMatchFinderMT::ThreadFunc()
{
while(true)
{
bool needStartEvent = true;
m_MtCanStart.Lock();
HRESULT result = S_OK;
UInt32 blockIndex = 0;
while (true)
{
m_CS[blockIndex].Enter();
if (needStartEvent)
{
m_MtWasStarted.Set();
needStartEvent = false;
}
else
m_CS[(blockIndex == 0) ? kNumMTBlocks - 1 : blockIndex - 1].Leave();
if (m_Exit)
return 0;
if (m_StopWriting)
{
m_MtWasStopped.Set();
m_CS[blockIndex].Leave();
break;
}
if (result == S_OK)
{
IMatchFinder *mf = m_MatchFinder;
if (mf->NeedChangeBufferPos(kBlockSize) != 0)
{
// m_AskChangeBufferPos.Set();
m_StopReading[blockIndex] = true;
m_CS[blockIndex].Leave();
m_CanChangeBufferPos.Lock();
m_CS[blockIndex].Enter();
const Byte *bufferPosBefore = mf->GetPointerToCurrentPos();
mf->ChangeBufferPos();
m_DataCurrentPos += mf->GetPointerToCurrentPos() - bufferPosBefore;
m_BufferPosWasChanged.Set();
}
else
{
UInt32 curPos = blockIndex * kBlockSize;
UInt32 limit = curPos + kBlockSize - m_MatchMaxLen - m_MatchMaxLen - 1;
UInt32 *buffer = m_Buffer;
m_Results[blockIndex] = S_OK;
curPos++;
UInt32 numAvailableBytes = mf->GetNumAvailableBytes();
buffer[curPos++] = numAvailableBytes;
while (numAvailableBytes-- != 0 && curPos < limit)
{
result = mf->GetMatches(buffer + curPos);
if (result != S_OK)
{
m_Results[blockIndex] = result;
break;
}
curPos += buffer[curPos] + 1;
}
buffer[blockIndex * kBlockSize] = curPos;
}
}
else
{
UInt32 curPos = blockIndex * kBlockSize;
m_Buffer[curPos] = curPos + 2; // size of buffer
m_Buffer[curPos + 1] = 0; // NumAvailableBytes
m_Results[blockIndex] = result; // error
}
if (++blockIndex == kNumMTBlocks)
blockIndex = 0;
}
}
}

View File

@@ -1,79 +0,0 @@
// LZ/MT.h
#ifndef __LZ_MT_H
#define __LZ_MT_H
#include "../../../../Common/MyCom.h"
#include "../../../../OS/Thread.h"
#include "../../../../OS/Synchronization.h"
#include "../../../ICoder.h"
#include "../IMatchFinder.h"
const UInt32 kNumMTBlocks = (1 << 6);
class CMatchFinderMT:
public IMatchFinder,
public CMyUnknownImp
{
MY_UNKNOWN_IMP
STDMETHOD(SetStream)(ISequentialInStream *inStream);
STDMETHOD_(void, ReleaseStream)();
STDMETHOD(Init)();
STDMETHOD_(Byte, GetIndexByte)(Int32 index);
STDMETHOD_(UInt32, GetMatchLen)(Int32 index, UInt32 distance, UInt32 limit);
STDMETHOD_(UInt32, GetNumAvailableBytes)();
STDMETHOD_(const Byte *, GetPointerToCurrentPos)();
STDMETHOD(Create)(UInt32 sizeHistory, UInt32 keepAddBufferBefore,
UInt32 matchMaxLen, UInt32 keepAddBufferAfter);
STDMETHOD(GetMatches)(UInt32 *distances);
STDMETHOD(Skip)(UInt32 num);
STDMETHOD_(Int32, NeedChangeBufferPos)(UInt32 numCheckBytes);
STDMETHOD_(void, ChangeBufferPos)();
UInt32 m_Pos;
UInt32 m_PosLimit;
UInt32 m_MatchMaxLen;
UInt32 *m_Buffer;
bool m_NeedStart;
UInt32 m_BlockIndex;
HRESULT m_Result;
UInt32 m_NumAvailableBytes;
const Byte *m_DataCurrentPos;
// Common variables
CMyComPtr<IMatchFinder> m_MatchFinder;
NWindows::CThread m_Thread;
NWindows::NSynchronization::CAutoResetEvent m_MtCanStart;
NWindows::NSynchronization::CAutoResetEvent m_MtWasStarted;
NWindows::NSynchronization::CAutoResetEvent m_MtWasStopped;
NWindows::NSynchronization::CAutoResetEvent m_CanChangeBufferPos;
NWindows::NSynchronization::CAutoResetEvent m_BufferPosWasChanged;
NWindows::NSynchronization::CCriticalSection m_CS[kNumMTBlocks];
HRESULT m_Results[kNumMTBlocks];
bool m_StopReading[kNumMTBlocks];
bool m_Exit;
bool m_StopWriting;
////////////////////////////
void FreeMem();
void GetNextBlock();
public:
DWORD ThreadFunc();
CMatchFinderMT();
~CMatchFinderMT();
HRESULT SetMatchFinder(IMatchFinder *matchFinder);
};
#endif

View File

@@ -1,8 +0,0 @@
// StdAfx.h
#ifndef __STDAFX_H
#define __STDAFX_H
#include "../../../../Common/MyWindows.h"
#endif

View File

@@ -1,6 +0,0 @@
// StdAfx.h
#ifndef __STDAFX_H
#define __STDAFX_H
#endif

View File

@@ -1,82 +0,0 @@
// LZMA.h
#ifndef __LZMA_H
#define __LZMA_H
namespace NCompress {
namespace NLZMA {
const UInt32 kNumRepDistances = 4;
const int kNumStates = 12;
const Byte kLiteralNextStates[kNumStates] = {0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 4, 5};
const Byte kMatchNextStates[kNumStates] = {7, 7, 7, 7, 7, 7, 7, 10, 10, 10, 10, 10};
const Byte kRepNextStates[kNumStates] = {8, 8, 8, 8, 8, 8, 8, 11, 11, 11, 11, 11};
const Byte kShortRepNextStates[kNumStates]= {9, 9, 9, 9, 9, 9, 9, 11, 11, 11, 11, 11};
class CState
{
public:
Byte Index;
void Init() { Index = 0; }
void UpdateChar() { Index = kLiteralNextStates[Index]; }
void UpdateMatch() { Index = kMatchNextStates[Index]; }
void UpdateRep() { Index = kRepNextStates[Index]; }
void UpdateShortRep() { Index = kShortRepNextStates[Index]; }
bool IsCharState() const { return Index < 7; }
};
const int kNumPosSlotBits = 6;
const int kDicLogSizeMin = 0;
const int kDicLogSizeMax = 32;
const int kDistTableSizeMax = kDicLogSizeMax * 2;
const UInt32 kNumLenToPosStates = 4;
inline UInt32 GetLenToPosState(UInt32 len)
{
len -= 2;
if (len < kNumLenToPosStates)
return len;
return kNumLenToPosStates - 1;
}
namespace NLength {
const int kNumPosStatesBitsMax = 4;
const UInt32 kNumPosStatesMax = (1 << kNumPosStatesBitsMax);
const int kNumPosStatesBitsEncodingMax = 4;
const UInt32 kNumPosStatesEncodingMax = (1 << kNumPosStatesBitsEncodingMax);
const int kNumLowBits = 3;
const int kNumMidBits = 3;
const int kNumHighBits = 8;
const UInt32 kNumLowSymbols = 1 << kNumLowBits;
const UInt32 kNumMidSymbols = 1 << kNumMidBits;
const UInt32 kNumSymbolsTotal = kNumLowSymbols + kNumMidSymbols + (1 << kNumHighBits);
}
const UInt32 kMatchMinLen = 2;
const UInt32 kMatchMaxLen = kMatchMinLen + NLength::kNumSymbolsTotal - 1;
const int kNumAlignBits = 4;
const UInt32 kAlignTableSize = 1 << kNumAlignBits;
const UInt32 kAlignMask = (kAlignTableSize - 1);
const UInt32 kStartPosModelIndex = 4;
const UInt32 kEndPosModelIndex = 14;
const UInt32 kNumPosModels = kEndPosModelIndex - kStartPosModelIndex;
const UInt32 kNumFullDistances = 1 << (kEndPosModelIndex / 2);
const int kNumLitPosStatesBitsEncodingMax = 4;
const int kNumLitContextBitsMax = 8;
const int kNumMoveBits = 5;
}}
#endif

View File

@@ -1,337 +0,0 @@
// LZMADecoder.cpp
#include "StdAfx.h"
#include "LZMADecoder.h"
#include "../../../Common/Defs.h"
namespace NCompress {
namespace NLZMA {
const int kLenIdFinished = -1;
const int kLenIdNeedInit = -2;
void CDecoder::Init()
{
{
for(int i = 0; i < kNumStates; i++)
{
for (UInt32 j = 0; j <= _posStateMask; j++)
{
_isMatch[i][j].Init();
_isRep0Long[i][j].Init();
}
_isRep[i].Init();
_isRepG0[i].Init();
_isRepG1[i].Init();
_isRepG2[i].Init();
}
}
{
for (UInt32 i = 0; i < kNumLenToPosStates; i++)
_posSlotDecoder[i].Init();
}
{
for(UInt32 i = 0; i < kNumFullDistances - kEndPosModelIndex; i++)
_posDecoders[i].Init();
}
_posAlignDecoder.Init();
_lenDecoder.Init(_posStateMask + 1);
_repMatchLenDecoder.Init(_posStateMask + 1);
_literalDecoder.Init();
_state.Init();
_reps[0] = _reps[1] = _reps[2] = _reps[3] = 0;
}
HRESULT CDecoder::CodeSpec(UInt32 curSize)
{
if (_outSizeDefined)
{
const UInt64 rem = _outSize - _outWindowStream.GetProcessedSize();
if (curSize > rem)
curSize = (UInt32)rem;
}
if (_remainLen == kLenIdFinished)
return S_OK;
if (_remainLen == kLenIdNeedInit)
{
_rangeDecoder.Init();
Init();
_remainLen = 0;
}
if (curSize == 0)
return S_OK;
UInt32 rep0 = _reps[0];
UInt32 rep1 = _reps[1];
UInt32 rep2 = _reps[2];
UInt32 rep3 = _reps[3];
CState state = _state;
Byte previousByte;
while(_remainLen > 0 && curSize > 0)
{
previousByte = _outWindowStream.GetByte(rep0);
_outWindowStream.PutByte(previousByte);
_remainLen--;
curSize--;
}
UInt64 nowPos64 = _outWindowStream.GetProcessedSize();
if (nowPos64 == 0)
previousByte = 0;
else
previousByte = _outWindowStream.GetByte(0);
while(curSize > 0)
{
{
#ifdef _NO_EXCEPTIONS
if (_rangeDecoder.Stream.ErrorCode != S_OK)
return _rangeDecoder.Stream.ErrorCode;
#endif
if (_rangeDecoder.Stream.WasFinished())
return S_FALSE;
UInt32 posState = UInt32(nowPos64) & _posStateMask;
if (_isMatch[state.Index][posState].Decode(&_rangeDecoder) == 0)
{
if(!state.IsCharState())
previousByte = _literalDecoder.DecodeWithMatchByte(&_rangeDecoder,
(UInt32)nowPos64, previousByte, _outWindowStream.GetByte(rep0));
else
previousByte = _literalDecoder.DecodeNormal(&_rangeDecoder,
(UInt32)nowPos64, previousByte);
_outWindowStream.PutByte(previousByte);
state.UpdateChar();
curSize--;
nowPos64++;
}
else
{
UInt32 len;
if(_isRep[state.Index].Decode(&_rangeDecoder) == 1)
{
len = 0;
if(_isRepG0[state.Index].Decode(&_rangeDecoder) == 0)
{
if(_isRep0Long[state.Index][posState].Decode(&_rangeDecoder) == 0)
{
state.UpdateShortRep();
len = 1;
}
}
else
{
UInt32 distance;
if(_isRepG1[state.Index].Decode(&_rangeDecoder) == 0)
distance = rep1;
else
{
if (_isRepG2[state.Index].Decode(&_rangeDecoder) == 0)
distance = rep2;
else
{
distance = rep3;
rep3 = rep2;
}
rep2 = rep1;
}
rep1 = rep0;
rep0 = distance;
}
if (len == 0)
{
len = _repMatchLenDecoder.Decode(&_rangeDecoder, posState) + kMatchMinLen;
state.UpdateRep();
}
}
else
{
rep3 = rep2;
rep2 = rep1;
rep1 = rep0;
len = kMatchMinLen + _lenDecoder.Decode(&_rangeDecoder, posState);
state.UpdateMatch();
UInt32 posSlot = _posSlotDecoder[GetLenToPosState(len)].Decode(&_rangeDecoder);
if (posSlot >= kStartPosModelIndex)
{
UInt32 numDirectBits = (posSlot >> 1) - 1;
rep0 = ((2 | (posSlot & 1)) << numDirectBits);
if (posSlot < kEndPosModelIndex)
rep0 += NRangeCoder::ReverseBitTreeDecode(_posDecoders +
rep0 - posSlot - 1, &_rangeDecoder, numDirectBits);
else
{
rep0 += (_rangeDecoder.DecodeDirectBits(
numDirectBits - kNumAlignBits) << kNumAlignBits);
rep0 += _posAlignDecoder.ReverseDecode(&_rangeDecoder);
if (rep0 == 0xFFFFFFFF)
{
_remainLen = kLenIdFinished;
return S_OK;
}
}
}
else
rep0 = posSlot;
}
UInt32 locLen = len;
if (len > curSize)
locLen = (UInt32)curSize;
if (!_outWindowStream.CopyBlock(rep0, locLen))
return S_FALSE;
previousByte = _outWindowStream.GetByte(0);
curSize -= locLen;
nowPos64 += locLen;
len -= locLen;
if (len != 0)
{
_remainLen = (Int32)len;
break;
}
#ifdef _NO_EXCEPTIONS
if (_outWindowStream.ErrorCode != S_OK)
return _outWindowStream.ErrorCode;
#endif
}
}
}
if (_rangeDecoder.Stream.WasFinished())
return S_FALSE;
_reps[0] = rep0;
_reps[1] = rep1;
_reps[2] = rep2;
_reps[3] = rep3;
_state = state;
return S_OK;
}
STDMETHODIMP CDecoder::CodeReal(ISequentialInStream *inStream,
ISequentialOutStream *outStream,
const UInt64 *, const UInt64 *outSize,
ICompressProgressInfo *progress)
{
SetInStream(inStream);
_outWindowStream.SetStream(outStream);
SetOutStreamSize(outSize);
CDecoderFlusher flusher(this);
while (true)
{
UInt32 curSize = 1 << 18;
RINOK(CodeSpec(curSize));
if (_remainLen == kLenIdFinished)
break;
if (progress != NULL)
{
UInt64 inSize = _rangeDecoder.GetProcessedSize();
UInt64 nowPos64 = _outWindowStream.GetProcessedSize();
RINOK(progress->SetRatioInfo(&inSize, &nowPos64));
}
if (_outSizeDefined)
if (_outWindowStream.GetProcessedSize() >= _outSize)
break;
}
flusher.NeedFlush = false;
return Flush();
}
#ifdef _NO_EXCEPTIONS
#define LZMA_TRY_BEGIN
#define LZMA_TRY_END
#else
#define LZMA_TRY_BEGIN try {
#define LZMA_TRY_END } \
catch(const CInBufferException &e) { return e.ErrorCode; } \
catch(const CLZOutWindowException &e) { return e.ErrorCode; } \
catch(...) { return S_FALSE; }
#endif
STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream,
ISequentialOutStream *outStream, const UInt64 *inSize, const UInt64 *outSize,
ICompressProgressInfo *progress)
{
LZMA_TRY_BEGIN
return CodeReal(inStream, outStream, inSize, outSize, progress);
LZMA_TRY_END
}
STDMETHODIMP CDecoder::SetDecoderProperties2(const Byte *properties, UInt32 size)
{
if (size < 5)
return E_INVALIDARG;
int lc = properties[0] % 9;
Byte remainder = (Byte)(properties[0] / 9);
int lp = remainder % 5;
int pb = remainder / 5;
if (pb > NLength::kNumPosStatesBitsMax)
return E_INVALIDARG;
_posStateMask = (1 << pb) - 1;
UInt32 dictionarySize = 0;
for (int i = 0; i < 4; i++)
dictionarySize += ((UInt32)(properties[1 + i])) << (i * 8);
if (!_outWindowStream.Create(dictionarySize))
return E_OUTOFMEMORY;
if (!_literalDecoder.Create(lp, lc))
return E_OUTOFMEMORY;
if (!_rangeDecoder.Create(1 << 20))
return E_OUTOFMEMORY;
return S_OK;
}
STDMETHODIMP CDecoder::GetInStreamProcessedSize(UInt64 *value)
{
*value = _rangeDecoder.GetProcessedSize();
return S_OK;
}
STDMETHODIMP CDecoder::SetInStream(ISequentialInStream *inStream)
{
_rangeDecoder.SetStream(inStream);
return S_OK;
}
STDMETHODIMP CDecoder::ReleaseInStream()
{
_rangeDecoder.ReleaseStream();
return S_OK;
}
STDMETHODIMP CDecoder::SetOutStreamSize(const UInt64 *outSize)
{
if (_outSizeDefined = (outSize != NULL))
_outSize = *outSize;
_remainLen = kLenIdNeedInit;
_outWindowStream.Init();
return S_OK;
}
#ifdef _ST_MODE
STDMETHODIMP CDecoder::Read(void *data, UInt32 size, UInt32 *processedSize)
{
LZMA_TRY_BEGIN
if (processedSize)
*processedSize = 0;
const UInt64 startPos = _outWindowStream.GetProcessedSize();
_outWindowStream.SetMemStream((Byte *)data);
RINOK(CodeSpec(size));
if (processedSize)
*processedSize = (UInt32)(_outWindowStream.GetProcessedSize() - startPos);
return Flush();
LZMA_TRY_END
}
#endif
}}

View File

@@ -1,251 +0,0 @@
// LZMA/Decoder.h
#ifndef __LZMA_DECODER_H
#define __LZMA_DECODER_H
#include "../../../Common/MyCom.h"
#include "../../../Common/Alloc.h"
#include "../../ICoder.h"
#include "../LZ/LZOutWindow.h"
#include "../RangeCoder/RangeCoderBitTree.h"
#include "LZMA.h"
namespace NCompress {
namespace NLZMA {
typedef NRangeCoder::CBitDecoder<kNumMoveBits> CMyBitDecoder;
class CLiteralDecoder2
{
CMyBitDecoder _decoders[0x300];
public:
void Init()
{
for (int i = 0; i < 0x300; i++)
_decoders[i].Init();
}
Byte DecodeNormal(NRangeCoder::CDecoder *rangeDecoder)
{
UInt32 symbol = 1;
RC_INIT_VAR
do
{
// symbol = (symbol << 1) | _decoders[0][symbol].Decode(rangeDecoder);
RC_GETBIT(kNumMoveBits, _decoders[symbol].Prob, symbol)
}
while (symbol < 0x100);
RC_FLUSH_VAR
return (Byte)symbol;
}
Byte DecodeWithMatchByte(NRangeCoder::CDecoder *rangeDecoder, Byte matchByte)
{
UInt32 symbol = 1;
RC_INIT_VAR
do
{
UInt32 matchBit = (matchByte >> 7) & 1;
matchByte <<= 1;
// UInt32 bit = _decoders[1 + matchBit][symbol].Decode(rangeDecoder);
// symbol = (symbol << 1) | bit;
UInt32 bit;
RC_GETBIT2(kNumMoveBits, _decoders[0x100 + (matchBit << 8) + symbol].Prob, symbol,
bit = 0, bit = 1)
if (matchBit != bit)
{
while (symbol < 0x100)
{
// symbol = (symbol << 1) | _decoders[0][symbol].Decode(rangeDecoder);
RC_GETBIT(kNumMoveBits, _decoders[symbol].Prob, symbol)
}
break;
}
}
while (symbol < 0x100);
RC_FLUSH_VAR
return (Byte)symbol;
}
};
class CLiteralDecoder
{
CLiteralDecoder2 *_coders;
int _numPrevBits;
int _numPosBits;
UInt32 _posMask;
public:
CLiteralDecoder(): _coders(0) {}
~CLiteralDecoder() { Free(); }
void Free()
{
MyFree(_coders);
_coders = 0;
}
bool Create(int numPosBits, int numPrevBits)
{
if (_coders == 0 || (numPosBits + numPrevBits) !=
(_numPrevBits + _numPosBits) )
{
Free();
UInt32 numStates = 1 << (numPosBits + numPrevBits);
_coders = (CLiteralDecoder2 *)MyAlloc(numStates * sizeof(CLiteralDecoder2));
}
_numPosBits = numPosBits;
_posMask = (1 << numPosBits) - 1;
_numPrevBits = numPrevBits;
return (_coders != 0);
}
void Init()
{
UInt32 numStates = 1 << (_numPrevBits + _numPosBits);
for (UInt32 i = 0; i < numStates; i++)
_coders[i].Init();
}
UInt32 GetState(UInt32 pos, Byte prevByte) const
{ return ((pos & _posMask) << _numPrevBits) + (prevByte >> (8 - _numPrevBits)); }
Byte DecodeNormal(NRangeCoder::CDecoder *rangeDecoder, UInt32 pos, Byte prevByte)
{ return _coders[GetState(pos, prevByte)].DecodeNormal(rangeDecoder); }
Byte DecodeWithMatchByte(NRangeCoder::CDecoder *rangeDecoder, UInt32 pos, Byte prevByte, Byte matchByte)
{ return _coders[GetState(pos, prevByte)].DecodeWithMatchByte(rangeDecoder, matchByte); }
};
namespace NLength {
class CDecoder
{
CMyBitDecoder _choice;
CMyBitDecoder _choice2;
NRangeCoder::CBitTreeDecoder<kNumMoveBits, kNumLowBits> _lowCoder[kNumPosStatesMax];
NRangeCoder::CBitTreeDecoder<kNumMoveBits, kNumMidBits> _midCoder[kNumPosStatesMax];
NRangeCoder::CBitTreeDecoder<kNumMoveBits, kNumHighBits> _highCoder;
public:
void Init(UInt32 numPosStates)
{
_choice.Init();
_choice2.Init();
for (UInt32 posState = 0; posState < numPosStates; posState++)
{
_lowCoder[posState].Init();
_midCoder[posState].Init();
}
_highCoder.Init();
}
UInt32 Decode(NRangeCoder::CDecoder *rangeDecoder, UInt32 posState)
{
if(_choice.Decode(rangeDecoder) == 0)
return _lowCoder[posState].Decode(rangeDecoder);
if(_choice2.Decode(rangeDecoder) == 0)
return kNumLowSymbols + _midCoder[posState].Decode(rangeDecoder);
return kNumLowSymbols + kNumMidSymbols + _highCoder.Decode(rangeDecoder);
}
};
}
class CDecoder:
public ICompressCoder,
public ICompressSetDecoderProperties2,
public ICompressGetInStreamProcessedSize,
#ifdef _ST_MODE
public ICompressSetInStream,
public ICompressSetOutStreamSize,
public ISequentialInStream,
#endif
public CMyUnknownImp
{
CLZOutWindow _outWindowStream;
NRangeCoder::CDecoder _rangeDecoder;
CMyBitDecoder _isMatch[kNumStates][NLength::kNumPosStatesMax];
CMyBitDecoder _isRep[kNumStates];
CMyBitDecoder _isRepG0[kNumStates];
CMyBitDecoder _isRepG1[kNumStates];
CMyBitDecoder _isRepG2[kNumStates];
CMyBitDecoder _isRep0Long[kNumStates][NLength::kNumPosStatesMax];
NRangeCoder::CBitTreeDecoder<kNumMoveBits, kNumPosSlotBits> _posSlotDecoder[kNumLenToPosStates];
CMyBitDecoder _posDecoders[kNumFullDistances - kEndPosModelIndex];
NRangeCoder::CBitTreeDecoder<kNumMoveBits, kNumAlignBits> _posAlignDecoder;
NLength::CDecoder _lenDecoder;
NLength::CDecoder _repMatchLenDecoder;
CLiteralDecoder _literalDecoder;
UInt32 _posStateMask;
///////////////////
// State
UInt32 _reps[4];
CState _state;
Int32 _remainLen; // -1 means end of stream. // -2 means need Init
UInt64 _outSize;
bool _outSizeDefined;
void Init();
HRESULT CodeSpec(UInt32 size);
public:
#ifdef _ST_MODE
MY_UNKNOWN_IMP5(
ICompressSetDecoderProperties2,
ICompressGetInStreamProcessedSize,
ICompressSetInStream,
ICompressSetOutStreamSize,
ISequentialInStream)
#else
MY_UNKNOWN_IMP2(
ICompressSetDecoderProperties2,
ICompressGetInStreamProcessedSize)
#endif
void ReleaseStreams()
{
_outWindowStream.ReleaseStream();
ReleaseInStream();
}
class CDecoderFlusher
{
CDecoder *_decoder;
public:
bool NeedFlush;
CDecoderFlusher(CDecoder *decoder): _decoder(decoder), NeedFlush(true) {}
~CDecoderFlusher()
{
if (NeedFlush)
_decoder->Flush();
_decoder->ReleaseStreams();
}
};
HRESULT Flush() { return _outWindowStream.Flush(); }
STDMETHOD(CodeReal)(ISequentialInStream *inStream,
ISequentialOutStream *outStream, const UInt64 *inSize, const UInt64 *outSize,
ICompressProgressInfo *progress);
STDMETHOD(Code)(ISequentialInStream *inStream,
ISequentialOutStream *outStream, const UInt64 *inSize, const UInt64 *outSize,
ICompressProgressInfo *progress);
STDMETHOD(SetDecoderProperties2)(const Byte *data, UInt32 size);
STDMETHOD(GetInStreamProcessedSize)(UInt64 *value);
STDMETHOD(SetInStream)(ISequentialInStream *inStream);
STDMETHOD(ReleaseInStream)();
STDMETHOD(SetOutStreamSize)(const UInt64 *outSize);
#ifdef _ST_MODE
STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize);
#endif
CDecoder(): _outSizeDefined(false) {}
virtual ~CDecoder() {}
};
}}
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -1,411 +0,0 @@
// LZMA/Encoder.h
#ifndef __LZMA_ENCODER_H
#define __LZMA_ENCODER_H
#include "../../../Common/MyCom.h"
#include "../../../Common/Alloc.h"
#include "../../ICoder.h"
#include "../LZ/IMatchFinder.h"
#include "../RangeCoder/RangeCoderBitTree.h"
#include "LZMA.h"
namespace NCompress {
namespace NLZMA {
typedef NRangeCoder::CBitEncoder<kNumMoveBits> CMyBitEncoder;
class CBaseState
{
protected:
CState _state;
Byte _previousByte;
UInt32 _repDistances[kNumRepDistances];
void Init()
{
_state.Init();
_previousByte = 0;
for(UInt32 i = 0 ; i < kNumRepDistances; i++)
_repDistances[i] = 0;
}
};
struct COptimal
{
CState State;
bool Prev1IsChar;
bool Prev2;
UInt32 PosPrev2;
UInt32 BackPrev2;
UInt32 Price;
UInt32 PosPrev; // posNext;
UInt32 BackPrev;
UInt32 Backs[kNumRepDistances];
void MakeAsChar() { BackPrev = UInt32(-1); Prev1IsChar = false; }
void MakeAsShortRep() { BackPrev = 0; ; Prev1IsChar = false; }
bool IsShortRep() { return (BackPrev == 0); }
};
extern Byte g_FastPos[1 << 11];
inline UInt32 GetPosSlot(UInt32 pos)
{
if (pos < (1 << 11))
return g_FastPos[pos];
if (pos < (1 << 21))
return g_FastPos[pos >> 10] + 20;
return g_FastPos[pos >> 20] + 40;
}
inline UInt32 GetPosSlot2(UInt32 pos)
{
if (pos < (1 << 17))
return g_FastPos[pos >> 6] + 12;
if (pos < (1 << 27))
return g_FastPos[pos >> 16] + 32;
return g_FastPos[pos >> 26] + 52;
}
const UInt32 kIfinityPrice = 0xFFFFFFF;
const UInt32 kNumOpts = 1 << 12;
class CLiteralEncoder2
{
CMyBitEncoder _encoders[0x300];
public:
void Init()
{
for (int i = 0; i < 0x300; i++)
_encoders[i].Init();
}
void Encode(NRangeCoder::CEncoder *rangeEncoder, Byte symbol);
void EncodeMatched(NRangeCoder::CEncoder *rangeEncoder, Byte matchByte, Byte symbol);
UInt32 GetPrice(bool matchMode, Byte matchByte, Byte symbol) const;
};
class CLiteralEncoder
{
CLiteralEncoder2 *_coders;
int _numPrevBits;
int _numPosBits;
UInt32 _posMask;
public:
CLiteralEncoder(): _coders(0) {}
~CLiteralEncoder() { Free(); }
void Free()
{
MyFree(_coders);
_coders = 0;
}
bool Create(int numPosBits, int numPrevBits)
{
if (_coders == 0 || (numPosBits + numPrevBits) != (_numPrevBits + _numPosBits))
{
Free();
UInt32 numStates = 1 << (numPosBits + numPrevBits);
_coders = (CLiteralEncoder2 *)MyAlloc(numStates * sizeof(CLiteralEncoder2));
}
_numPosBits = numPosBits;
_posMask = (1 << numPosBits) - 1;
_numPrevBits = numPrevBits;
return (_coders != 0);
}
void Init()
{
UInt32 numStates = 1 << (_numPrevBits + _numPosBits);
for (UInt32 i = 0; i < numStates; i++)
_coders[i].Init();
}
CLiteralEncoder2 *GetSubCoder(UInt32 pos, Byte prevByte)
{ return &_coders[((pos & _posMask) << _numPrevBits) + (prevByte >> (8 - _numPrevBits))]; }
};
namespace NLength {
class CEncoder
{
CMyBitEncoder _choice;
CMyBitEncoder _choice2;
NRangeCoder::CBitTreeEncoder<kNumMoveBits, kNumLowBits> _lowCoder[kNumPosStatesEncodingMax];
NRangeCoder::CBitTreeEncoder<kNumMoveBits, kNumMidBits> _midCoder[kNumPosStatesEncodingMax];
NRangeCoder::CBitTreeEncoder<kNumMoveBits, kNumHighBits> _highCoder;
public:
void Init(UInt32 numPosStates);
void Encode(NRangeCoder::CEncoder *rangeEncoder, UInt32 symbol, UInt32 posState);
void SetPrices(UInt32 posState, UInt32 numSymbols, UInt32 *prices) const;
};
const UInt32 kNumSpecSymbols = kNumLowSymbols + kNumMidSymbols;
class CPriceTableEncoder: public CEncoder
{
UInt32 _prices[kNumPosStatesEncodingMax][kNumSymbolsTotal];
UInt32 _tableSize;
UInt32 _counters[kNumPosStatesEncodingMax];
public:
void SetTableSize(UInt32 tableSize) { _tableSize = tableSize; }
UInt32 GetPrice(UInt32 symbol, UInt32 posState) const { return _prices[posState][symbol]; }
void UpdateTable(UInt32 posState)
{
SetPrices(posState, _tableSize, _prices[posState]);
_counters[posState] = _tableSize;
}
void UpdateTables(UInt32 numPosStates)
{
for (UInt32 posState = 0; posState < numPosStates; posState++)
UpdateTable(posState);
}
void Encode(NRangeCoder::CEncoder *rangeEncoder, UInt32 symbol, UInt32 posState, bool updatePrice)
{
CEncoder::Encode(rangeEncoder, symbol, posState);
if (updatePrice)
if (--_counters[posState] == 0)
UpdateTable(posState);
}
};
}
class CEncoder :
public ICompressCoder,
public ICompressSetOutStream,
public ICompressSetCoderProperties,
public ICompressWriteCoderProperties,
public CBaseState,
public CMyUnknownImp
{
COptimal _optimum[kNumOpts];
CMyComPtr<IMatchFinder> _matchFinder; // test it
NRangeCoder::CEncoder _rangeEncoder;
CMyBitEncoder _isMatch[kNumStates][NLength::kNumPosStatesEncodingMax];
CMyBitEncoder _isRep[kNumStates];
CMyBitEncoder _isRepG0[kNumStates];
CMyBitEncoder _isRepG1[kNumStates];
CMyBitEncoder _isRepG2[kNumStates];
CMyBitEncoder _isRep0Long[kNumStates][NLength::kNumPosStatesEncodingMax];
NRangeCoder::CBitTreeEncoder<kNumMoveBits, kNumPosSlotBits> _posSlotEncoder[kNumLenToPosStates];
CMyBitEncoder _posEncoders[kNumFullDistances - kEndPosModelIndex];
NRangeCoder::CBitTreeEncoder<kNumMoveBits, kNumAlignBits> _posAlignEncoder;
NLength::CPriceTableEncoder _lenEncoder;
NLength::CPriceTableEncoder _repMatchLenEncoder;
CLiteralEncoder _literalEncoder;
UInt32 _matchDistances[kMatchMaxLen * 2 + 2 + 1];
bool _fastMode;
// bool _maxMode;
UInt32 _numFastBytes;
UInt32 _longestMatchLength;
UInt32 _numDistancePairs;
UInt32 _additionalOffset;
UInt32 _optimumEndIndex;
UInt32 _optimumCurrentIndex;
bool _longestMatchWasFound;
UInt32 _posSlotPrices[kNumLenToPosStates][kDistTableSizeMax];
UInt32 _distancesPrices[kNumLenToPosStates][kNumFullDistances];
UInt32 _alignPrices[kAlignTableSize];
UInt32 _alignPriceCount;
UInt32 _distTableSize;
UInt32 _posStateBits;
UInt32 _posStateMask;
UInt32 _numLiteralPosStateBits;
UInt32 _numLiteralContextBits;
UInt32 _dictionarySize;
UInt32 _dictionarySizePrev;
UInt32 _numFastBytesPrev;
UInt32 _matchPriceCount;
UInt64 nowPos64;
bool _finished;
ISequentialInStream *_inStream;
UInt32 _matchFinderCycles;
int _matchFinderIndex;
#ifdef COMPRESS_MF_MT
bool _multiThread;
#endif
bool _writeEndMark;
bool _needReleaseMFStream;
IMatchFinderSetNumPasses *setMfPasses;
void ReleaseMatchFinder()
{
setMfPasses = 0;
_matchFinder.Release();
}
HRESULT ReadMatchDistances(UInt32 &len, UInt32 &numDistancePairs);
HRESULT MovePos(UInt32 num);
UInt32 GetRepLen1Price(CState state, UInt32 posState) const
{
return _isRepG0[state.Index].GetPrice0() +
_isRep0Long[state.Index][posState].GetPrice0();
}
UInt32 GetPureRepPrice(UInt32 repIndex, CState state, UInt32 posState) const
{
UInt32 price;
if(repIndex == 0)
{
price = _isRepG0[state.Index].GetPrice0();
price += _isRep0Long[state.Index][posState].GetPrice1();
}
else
{
price = _isRepG0[state.Index].GetPrice1();
if (repIndex == 1)
price += _isRepG1[state.Index].GetPrice0();
else
{
price += _isRepG1[state.Index].GetPrice1();
price += _isRepG2[state.Index].GetPrice(repIndex - 2);
}
}
return price;
}
UInt32 GetRepPrice(UInt32 repIndex, UInt32 len, CState state, UInt32 posState) const
{
return _repMatchLenEncoder.GetPrice(len - kMatchMinLen, posState) +
GetPureRepPrice(repIndex, state, posState);
}
/*
UInt32 GetPosLen2Price(UInt32 pos, UInt32 posState) const
{
if (pos >= kNumFullDistances)
return kIfinityPrice;
return _distancesPrices[0][pos] + _lenEncoder.GetPrice(0, posState);
}
UInt32 GetPosLen3Price(UInt32 pos, UInt32 len, UInt32 posState) const
{
UInt32 price;
UInt32 lenToPosState = GetLenToPosState(len);
if (pos < kNumFullDistances)
price = _distancesPrices[lenToPosState][pos];
else
price = _posSlotPrices[lenToPosState][GetPosSlot2(pos)] +
_alignPrices[pos & kAlignMask];
return price + _lenEncoder.GetPrice(len - kMatchMinLen, posState);
}
*/
UInt32 GetPosLenPrice(UInt32 pos, UInt32 len, UInt32 posState) const
{
UInt32 price;
UInt32 lenToPosState = GetLenToPosState(len);
if (pos < kNumFullDistances)
price = _distancesPrices[lenToPosState][pos];
else
price = _posSlotPrices[lenToPosState][GetPosSlot2(pos)] +
_alignPrices[pos & kAlignMask];
return price + _lenEncoder.GetPrice(len - kMatchMinLen, posState);
}
UInt32 Backward(UInt32 &backRes, UInt32 cur);
HRESULT GetOptimum(UInt32 position, UInt32 &backRes, UInt32 &lenRes);
HRESULT GetOptimumFast(UInt32 position, UInt32 &backRes, UInt32 &lenRes);
void FillDistancesPrices();
void FillAlignPrices();
void ReleaseMFStream()
{
if (_matchFinder && _needReleaseMFStream)
{
_matchFinder->ReleaseStream();
_needReleaseMFStream = false;
}
}
void ReleaseStreams()
{
ReleaseMFStream();
ReleaseOutStream();
}
HRESULT Flush(UInt32 nowPos);
class CCoderReleaser
{
CEncoder *_coder;
public:
CCoderReleaser(CEncoder *coder): _coder(coder) {}
~CCoderReleaser()
{
_coder->ReleaseStreams();
}
};
friend class CCoderReleaser;
void WriteEndMarker(UInt32 posState);
public:
CEncoder();
void SetWriteEndMarkerMode(bool writeEndMarker)
{ _writeEndMark= writeEndMarker; }
HRESULT Create();
MY_UNKNOWN_IMP3(
ICompressSetOutStream,
ICompressSetCoderProperties,
ICompressWriteCoderProperties
)
HRESULT Init();
// ICompressCoder interface
HRESULT SetStreams(ISequentialInStream *inStream,
ISequentialOutStream *outStream,
const UInt64 *inSize, const UInt64 *outSize);
HRESULT CodeOneBlock(UInt64 *inSize, UInt64 *outSize, Int32 *finished);
HRESULT CodeReal(ISequentialInStream *inStream,
ISequentialOutStream *outStream,
const UInt64 *inSize, const UInt64 *outSize,
ICompressProgressInfo *progress);
// ICompressCoder interface
STDMETHOD(Code)(ISequentialInStream *inStream,
ISequentialOutStream *outStream,
const UInt64 *inSize, const UInt64 *outSize,
ICompressProgressInfo *progress);
// ICompressSetCoderProperties2
STDMETHOD(SetCoderProperties)(const PROPID *propIDs,
const PROPVARIANT *properties, UInt32 numProperties);
// ICompressWriteCoderProperties
STDMETHOD(WriteCoderProperties)(ISequentialOutStream *outStream);
STDMETHOD(SetOutStream)(ISequentialOutStream *outStream);
STDMETHOD(ReleaseOutStream)();
virtual ~CEncoder() {}
};
}}
#endif

View File

@@ -1,8 +0,0 @@
// StdAfx.h
#ifndef __STDAFX_H
#define __STDAFX_H
#include "../../../Common/MyWindows.h"
#endif

View File

@@ -1,205 +0,0 @@
// Compress/RangeCoder/RangeCoder.h
#ifndef __COMPRESS_RANGECODER_H
#define __COMPRESS_RANGECODER_H
#include "../../Common/InBuffer.h"
#include "../../Common/OutBuffer.h"
namespace NCompress {
namespace NRangeCoder {
const int kNumTopBits = 24;
const UInt32 kTopValue = (1 << kNumTopBits);
class CEncoder
{
UInt32 _cacheSize;
Byte _cache;
public:
UInt64 Low;
UInt32 Range;
COutBuffer Stream;
bool Create(UInt32 bufferSize) { return Stream.Create(bufferSize); }
void SetStream(ISequentialOutStream *stream) { Stream.SetStream(stream); }
void Init()
{
Stream.Init();
Low = 0;
Range = 0xFFFFFFFF;
_cacheSize = 1;
_cache = 0;
}
void FlushData()
{
// Low += 1;
for(int i = 0; i < 5; i++)
ShiftLow();
}
HRESULT FlushStream() { return Stream.Flush(); }
void ReleaseStream() { Stream.ReleaseStream(); }
void Encode(UInt32 start, UInt32 size, UInt32 total)
{
Low += start * (Range /= total);
Range *= size;
while (Range < kTopValue)
{
Range <<= 8;
ShiftLow();
}
}
void ShiftLow()
{
if ((UInt32)Low < (UInt32)0xFF000000 || (int)(Low >> 32) != 0)
{
Byte temp = _cache;
do
{
Stream.WriteByte((Byte)(temp + (Byte)(Low >> 32)));
temp = 0xFF;
}
while(--_cacheSize != 0);
_cache = (Byte)((UInt32)Low >> 24);
}
_cacheSize++;
Low = (UInt32)Low << 8;
}
void EncodeDirectBits(UInt32 value, int numTotalBits)
{
for (int i = numTotalBits - 1; i >= 0; i--)
{
Range >>= 1;
if (((value >> i) & 1) == 1)
Low += Range;
if (Range < kTopValue)
{
Range <<= 8;
ShiftLow();
}
}
}
void EncodeBit(UInt32 size0, UInt32 numTotalBits, UInt32 symbol)
{
UInt32 newBound = (Range >> numTotalBits) * size0;
if (symbol == 0)
Range = newBound;
else
{
Low += newBound;
Range -= newBound;
}
while (Range < kTopValue)
{
Range <<= 8;
ShiftLow();
}
}
UInt64 GetProcessedSize() { return Stream.GetProcessedSize() + _cacheSize + 4; }
};
class CDecoder
{
public:
CInBuffer Stream;
UInt32 Range;
UInt32 Code;
bool Create(UInt32 bufferSize) { return Stream.Create(bufferSize); }
void Normalize()
{
while (Range < kTopValue)
{
Code = (Code << 8) | Stream.ReadByte();
Range <<= 8;
}
}
void SetStream(ISequentialInStream *stream) { Stream.SetStream(stream); }
void Init()
{
Stream.Init();
Code = 0;
Range = 0xFFFFFFFF;
for(int i = 0; i < 5; i++)
Code = (Code << 8) | Stream.ReadByte();
}
void ReleaseStream() { Stream.ReleaseStream(); }
UInt32 GetThreshold(UInt32 total)
{
return (Code) / ( Range /= total);
}
void Decode(UInt32 start, UInt32 size)
{
Code -= start * Range;
Range *= size;
Normalize();
}
UInt32 DecodeDirectBits(int numTotalBits)
{
UInt32 range = Range;
UInt32 code = Code;
UInt32 result = 0;
for (int i = numTotalBits; i != 0; i--)
{
range >>= 1;
/*
result <<= 1;
if (code >= range)
{
code -= range;
result |= 1;
}
*/
UInt32 t = (code - range) >> 31;
code -= range & (t - 1);
result = (result << 1) | (1 - t);
if (range < kTopValue)
{
code = (code << 8) | Stream.ReadByte();
range <<= 8;
}
}
Range = range;
Code = code;
return result;
}
UInt32 DecodeBit(UInt32 size0, UInt32 numTotalBits)
{
UInt32 newBound = (Range >> numTotalBits) * size0;
UInt32 symbol;
if (Code < newBound)
{
symbol = 0;
Range = newBound;
}
else
{
symbol = 1;
Code -= newBound;
Range -= newBound;
}
Normalize();
return symbol;
}
UInt64 GetProcessedSize() {return Stream.GetProcessedSize(); }
};
}}
#endif

View File

@@ -1,80 +0,0 @@
// Compress/RangeCoder/RangeCoderBit.cpp
#include "StdAfx.h"
#include "RangeCoderBit.h"
namespace NCompress {
namespace NRangeCoder {
UInt32 CPriceTables::ProbPrices[kBitModelTotal >> kNumMoveReducingBits];
static CPriceTables g_PriceTables;
CPriceTables::CPriceTables() { Init(); }
void CPriceTables::Init()
{
const int kNumBits = (kNumBitModelTotalBits - kNumMoveReducingBits);
for(int i = kNumBits - 1; i >= 0; i--)
{
UInt32 start = 1 << (kNumBits - i - 1);
UInt32 end = 1 << (kNumBits - i);
for (UInt32 j = start; j < end; j++)
ProbPrices[j] = (i << kNumBitPriceShiftBits) +
(((end - j) << kNumBitPriceShiftBits) >> (kNumBits - i - 1));
}
/*
// simplest: bad solution
for(UInt32 i = 1; i < (kBitModelTotal >> kNumMoveReducingBits) - 1; i++)
ProbPrices[i] = kBitPrice;
*/
/*
const double kDummyMultMid = (1.0 / kBitPrice) / 2;
const double kDummyMultMid = 0;
// float solution
double ln2 = log(double(2));
double lnAll = log(double(kBitModelTotal >> kNumMoveReducingBits));
for(UInt32 i = 1; i < (kBitModelTotal >> kNumMoveReducingBits) - 1; i++)
ProbPrices[i] = UInt32((fabs(lnAll - log(double(i))) / ln2 + kDummyMultMid) * kBitPrice);
*/
/*
// experimental, slow, solution:
for(UInt32 i = 1; i < (kBitModelTotal >> kNumMoveReducingBits) - 1; i++)
{
const int kCyclesBits = 5;
const UInt32 kCycles = (1 << kCyclesBits);
UInt32 range = UInt32(-1);
UInt32 bitCount = 0;
for (UInt32 j = 0; j < kCycles; j++)
{
range >>= (kNumBitModelTotalBits - kNumMoveReducingBits);
range *= i;
while(range < (1 << 31))
{
range <<= 1;
bitCount++;
}
}
bitCount <<= kNumBitPriceShiftBits;
range -= (1 << 31);
for (int k = kNumBitPriceShiftBits - 1; k >= 0; k--)
{
range <<= 1;
if (range > (1 << 31))
{
bitCount += (1 << k);
range -= (1 << 31);
}
}
ProbPrices[i] = (bitCount
// + (1 << (kCyclesBits - 1))
) >> kCyclesBits;
}
*/
}
}}

View File

@@ -1,120 +0,0 @@
// Compress/RangeCoder/RangeCoderBit.h
#ifndef __COMPRESS_RANGECODER_BIT_H
#define __COMPRESS_RANGECODER_BIT_H
#include "RangeCoder.h"
namespace NCompress {
namespace NRangeCoder {
const int kNumBitModelTotalBits = 11;
const UInt32 kBitModelTotal = (1 << kNumBitModelTotalBits);
const int kNumMoveReducingBits = 2;
const int kNumBitPriceShiftBits = 6;
const UInt32 kBitPrice = 1 << kNumBitPriceShiftBits;
class CPriceTables
{
public:
static UInt32 ProbPrices[kBitModelTotal >> kNumMoveReducingBits];
static void Init();
CPriceTables();
};
template <int numMoveBits>
class CBitModel
{
public:
UInt32 Prob;
void UpdateModel(UInt32 symbol)
{
/*
Prob -= (Prob + ((symbol - 1) & ((1 << numMoveBits) - 1))) >> numMoveBits;
Prob += (1 - symbol) << (kNumBitModelTotalBits - numMoveBits);
*/
if (symbol == 0)
Prob += (kBitModelTotal - Prob) >> numMoveBits;
else
Prob -= (Prob) >> numMoveBits;
}
public:
void Init() { Prob = kBitModelTotal / 2; }
};
template <int numMoveBits>
class CBitEncoder: public CBitModel<numMoveBits>
{
public:
void Encode(CEncoder *encoder, UInt32 symbol)
{
/*
encoder->EncodeBit(this->Prob, kNumBitModelTotalBits, symbol);
this->UpdateModel(symbol);
*/
UInt32 newBound = (encoder->Range >> kNumBitModelTotalBits) * this->Prob;
if (symbol == 0)
{
encoder->Range = newBound;
this->Prob += (kBitModelTotal - this->Prob) >> numMoveBits;
}
else
{
encoder->Low += newBound;
encoder->Range -= newBound;
this->Prob -= (this->Prob) >> numMoveBits;
}
if (encoder->Range < kTopValue)
{
encoder->Range <<= 8;
encoder->ShiftLow();
}
}
UInt32 GetPrice(UInt32 symbol) const
{
return CPriceTables::ProbPrices[
(((this->Prob - symbol) ^ ((-(int)symbol))) & (kBitModelTotal - 1)) >> kNumMoveReducingBits];
}
UInt32 GetPrice0() const { return CPriceTables::ProbPrices[this->Prob >> kNumMoveReducingBits]; }
UInt32 GetPrice1() const { return CPriceTables::ProbPrices[(kBitModelTotal - this->Prob) >> kNumMoveReducingBits]; }
};
template <int numMoveBits>
class CBitDecoder: public CBitModel<numMoveBits>
{
public:
UInt32 Decode(CDecoder *decoder)
{
UInt32 newBound = (decoder->Range >> kNumBitModelTotalBits) * this->Prob;
if (decoder->Code < newBound)
{
decoder->Range = newBound;
this->Prob += (kBitModelTotal - this->Prob) >> numMoveBits;
if (decoder->Range < kTopValue)
{
decoder->Code = (decoder->Code << 8) | decoder->Stream.ReadByte();
decoder->Range <<= 8;
}
return 0;
}
else
{
decoder->Range -= newBound;
decoder->Code -= newBound;
this->Prob -= (this->Prob) >> numMoveBits;
if (decoder->Range < kTopValue)
{
decoder->Code = (decoder->Code << 8) | decoder->Stream.ReadByte();
decoder->Range <<= 8;
}
return 1;
}
}
};
}}
#endif

View File

@@ -1,161 +0,0 @@
// Compress/RangeCoder/RangeCoderBitTree.h
#ifndef __COMPRESS_RANGECODER_BIT_TREE_H
#define __COMPRESS_RANGECODER_BIT_TREE_H
#include "RangeCoderBit.h"
#include "RangeCoderOpt.h"
namespace NCompress {
namespace NRangeCoder {
template <int numMoveBits, int NumBitLevels>
class CBitTreeEncoder
{
CBitEncoder<numMoveBits> Models[1 << NumBitLevels];
public:
void Init()
{
for(UInt32 i = 1; i < (1 << NumBitLevels); i++)
Models[i].Init();
}
void Encode(CEncoder *rangeEncoder, UInt32 symbol)
{
UInt32 modelIndex = 1;
for (int bitIndex = NumBitLevels; bitIndex != 0 ;)
{
bitIndex--;
UInt32 bit = (symbol >> bitIndex) & 1;
Models[modelIndex].Encode(rangeEncoder, bit);
modelIndex = (modelIndex << 1) | bit;
}
};
void ReverseEncode(CEncoder *rangeEncoder, UInt32 symbol)
{
UInt32 modelIndex = 1;
for (int i = 0; i < NumBitLevels; i++)
{
UInt32 bit = symbol & 1;
Models[modelIndex].Encode(rangeEncoder, bit);
modelIndex = (modelIndex << 1) | bit;
symbol >>= 1;
}
}
UInt32 GetPrice(UInt32 symbol) const
{
symbol |= (1 << NumBitLevels);
UInt32 price = 0;
while (symbol != 1)
{
price += Models[symbol >> 1].GetPrice(symbol & 1);
symbol >>= 1;
}
return price;
}
UInt32 ReverseGetPrice(UInt32 symbol) const
{
UInt32 price = 0;
UInt32 modelIndex = 1;
for (int i = NumBitLevels; i != 0; i--)
{
UInt32 bit = symbol & 1;
symbol >>= 1;
price += Models[modelIndex].GetPrice(bit);
modelIndex = (modelIndex << 1) | bit;
}
return price;
}
};
template <int numMoveBits, int NumBitLevels>
class CBitTreeDecoder
{
CBitDecoder<numMoveBits> Models[1 << NumBitLevels];
public:
void Init()
{
for(UInt32 i = 1; i < (1 << NumBitLevels); i++)
Models[i].Init();
}
UInt32 Decode(CDecoder *rangeDecoder)
{
UInt32 modelIndex = 1;
RC_INIT_VAR
for(int bitIndex = NumBitLevels; bitIndex != 0; bitIndex--)
{
// modelIndex = (modelIndex << 1) + Models[modelIndex].Decode(rangeDecoder);
RC_GETBIT(numMoveBits, Models[modelIndex].Prob, modelIndex)
}
RC_FLUSH_VAR
return modelIndex - (1 << NumBitLevels);
};
UInt32 ReverseDecode(CDecoder *rangeDecoder)
{
UInt32 modelIndex = 1;
UInt32 symbol = 0;
RC_INIT_VAR
for(int bitIndex = 0; bitIndex < NumBitLevels; bitIndex++)
{
// UInt32 bit = Models[modelIndex].Decode(rangeDecoder);
// modelIndex <<= 1;
// modelIndex += bit;
// symbol |= (bit << bitIndex);
RC_GETBIT2(numMoveBits, Models[modelIndex].Prob, modelIndex, ; , symbol |= (1 << bitIndex))
}
RC_FLUSH_VAR
return symbol;
}
};
template <int numMoveBits>
void ReverseBitTreeEncode(CBitEncoder<numMoveBits> *Models,
CEncoder *rangeEncoder, int NumBitLevels, UInt32 symbol)
{
UInt32 modelIndex = 1;
for (int i = 0; i < NumBitLevels; i++)
{
UInt32 bit = symbol & 1;
Models[modelIndex].Encode(rangeEncoder, bit);
modelIndex = (modelIndex << 1) | bit;
symbol >>= 1;
}
}
template <int numMoveBits>
UInt32 ReverseBitTreeGetPrice(CBitEncoder<numMoveBits> *Models,
UInt32 NumBitLevels, UInt32 symbol)
{
UInt32 price = 0;
UInt32 modelIndex = 1;
for (int i = NumBitLevels; i != 0; i--)
{
UInt32 bit = symbol & 1;
symbol >>= 1;
price += Models[modelIndex].GetPrice(bit);
modelIndex = (modelIndex << 1) | bit;
}
return price;
}
template <int numMoveBits>
UInt32 ReverseBitTreeDecode(CBitDecoder<numMoveBits> *Models,
CDecoder *rangeDecoder, int NumBitLevels)
{
UInt32 modelIndex = 1;
UInt32 symbol = 0;
RC_INIT_VAR
for(int bitIndex = 0; bitIndex < NumBitLevels; bitIndex++)
{
// UInt32 bit = Models[modelIndex].Decode(rangeDecoder);
// modelIndex <<= 1;
// modelIndex += bit;
// symbol |= (bit << bitIndex);
RC_GETBIT2(numMoveBits, Models[modelIndex].Prob, modelIndex, ; , symbol |= (1 << bitIndex))
}
RC_FLUSH_VAR
return symbol;
}
}}
#endif

View File

@@ -1,31 +0,0 @@
// Compress/RangeCoder/RangeCoderOpt.h
#ifndef __COMPRESS_RANGECODER_OPT_H
#define __COMPRESS_RANGECODER_OPT_H
#define RC_INIT_VAR \
UInt32 range = rangeDecoder->Range; \
UInt32 code = rangeDecoder->Code;
#define RC_FLUSH_VAR \
rangeDecoder->Range = range; \
rangeDecoder->Code = code;
#define RC_NORMALIZE \
if (range < NCompress::NRangeCoder::kTopValue) \
{ code = (code << 8) | rangeDecoder->Stream.ReadByte(); range <<= 8; }
#define RC_GETBIT2(numMoveBits, prob, mi, A0, A1) \
{ UInt32 bound = (range >> NCompress::NRangeCoder::kNumBitModelTotalBits) * prob; \
if (code < bound) \
{ A0; range = bound; \
prob += (NCompress::NRangeCoder::kBitModelTotal - prob) >> numMoveBits; \
mi <<= 1; } \
else \
{ A1; range -= bound; code -= bound; prob -= (prob) >> numMoveBits; \
mi = (mi + mi) + 1; }} \
RC_NORMALIZE
#define RC_GETBIT(numMoveBits, prob, mi) RC_GETBIT2(numMoveBits, prob, mi, ; , ;)
#endif

View File

@@ -1,6 +0,0 @@
// StdAfx.h
#ifndef __STDAFX_H
#define __STDAFX_H
#endif

View File

@@ -1,163 +0,0 @@
// ICoder.h
#ifndef __ICODER_H
#define __ICODER_H
#include "IStream.h"
// "23170F69-40C1-278A-0000-000400xx0000"
#define CODER_INTERFACE(i, x) \
DEFINE_GUID(IID_ ## i, \
0x23170F69, 0x40C1, 0x278A, 0x00, 0x00, 0x00, 0x04, 0x00, x, 0x00, 0x00); \
struct i: public IUnknown
CODER_INTERFACE(ICompressProgressInfo, 0x04)
{
STDMETHOD(SetRatioInfo)(const UInt64 *inSize, const UInt64 *outSize) PURE;
};
CODER_INTERFACE(ICompressCoder, 0x05)
{
STDMETHOD(Code)(ISequentialInStream *inStream,
ISequentialOutStream *outStream,
const UInt64 *inSize,
const UInt64 *outSize,
ICompressProgressInfo *progress) PURE;
};
CODER_INTERFACE(ICompressCoder2, 0x18)
{
STDMETHOD(Code)(ISequentialInStream **inStreams,
const UInt64 **inSizes,
UInt32 numInStreams,
ISequentialOutStream **outStreams,
const UInt64 **outSizes,
UInt32 numOutStreams,
ICompressProgressInfo *progress) PURE;
};
namespace NCoderPropID
{
enum EEnum
{
kDictionarySize = 0x400,
kUsedMemorySize,
kOrder,
kPosStateBits = 0x440,
kLitContextBits,
kLitPosBits,
kNumFastBytes = 0x450,
kMatchFinder,
kMatchFinderCycles,
kNumPasses = 0x460,
kAlgorithm = 0x470,
kMultiThread = 0x480,
kNumThreads,
kEndMarker = 0x490
};
}
CODER_INTERFACE(ICompressSetCoderProperties, 0x20)
{
STDMETHOD(SetCoderProperties)(const PROPID *propIDs,
const PROPVARIANT *properties, UInt32 numProperties) PURE;
};
/*
CODER_INTERFACE(ICompressSetCoderProperties, 0x21)
{
STDMETHOD(SetDecoderProperties)(ISequentialInStream *inStream) PURE;
};
*/
CODER_INTERFACE(ICompressSetDecoderProperties2, 0x22)
{
STDMETHOD(SetDecoderProperties2)(const Byte *data, UInt32 size) PURE;
};
CODER_INTERFACE(ICompressWriteCoderProperties, 0x23)
{
STDMETHOD(WriteCoderProperties)(ISequentialOutStream *outStreams) PURE;
};
CODER_INTERFACE(ICompressGetInStreamProcessedSize, 0x24)
{
STDMETHOD(GetInStreamProcessedSize)(UInt64 *value) PURE;
};
CODER_INTERFACE(ICompressSetCoderMt, 0x25)
{
STDMETHOD(SetNumberOfThreads)(UInt32 numThreads) PURE;
};
CODER_INTERFACE(ICompressGetSubStreamSize, 0x30)
{
STDMETHOD(GetSubStreamSize)(UInt64 subStream, UInt64 *value) PURE;
};
CODER_INTERFACE(ICompressSetInStream, 0x31)
{
STDMETHOD(SetInStream)(ISequentialInStream *inStream) PURE;
STDMETHOD(ReleaseInStream)() PURE;
};
CODER_INTERFACE(ICompressSetOutStream, 0x32)
{
STDMETHOD(SetOutStream)(ISequentialOutStream *outStream) PURE;
STDMETHOD(ReleaseOutStream)() PURE;
};
CODER_INTERFACE(ICompressSetInStreamSize, 0x33)
{
STDMETHOD(SetInStreamSize)(const UInt64 *inSize) PURE;
};
CODER_INTERFACE(ICompressSetOutStreamSize, 0x34)
{
STDMETHOD(SetOutStreamSize)(const UInt64 *outSize) PURE;
};
CODER_INTERFACE(ICompressFilter, 0x40)
{
STDMETHOD(Init)() PURE;
STDMETHOD_(UInt32, Filter)(Byte *data, UInt32 size) PURE;
// Filter return outSize (UInt32)
// if (outSize <= size): Filter have converted outSize bytes
// if (outSize > size): Filter have not converted anything.
// and it needs at least outSize bytes to convert one block
// (it's for crypto block algorithms).
};
CODER_INTERFACE(ICryptoProperties, 0x80)
{
STDMETHOD(SetKey)(const Byte *data, UInt32 size) PURE;
STDMETHOD(SetInitVector)(const Byte *data, UInt32 size) PURE;
};
CODER_INTERFACE(ICryptoSetPassword, 0x90)
{
STDMETHOD(CryptoSetPassword)(const Byte *data, UInt32 size) PURE;
};
CODER_INTERFACE(ICryptoSetCRC, 0xA0)
{
STDMETHOD(CryptoSetCRC)(UInt32 crc) PURE;
};
//////////////////////
// It's for DLL file
namespace NMethodPropID
{
enum EEnum
{
kID,
kName,
kDecoder,
kEncoder,
kInStreams,
kOutStreams,
kDescription
};
}
#endif

View File

@@ -1,62 +0,0 @@
// IStream.h
#ifndef __ISTREAM_H
#define __ISTREAM_H
#include "../Common/MyUnknown.h"
#include "../Common/Types.h"
// "23170F69-40C1-278A-0000-000300xx0000"
#define STREAM_INTERFACE_SUB(i, b, x) \
DEFINE_GUID(IID_ ## i, \
0x23170F69, 0x40C1, 0x278A, 0x00, 0x00, 0x00, 0x03, 0x00, x, 0x00, 0x00); \
struct i: public b
#define STREAM_INTERFACE(i, x) STREAM_INTERFACE_SUB(i, IUnknown, x)
STREAM_INTERFACE(ISequentialInStream, 0x01)
{
STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize) PURE;
/*
Out: if size != 0, return_value = S_OK and (*processedSize == 0),
then there are no more bytes in stream.
if (size > 0) && there are bytes in stream,
this function must read at least 1 byte.
This function is allowed to read less than number of remaining bytes in stream.
You must call Read function in loop, if you need exact amount of data
*/
};
STREAM_INTERFACE(ISequentialOutStream, 0x02)
{
STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize) PURE;
/*
if (size > 0) this function must write at least 1 byte.
This function is allowed to write less than "size".
You must call Write function in loop, if you need to write exact amount of data
*/
};
STREAM_INTERFACE_SUB(IInStream, ISequentialInStream, 0x03)
{
STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) PURE;
};
STREAM_INTERFACE_SUB(IOutStream, ISequentialOutStream, 0x04)
{
STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) PURE;
STDMETHOD(SetSize)(Int64 newSize) PURE;
};
STREAM_INTERFACE(IStreamGetSize, 0x06)
{
STDMETHOD(GetSize)(UInt64 *size) PURE;
};
STREAM_INTERFACE(IOutStreamFlush, 0x07)
{
STDMETHOD(Flush)() PURE;
};
#endif

View File

@@ -1,121 +0,0 @@
// Common/Alloc.cpp
#include "StdAfx.h"
#ifdef _WIN32
#include "MyWindows.h"
#else
#include <stdlib.h>
#endif
#include "Alloc.h"
/* #define _SZ_ALLOC_DEBUG */
/* use _SZ_ALLOC_DEBUG to debug alloc/free operations */
#ifdef _SZ_ALLOC_DEBUG
#include <stdio.h>
int g_allocCount = 0;
int g_allocCountMid = 0;
int g_allocCountBig = 0;
#endif
void *MyAlloc(size_t size) throw()
{
if (size == 0)
return 0;
#ifdef _SZ_ALLOC_DEBUG
fprintf(stderr, "\nAlloc %10d bytes; count = %10d", size, g_allocCount++);
#endif
return ::malloc(size);
}
void MyFree(void *address) throw()
{
#ifdef _SZ_ALLOC_DEBUG
if (address != 0)
fprintf(stderr, "\nFree; count = %10d", --g_allocCount);
#endif
::free(address);
}
#ifdef _WIN32
void *MidAlloc(size_t size) throw()
{
if (size == 0)
return 0;
#ifdef _SZ_ALLOC_DEBUG
fprintf(stderr, "\nAlloc_Mid %10d bytes; count = %10d", size, g_allocCountMid++);
#endif
return ::VirtualAlloc(0, size, MEM_COMMIT, PAGE_READWRITE);
}
void MidFree(void *address) throw()
{
#ifdef _SZ_ALLOC_DEBUG
if (address != 0)
fprintf(stderr, "\nFree_Mid; count = %10d", --g_allocCountMid);
#endif
if (address == 0)
return;
::VirtualFree(address, 0, MEM_RELEASE);
}
static SIZE_T g_LargePageSize =
#ifdef _WIN64
(1 << 21);
#else
(1 << 22);
#endif
typedef SIZE_T (WINAPI *GetLargePageMinimumP)();
bool SetLargePageSize()
{
GetLargePageMinimumP largePageMinimum = (GetLargePageMinimumP)
::GetProcAddress(::GetModuleHandle(TEXT("kernel32.dll")), "GetLargePageMinimum");
if (largePageMinimum == 0)
return false;
SIZE_T size = largePageMinimum();
if (size == 0 || (size & (size - 1)) != 0)
return false;
g_LargePageSize = size;
return true;
}
#ifdef MEM_LARGE_PAGES
void *BigAlloc(size_t size) throw()
{
if (size == 0)
return 0;
#ifdef _SZ_ALLOC_DEBUG
fprintf(stderr, "\nAlloc_Big %10d bytes; count = %10d", size, g_allocCountBig++);
#endif
if (size >= (1 << 18))
{
void *res = ::VirtualAlloc(0, (size + g_LargePageSize - 1) & (~(g_LargePageSize - 1)),
MEM_COMMIT | MEM_LARGE_PAGES, PAGE_READWRITE);
if (res != 0)
return res;
}
return ::VirtualAlloc(0, size, MEM_COMMIT, PAGE_READWRITE);
}
void BigFree(void *address) throw()
{
#ifdef _SZ_ALLOC_DEBUG
if (address != 0)
fprintf(stderr, "\nFree_Big; count = %10d", --g_allocCountBig);
#endif
if (address == 0)
return;
::VirtualFree(address, 0, MEM_RELEASE);
}
#endif
#endif

View File

@@ -1,34 +0,0 @@
// Common/Alloc.h
#ifndef __COMMON_ALLOC_H
#define __COMMON_ALLOC_H
#include <stddef.h>
void *MyAlloc(size_t size) throw();
void MyFree(void *address) throw();
#ifdef _WIN32
bool SetLargePageSize();
void *MidAlloc(size_t size) throw();
void MidFree(void *address) throw();
#ifdef MEM_LARGE_PAGES
void *BigAlloc(size_t size) throw();
void BigFree(void *address) throw();
#else
#define BigAlloc(size) MidAlloc(size)
#define BigFree(address) MidFree(address)
#endif
#else
#define MidAlloc(size) MyAlloc(size)
#define MidFree(address) MyFree(address)
#define BigAlloc(size) MyAlloc(size)
#define BigFree(address) MyFree(address)
#endif
#endif

View File

@@ -1,77 +0,0 @@
// Common/Buffer.h
#ifndef __COMMON_BUFFER_H
#define __COMMON_BUFFER_H
#include "Defs.h"
template <class T> class CBuffer
{
protected:
size_t _capacity;
T *_items;
void Free()
{
delete []_items;
_items = 0;
_capacity = 0;
}
public:
CBuffer(): _capacity(0), _items(0) {};
CBuffer(const CBuffer &buffer): _capacity(0), _items(0) { *this = buffer; }
CBuffer(size_t size): _items(0), _capacity(0) { SetCapacity(size); }
virtual ~CBuffer() { delete []_items; }
operator T *() { return _items; };
operator const T *() const { return _items; };
size_t GetCapacity() const { return _capacity; }
void SetCapacity(size_t newCapacity)
{
if (newCapacity == _capacity)
return;
T *newBuffer;
if (newCapacity > 0)
{
newBuffer = new T[newCapacity];
if(_capacity > 0)
memmove(newBuffer, _items, MyMin(_capacity, newCapacity) * sizeof(T));
}
else
newBuffer = 0;
delete []_items;
_items = newBuffer;
_capacity = newCapacity;
}
CBuffer& operator=(const CBuffer &buffer)
{
Free();
if(buffer._capacity > 0)
{
SetCapacity(buffer._capacity);
memmove(_items, buffer._items, buffer._capacity * sizeof(T));
}
return *this;
}
};
template <class T>
bool operator==(const CBuffer<T>& b1, const CBuffer<T>& b2)
{
if (b1.GetCapacity() != b2.GetCapacity())
return false;
for (size_t i = 0; i < b1.GetCapacity(); i++)
if (b1[i] != b2[i])
return false;
return true;
}
template <class T>
bool operator!=(const CBuffer<T>& b1, const CBuffer<T>& b2)
{
return !(b1 == b2);
}
typedef CBuffer<char> CCharBuffer;
typedef CBuffer<wchar_t> CWCharBuffer;
typedef CBuffer<unsigned char> CByteBuffer;
#endif

View File

@@ -1,61 +0,0 @@
// Common/CRC.cpp
#include "StdAfx.h"
#include "CRC.h"
static const UInt32 kCRCPoly = 0xEDB88320;
UInt32 CCRC::Table[256];
void CCRC::InitTable()
{
for (UInt32 i = 0; i < 256; i++)
{
UInt32 r = i;
for (int j = 0; j < 8; j++)
if (r & 1)
r = (r >> 1) ^ kCRCPoly;
else
r >>= 1;
CCRC::Table[i] = r;
}
}
class CCRCTableInit
{
public:
CCRCTableInit() { CCRC::InitTable(); }
} g_CRCTableInit;
void CCRC::UpdateByte(Byte b)
{
_value = Table[((Byte)(_value)) ^ b] ^ (_value >> 8);
}
void CCRC::UpdateUInt16(UInt16 v)
{
UpdateByte(Byte(v));
UpdateByte(Byte(v >> 8));
}
void CCRC::UpdateUInt32(UInt32 v)
{
for (int i = 0; i < 4; i++)
UpdateByte((Byte)(v >> (8 * i)));
}
void CCRC::UpdateUInt64(UInt64 v)
{
for (int i = 0; i < 8; i++)
UpdateByte((Byte)(v >> (8 * i)));
}
void CCRC::Update(const void *data, size_t size)
{
UInt32 v = _value;
const Byte *p = (const Byte *)data;
for (; size > 0 ; size--, p++)
v = Table[((Byte)(v)) ^ *p] ^ (v >> 8);
_value = v;
}

View File

@@ -1,36 +0,0 @@
// Common/CRC.h
#ifndef __COMMON_CRC_H
#define __COMMON_CRC_H
#include <stddef.h>
#include "Types.h"
class CCRC
{
UInt32 _value;
public:
static UInt32 Table[256];
static void InitTable();
CCRC(): _value(0xFFFFFFFF){};
void Init() { _value = 0xFFFFFFFF; }
void UpdateByte(Byte v);
void UpdateUInt16(UInt16 v);
void UpdateUInt32(UInt32 v);
void UpdateUInt64(UInt64 v);
void Update(const void *data, size_t size);
UInt32 GetDigest() const { return _value ^ 0xFFFFFFFF; }
static UInt32 CalculateDigest(const void *data, size_t size)
{
CCRC crc;
crc.Update(data, size);
return crc.GetDigest();
}
static bool VerifyDigest(UInt32 digest, const void *data, size_t size)
{
return (CalculateDigest(data, size) == digest);
}
};
#endif

View File

@@ -1,17 +0,0 @@
// ComTry.h
#ifndef __COM_TRY_H
#define __COM_TRY_H
#include "MyWindows.h"
// #include "Exception.h"
// #include "NewHandler.h"
#define COM_TRY_BEGIN try {
#define COM_TRY_END } catch(...) { return E_OUTOFMEMORY; }
// catch(const CNewException &) { return E_OUTOFMEMORY; }\
// catch(const CSystemException &e) { return e.ErrorCode; }\
// catch(...) { return E_FAIL; }
#endif

View File

@@ -1,20 +0,0 @@
// Common/Defs.h
#ifndef __COMMON_DEFS_H
#define __COMMON_DEFS_H
template <class T> inline T MyMin(T a, T b)
{ return a < b ? a : b; }
template <class T> inline T MyMax(T a, T b)
{ return a > b ? a : b; }
template <class T> inline int MyCompare(T a, T b)
{ return a < b ? -1 : (a == b ? 0 : 1); }
inline int BoolToInt(bool value)
{ return (value ? 1: 0); }
inline bool IntToBool(int value)
{ return (value != 0); }
#endif

View File

@@ -1,203 +0,0 @@
// MyCom.h
#ifndef __MYCOM_H
#define __MYCOM_H
#include "MyWindows.h"
#define RINOK(x) { HRESULT __result_ = (x); if(__result_ != S_OK) return __result_; }
template <class T>
class CMyComPtr
{
T* _p;
public:
// typedef T _PtrClass;
CMyComPtr() { _p = NULL;}
CMyComPtr(T* p) {if ((_p = p) != NULL) p->AddRef(); }
CMyComPtr(const CMyComPtr<T>& lp)
{
if ((_p = lp._p) != NULL)
_p->AddRef();
}
~CMyComPtr() { if (_p) _p->Release(); }
void Release() { if (_p) { _p->Release(); _p = NULL; } }
operator T*() const { return (T*)_p; }
// T& operator*() const { return *_p; }
T** operator&() { return &_p; }
T* operator->() const { return _p; }
T* operator=(T* p)
{
if (p != 0)
p->AddRef();
if (_p)
_p->Release();
_p = p;
return p;
}
T* operator=(const CMyComPtr<T>& lp) { return (*this = lp._p); }
bool operator!() const { return (_p == NULL); }
// bool operator==(T* pT) const { return _p == pT; }
// Compare two objects for equivalence
void Attach(T* p2)
{
Release();
_p = p2;
}
T* Detach()
{
T* pt = _p;
_p = NULL;
return pt;
}
#ifdef _WIN32
HRESULT CoCreateInstance(REFCLSID rclsid, REFIID iid, LPUNKNOWN pUnkOuter = NULL, DWORD dwClsContext = CLSCTX_ALL)
{
return ::CoCreateInstance(rclsid, pUnkOuter, dwClsContext, iid, (void**)&_p);
}
#endif
/*
HRESULT CoCreateInstance(LPCOLESTR szProgID, LPUNKNOWN pUnkOuter = NULL, DWORD dwClsContext = CLSCTX_ALL)
{
CLSID clsid;
HRESULT hr = CLSIDFromProgID(szProgID, &clsid);
ATLASSERT(_p == NULL);
if (SUCCEEDED(hr))
hr = ::CoCreateInstance(clsid, pUnkOuter, dwClsContext, __uuidof(T), (void**)&_p);
return hr;
}
*/
template <class Q>
HRESULT QueryInterface(REFGUID iid, Q** pp) const
{
return _p->QueryInterface(iid, (void**)pp);
}
};
//////////////////////////////////////////////////////////
class CMyComBSTR
{
public:
BSTR m_str;
CMyComBSTR() { m_str = NULL; }
CMyComBSTR(LPCOLESTR pSrc) { m_str = ::SysAllocString(pSrc); }
// CMyComBSTR(int nSize) { m_str = ::SysAllocStringLen(NULL, nSize); }
// CMyComBSTR(int nSize, LPCOLESTR sz) { m_str = ::SysAllocStringLen(sz, nSize); }
CMyComBSTR(const CMyComBSTR& src) { m_str = src.MyCopy(); }
/*
CMyComBSTR(REFGUID src)
{
LPOLESTR szGuid;
StringFromCLSID(src, &szGuid);
m_str = ::SysAllocString(szGuid);
CoTaskMemFree(szGuid);
}
*/
~CMyComBSTR() { ::SysFreeString(m_str); }
CMyComBSTR& operator=(const CMyComBSTR& src)
{
if (m_str != src.m_str)
{
if (m_str)
::SysFreeString(m_str);
m_str = src.MyCopy();
}
return *this;
}
CMyComBSTR& operator=(LPCOLESTR pSrc)
{
::SysFreeString(m_str);
m_str = ::SysAllocString(pSrc);
return *this;
}
unsigned int Length() const { return ::SysStringLen(m_str); }
operator BSTR() const { return m_str; }
BSTR* operator&() { return &m_str; }
BSTR MyCopy() const
{
int byteLen = ::SysStringByteLen(m_str);
BSTR res = ::SysAllocStringByteLen(NULL, byteLen);
memmove(res, m_str, byteLen);
return res;
}
void Attach(BSTR src) { m_str = src; }
BSTR Detach()
{
BSTR s = m_str;
m_str = NULL;
return s;
}
void Empty()
{
::SysFreeString(m_str);
m_str = NULL;
}
bool operator!() const { return (m_str == NULL); }
};
//////////////////////////////////////////////////////////
class CMyUnknownImp
{
public:
ULONG __m_RefCount;
CMyUnknownImp(): __m_RefCount(0) {}
};
#define MY_QUERYINTERFACE_BEGIN STDMETHOD(QueryInterface) \
(REFGUID iid, void **outObject) {
#define MY_QUERYINTERFACE_ENTRY(i) if (iid == IID_ ## i) \
{ *outObject = (void *)(i *)this; AddRef(); return S_OK; }
#define MY_QUERYINTERFACE_END return E_NOINTERFACE; }
#define MY_ADDREF_RELEASE \
STDMETHOD_(ULONG, AddRef)() { return ++__m_RefCount; } \
STDMETHOD_(ULONG, Release)() { if (--__m_RefCount != 0) \
return __m_RefCount; delete this; return 0; }
#define MY_UNKNOWN_IMP_SPEC(i) \
MY_QUERYINTERFACE_BEGIN \
i \
MY_QUERYINTERFACE_END \
MY_ADDREF_RELEASE
#define MY_UNKNOWN_IMP STDMETHOD(QueryInterface)(REFGUID, void **) { \
MY_QUERYINTERFACE_END \
MY_ADDREF_RELEASE
#define MY_UNKNOWN_IMP1(i) MY_UNKNOWN_IMP_SPEC( \
MY_QUERYINTERFACE_ENTRY(i) \
)
#define MY_UNKNOWN_IMP2(i1, i2) MY_UNKNOWN_IMP_SPEC( \
MY_QUERYINTERFACE_ENTRY(i1) \
MY_QUERYINTERFACE_ENTRY(i2) \
)
#define MY_UNKNOWN_IMP3(i1, i2, i3) MY_UNKNOWN_IMP_SPEC( \
MY_QUERYINTERFACE_ENTRY(i1) \
MY_QUERYINTERFACE_ENTRY(i2) \
MY_QUERYINTERFACE_ENTRY(i3) \
)
#define MY_UNKNOWN_IMP4(i1, i2, i3, i4) MY_UNKNOWN_IMP_SPEC( \
MY_QUERYINTERFACE_ENTRY(i1) \
MY_QUERYINTERFACE_ENTRY(i2) \
MY_QUERYINTERFACE_ENTRY(i3) \
MY_QUERYINTERFACE_ENTRY(i4) \
)
#define MY_UNKNOWN_IMP5(i1, i2, i3, i4, i5) MY_UNKNOWN_IMP_SPEC( \
MY_QUERYINTERFACE_ENTRY(i1) \
MY_QUERYINTERFACE_ENTRY(i2) \
MY_QUERYINTERFACE_ENTRY(i3) \
MY_QUERYINTERFACE_ENTRY(i4) \
MY_QUERYINTERFACE_ENTRY(i5) \
)
#endif

View File

@@ -1,54 +0,0 @@
// Common/MyGuidDef.h
#ifndef GUID_DEFINED
#define GUID_DEFINED
#include "Types.h"
typedef struct {
UInt32 Data1;
UInt16 Data2;
UInt16 Data3;
unsigned char Data4[8];
} GUID;
#ifdef __cplusplus
#define REFGUID const GUID &
#else
#define REFGUID const GUID *
#endif
#define REFCLSID REFGUID
#define REFIID REFGUID
#ifdef __cplusplus
inline bool operator==(REFGUID g1, REFGUID g2)
{
for (int i = 0; i < (int)sizeof(g1); i++)
if (((unsigned char *)&g1)[i] != ((unsigned char *)&g2)[i])
return false;
return true;
}
inline bool operator!=(REFGUID g1, REFGUID g2) { return !(g1 == g2); }
#endif
#ifdef __cplusplus
#define MY_EXTERN_C extern "C"
#else
#define MY_EXTERN_C extern
#endif
#endif // GUID_DEFINED
#ifdef DEFINE_GUID
#undef DEFINE_GUID
#endif
#ifdef INITGUID
#define DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \
MY_EXTERN_C const GUID name = { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } }
#else
#define DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \
MY_EXTERN_C const GUID name
#endif

View File

@@ -1,24 +0,0 @@
// MyUnknown.h
#ifndef __MYUNKNOWN_H
#define __MYUNKNOWN_H
#ifdef _WIN32
#ifdef _WIN32_WCE
#if (_WIN32_WCE > 300)
#include <basetyps.h>
#else
#define MIDL_INTERFACE(x) struct
#endif
#else
#include <basetyps.h>
#endif
#include <unknwn.h>
#else
#include "MyWindows.h"
#endif
#endif

View File

@@ -1,200 +0,0 @@
// MyWindows.h
#ifndef __MYWINDOWS_H
#define __MYWINDOWS_H
#ifdef _WIN32
#include <windows.h>
#define CHAR_PATH_SEPARATOR '\\'
#define WCHAR_PATH_SEPARATOR L'\\'
#define STRING_PATH_SEPARATOR "\\"
#define WSTRING_PATH_SEPARATOR L"\\"
#else
#define CHAR_PATH_SEPARATOR '/'
#define WCHAR_PATH_SEPARATOR L'/'
#define STRING_PATH_SEPARATOR "/"
#define WSTRING_PATH_SEPARATOR L"/"
#include <stddef.h> // for wchar_t
#include <string.h>
#include "MyGuidDef.h"
typedef char CHAR;
typedef unsigned char UCHAR;
#undef BYTE
typedef unsigned char BYTE;
typedef short SHORT;
typedef unsigned short USHORT;
#undef WORD
typedef unsigned short WORD;
typedef short VARIANT_BOOL;
typedef int INT;
typedef Int32 INT32;
typedef unsigned int UINT;
typedef UInt32 UINT32;
typedef INT32 LONG; // LONG, ULONG and DWORD must be 32-bit
typedef UINT32 ULONG;
#undef DWORD
typedef UINT32 DWORD;
typedef Int64 LONGLONG;
typedef UInt64 ULONGLONG;
typedef struct LARGE_INTEGER { LONGLONG QuadPart; }LARGE_INTEGER;
typedef struct _ULARGE_INTEGER { ULONGLONG QuadPart;} ULARGE_INTEGER;
typedef const CHAR *LPCSTR;
typedef CHAR TCHAR;
typedef const TCHAR *LPCTSTR;
typedef wchar_t WCHAR;
typedef WCHAR OLECHAR;
typedef const WCHAR *LPCWSTR;
typedef OLECHAR *BSTR;
typedef const OLECHAR *LPCOLESTR;
typedef OLECHAR *LPOLESTR;
typedef struct _FILETIME
{
DWORD dwLowDateTime;
DWORD dwHighDateTime;
}FILETIME;
#define HRESULT LONG
#define FAILED(Status) ((HRESULT)(Status)<0)
typedef ULONG PROPID;
typedef LONG SCODE;
#define S_OK ((HRESULT)0x00000000L)
#define S_FALSE ((HRESULT)0x00000001L)
#define E_NOTIMPL ((HRESULT)0x80004001L)
#define E_NOINTERFACE ((HRESULT)0x80004002L)
#define E_ABORT ((HRESULT)0x80004004L)
#define E_FAIL ((HRESULT)0x80004005L)
#define STG_E_INVALIDFUNCTION ((HRESULT)0x80030001L)
#define E_OUTOFMEMORY ((HRESULT)0x8007000EL)
#define E_INVALIDARG ((HRESULT)0x80070057L)
#ifdef _MSC_VER
#define STDMETHODCALLTYPE __stdcall
#else
#define STDMETHODCALLTYPE
#endif
#define STDMETHOD_(t, f) virtual t STDMETHODCALLTYPE f
#define STDMETHOD(f) STDMETHOD_(HRESULT, f)
#define STDMETHODIMP_(type) type STDMETHODCALLTYPE
#define STDMETHODIMP STDMETHODIMP_(HRESULT)
#define PURE = 0
#define MIDL_INTERFACE(x) struct
struct IUnknown
{
STDMETHOD(QueryInterface) (REFIID iid, void **outObject) PURE;
STDMETHOD_(ULONG, AddRef)() PURE;
STDMETHOD_(ULONG, Release)() PURE;
};
typedef IUnknown *LPUNKNOWN;
#define VARIANT_TRUE ((VARIANT_BOOL)-1)
#define VARIANT_FALSE ((VARIANT_BOOL)0)
enum VARENUM
{
VT_EMPTY = 0,
VT_NULL = 1,
VT_I2 = 2,
VT_I4 = 3,
VT_R4 = 4,
VT_R8 = 5,
VT_CY = 6,
VT_DATE = 7,
VT_BSTR = 8,
VT_DISPATCH = 9,
VT_ERROR = 10,
VT_BOOL = 11,
VT_VARIANT = 12,
VT_UNKNOWN = 13,
VT_DECIMAL = 14,
VT_I1 = 16,
VT_UI1 = 17,
VT_UI2 = 18,
VT_UI4 = 19,
VT_I8 = 20,
VT_UI8 = 21,
VT_INT = 22,
VT_UINT = 23,
VT_VOID = 24,
VT_HRESULT = 25,
VT_FILETIME = 64
};
typedef unsigned short VARTYPE;
typedef WORD PROPVAR_PAD1;
typedef WORD PROPVAR_PAD2;
typedef WORD PROPVAR_PAD3;
typedef struct tagPROPVARIANT
{
VARTYPE vt;
PROPVAR_PAD1 wReserved1;
PROPVAR_PAD2 wReserved2;
PROPVAR_PAD3 wReserved3;
union
{
CHAR cVal;
UCHAR bVal;
SHORT iVal;
USHORT uiVal;
LONG lVal;
ULONG ulVal;
INT intVal;
UINT uintVal;
LARGE_INTEGER hVal;
ULARGE_INTEGER uhVal;
VARIANT_BOOL boolVal;
SCODE scode;
FILETIME filetime;
BSTR bstrVal;
};
} PROPVARIANT;
typedef PROPVARIANT tagVARIANT;
typedef tagVARIANT VARIANT;
typedef VARIANT VARIANTARG;
MY_EXTERN_C BSTR SysAllocStringByteLen(LPCSTR psz, UINT len);
MY_EXTERN_C BSTR SysAllocString(const OLECHAR *sz);
MY_EXTERN_C void SysFreeString(BSTR bstr);
MY_EXTERN_C UINT SysStringByteLen(BSTR bstr);
MY_EXTERN_C UINT SysStringLen(BSTR bstr);
MY_EXTERN_C DWORD GetLastError();
MY_EXTERN_C HRESULT VariantClear(VARIANTARG *prop);
MY_EXTERN_C HRESULT VariantCopy(VARIANTARG *dest, VARIANTARG *src);
MY_EXTERN_C LONG CompareFileTime(const FILETIME* ft1, const FILETIME* ft2);
#define CP_ACP 0
#define CP_OEMCP 1
typedef enum tagSTREAM_SEEK
{
STREAM_SEEK_SET = 0,
STREAM_SEEK_CUR = 1,
STREAM_SEEK_END = 2
} STREAM_SEEK;
#endif
#endif

View File

@@ -1,116 +0,0 @@
// NewHandler.cpp
#include "StdAfx.h"
#include <stdlib.h>
#include "NewHandler.h"
// #define DEBUG_MEMORY_LEAK
#ifndef DEBUG_MEMORY_LEAK
#ifdef _WIN32
void *
#ifdef _MSC_VER
__cdecl
#endif
operator new(size_t size)
{
// void *p = ::HeapAlloc(::GetProcessHeap(), 0, size);
void *p = ::malloc(size);
if (p == 0)
throw CNewException();
return p;
}
void
#ifdef _MSC_VER
__cdecl
#endif
operator delete(void *p) throw()
{
/*
if (p == 0)
return;
::HeapFree(::GetProcessHeap(), 0, p);
*/
::free(p);
}
#endif
#else
#pragma init_seg(lib)
const int kDebugSize = 1000000;
static void *a[kDebugSize];
static int index = 0;
static int numAllocs = 0;
void * __cdecl operator new(size_t size)
{
numAllocs++;
void *p = HeapAlloc(GetProcessHeap(), 0, size);
if (index == 40)
{
int t = 1;
}
if (index < kDebugSize)
{
a[index] = p;
index++;
}
if (p == 0)
throw CNewException();
printf("Alloc %6d, size = %8d\n", numAllocs, size);
return p;
}
class CC
{
public:
CC()
{
for (int i = 0; i < kDebugSize; i++)
a[i] = 0;
}
~CC()
{
for (int i = 0; i < kDebugSize; i++)
if (a[i] != 0)
return;
}
} g_CC;
void __cdecl operator delete(void *p)
{
if (p == 0)
return;
/*
for (int i = 0; i < index; i++)
if (a[i] == p)
a[i] = 0;
*/
HeapFree(GetProcessHeap(), 0, p);
numAllocs--;
printf("Free %d\n", numAllocs);
}
#endif
/*
int MemErrorVC(size_t)
{
throw CNewException();
// return 1;
}
CNewHandlerSetter::CNewHandlerSetter()
{
// MemErrorOldVCFunction = _set_new_handler(MemErrorVC);
}
CNewHandlerSetter::~CNewHandlerSetter()
{
// _set_new_handler(MemErrorOldVCFunction);
}
*/

View File

@@ -1,16 +0,0 @@
// Common/NewHandler.h
#ifndef __COMMON_NEWHANDLER_H
#define __COMMON_NEWHANDLER_H
class CNewException {};
#ifdef _WIN32
void
#ifdef _MSC_VER
__cdecl
#endif
operator delete(void *p) throw();
#endif
#endif

View File

@@ -1,9 +0,0 @@
// StdAfx.h
#ifndef __STDAFX_H
#define __STDAFX_H
// #include "MyWindows.h"
#include "NewHandler.h"
#endif

View File

@@ -1,19 +0,0 @@
// Common/Types.h
#ifndef __COMMON_TYPES_H
#define __COMMON_TYPES_H
typedef unsigned char Byte;
typedef short Int16;
typedef unsigned short UInt16;
typedef int Int32;
typedef unsigned int UInt32;
#ifdef _MSC_VER
typedef __int64 Int64;
typedef unsigned __int64 UInt64;
#else
typedef long long int Int64;
typedef unsigned long long int UInt64;
#endif
#endif

View File

@@ -1,539 +0,0 @@
/*
LzmaDecode.c
LZMA Decoder
LZMA SDK 4.01 Copyright (c) 1999-2004 Igor Pavlov (2004-02-15)
Converted to a state machine by Amir Szekely
*/
#include "LzmaCompatDecode.h"
#define LEAVE { goto saveStateAndReturn; }
#define NEED_BYTE(c) case c: if (!avail_in) { mode = c; LEAVE; }
#define NEED_BYTE_ if (!avail_in) LEAVE;
#define NEXT_BYTE (avail_in--, *next_in++)
#define NEED_OUT(c) case c: if (!avail_out) { mode = c; LEAVE; }
#define PUT_BYTE_(b) { *next_out = b; next_out++; avail_out--; }
#define PUT_BYTE(b) { totalOut++; PUT_BYTE_(b) }
#define DECODE_BIT(c, x) prob = x; last = c; goto _LZMA_C_RDBD; case c:
#define DECODE_LEN(c, x) probs = x; last2 = c; goto _LZMA_C_LEND; case c:
#define DECODE_BIT_TREE(c, x, y) probs = x; numLevels = y; last3 = c; goto _LZMA_C_BTD; case c:
enum {
/* 0 */ LZMA_C_INIT = 0,
/* 1 */ LZMA_C_GETDICT,
/* 2 */ LZMA_C_BLOCK,
/* 3 */ LZMA_C_RDI, /* RangeDecoderInit */
/* 4 */ LZMA_C_RDBD, /* RangeDecoderBitDecode */
/* 5 */ LZMA_C_RDBD_IN, /* RangeDecoderBitDecode */
/* 6 */ LZMA_C_TYPE,
/* 7 */ LZMA_C_ISREP,
/* 8 */ LZMA_C_ISREPG0,
/* 9 */ LZMA_C_ISREP0LONG,
/* 10 */ LZMA_C_ISREPG1,
/* 11 */ LZMA_C_ISREPG2,
/* 12 */ LZMA_C_NORM,
/* 13 */ LZMA_C_LITDM1, /* LzmaLiteralDecodeMatch */
/* 14 */ LZMA_C_LITDM2, /* LzmaLiteralDecodeMatch */
/* 15 */ LZMA_C_LITD, /* LzmaLiteralDecode */
/* 16 */ LZMA_C_RDRBTD, /* RangeDecoderReverseBitTreeDecode */
/* 17 */ LZMA_C_LEND, /* LzmaLenDecode */
/* 18 */ LZMA_C_LEND1, /* LzmaLenDecode */
/* 19 */ LZMA_C_LEND2, /* LzmaLenDecode */
/* 20 */ LZMA_C_LEND_RES, /* LzmaLenDecode */
/* 21 */ LZMA_C_LEND_C1,
/* 22 */ LZMA_C_LEND_C2,
/* 23 */ LZMA_C_BTD, /* RangeDecoderBitTreeDecode */
/* 24 */ LZMA_C_BTD_LOOP,
/* 25 */ LZMA_C_BTD_C1,
/* 26 */ LZMA_C_OUTPUT_1,
/* 27 */ LZMA_C_OUTPUT_2,
/* 28 */ LZMA_C_OUTPUT_3
};
#define kNumTopBits 24
#define kTopValue ((UInt32)1 << kNumTopBits)
#define kNumBitModelTotalBits 11
#define kBitModelTotal (1 << kNumBitModelTotalBits)
#define kNumMoveBits 5
#define RC_NORMALIZE(c) if (range < kTopValue) { NEED_BYTE(c); range <<= 8; code = (code << 8) | NEXT_BYTE; }
#define RC_GET_BIT2(c, prob, mi, A0, A1) { \
UInt32 bound = (range >> kNumBitModelTotalBits) * *prob; \
if (code < bound) \
{ A0; range = bound; *prob += (kBitModelTotal - *prob) >> kNumMoveBits; mi <<= 1; } \
else \
{ A1; range -= bound; code -= bound; *prob -= (*prob) >> kNumMoveBits; mi = (mi + mi) + 1; } \
RC_NORMALIZE(c) \
}
#define RC_GET_BIT(c, prob, mi) RC_GET_BIT2(c, prob, mi, ; , ;)
#define kNumPosBitsMax 4
#define kNumPosStatesMax (1 << kNumPosBitsMax)
#define kLenNumLowBits 3
#define kLenNumLowSymbols (1 << kLenNumLowBits)
#define kLenNumMidBits 3
#define kLenNumMidSymbols (1 << kLenNumMidBits)
#define kLenNumHighBits 8
#define kLenNumHighSymbols (1 << kLenNumHighBits)
#define LenChoice 0
#define LenChoice2 (LenChoice + 1)
#define LenLow (LenChoice2 + 1)
#define LenMid (LenLow + (kNumPosStatesMax << kLenNumLowBits))
#define LenHigh (LenMid + (kNumPosStatesMax << kLenNumMidBits))
#define kNumLenProbs (LenHigh + kLenNumHighSymbols)
#define kNumStates 12
#define kStartPosModelIndex 4
#define kEndPosModelIndex 14
#define kNumFullDistances (1 << (kEndPosModelIndex >> 1))
#define kNumPosSlotBits 6
#define kNumLenToPosStates 4
#define kNumAlignBits 4
#define kAlignTableSize (1 << kNumAlignBits)
#define kMatchMinLen 2
#define IsMatch 0
#define IsRep (IsMatch + (kNumStates << kNumPosBitsMax))
#define IsRepG0 (IsRep + kNumStates)
#define IsRepG1 (IsRepG0 + kNumStates)
#define IsRepG2 (IsRepG1 + kNumStates)
#define IsRep0Long (IsRepG2 + kNumStates)
#define PosSlot (IsRep0Long + (kNumStates << kNumPosBitsMax))
#define SpecPos (PosSlot + (kNumLenToPosStates << kNumPosSlotBits))
#define Align (SpecPos + kNumFullDistances - kEndPosModelIndex)
#define LenCoder (Align + kAlignTableSize)
#define RepLenCoder (LenCoder + kNumLenProbs)
#define Literal (RepLenCoder + kNumLenProbs)
#define LZMA_BASE_SIZE 1846
#define LZMA_LIT_SIZE 768
#if Literal != LZMA_BASE_SIZE
StopCompilingDueBUG
#endif
void LZMACALL lzmaCompatInit(lzma_stream *s)
{
/* size of lzma_stream minus the size of the two allocated buffer pointers.
we don't want to lose to pointer or else we won't be able to free them. */
SizeT i = sizeof(lzma_stream) - (sizeof(unsigned char *) * 2);
while (i--)
((Byte *)s)[i] = 0;
s->rep0 = s->rep1 = s->rep2 = s->rep3 = 1;
s->range = (0xFFFFFFFF);
}
int LZMACALL lzmaCompatDecode(lzma_stream *s)
{
/* restore decoder state */
lzma_stream _s = *s;
#define mode _s.mode
#define last _s.last
#define last2 _s.last2
#define last3 _s.last3
#define p ((CProb *) _s.dynamicData)
#define dynamicDataSize _s.dynamicDataSize
#define state _s.state
#define isPreviousMatch _s.isPreviousMatch
#define previousByte _s.previousByte
#define rep0 _s.rep0
#define rep1 _s.rep1
#define rep2 _s.rep2
#define rep3 _s.rep3
#define lc _s.lc
#define len _s.len
#define totalOut _s.totalOut
#define dictionary _s.dictionary
#define dictionarySize _s.dictionarySize
#define dictionaryPos _s.dictionaryPos
#define posStateMask _s.posStateMask
#define literalPosMask _s.literalPosMask
#define avail_in _s.avail_in
#define next_in _s.next_in
#define avail_out _s.avail_out
#define next_out _s.next_out
#define range _s.range
#define code _s.code
#define probs _s.probs
#define prob _s.prob
#define symbol _s.temp2
#define bit _s.temp3
#define matchBit _s.temp1
#define i _s.temp1
#define result _s.temp2
#define numLevels _s.temp3
#define posSlot _s.temp2
#define newDictionarySize ((UInt32) _s.temp3)
#define matchByte _s.matchByte
#define mi _s.mi
#define posState _s.posState
if (len == -1)
return LZMA_STREAM_END;
for (;;) switch (mode)
{
case LZMA_C_INIT:
{
Byte firstByte;
UInt32 newDynamicDataSize;
UInt32 numProbs;
int lp;
int pb;
NEED_BYTE_;
firstByte = NEXT_BYTE;
if (firstByte > (9*5*5))
return LZMA_DATA_ERROR;
pb = firstByte / (9*5);
firstByte %= (9*5);
lp = firstByte / 9;
firstByte %= 9;
lc = firstByte;
posStateMask = (1 << (pb)) - 1;
literalPosMask = (1 << (lp)) - 1;
numProbs = Literal + (LZMA_LIT_SIZE << (lc + pb));
newDynamicDataSize = numProbs * sizeof(CProb);
if (newDynamicDataSize != dynamicDataSize)
{
if (p)
lzmafree(p);
//p = lzmaalloc(newDynamicDataSize);
_s.dynamicData = lzmaalloc(newDynamicDataSize);
if (!p)
return LZMA_NOT_ENOUGH_MEM;
dynamicDataSize = newDynamicDataSize;
}
while (numProbs--)
p[numProbs] = kBitModelTotal >> 1;
//for (i = 0, newDictionarySize = 0; i < 4; i++)
for (i = 0, _s.temp3 = 0; i < 4; i++)
{
NEED_BYTE(LZMA_C_GETDICT);
//newDictionarySize |= NEXT_BYTE << (i * 8);
_s.temp3 |= NEXT_BYTE << (i * 8);
}
if (newDictionarySize != dictionarySize)
{
dictionarySize = newDictionarySize;
if (dictionary)
lzmafree(dictionary);
dictionary = lzmaalloc(dictionarySize);
if (!dictionary)
return LZMA_NOT_ENOUGH_MEM;
}
dictionary[dictionarySize - 1] = 0;
i = 5;
while (i--)
{
NEED_BYTE(LZMA_C_RDI);
code = (code << 8) | NEXT_BYTE;
}
}
case LZMA_C_BLOCK:
posState = (int)(totalOut & posStateMask);
DECODE_BIT(LZMA_C_TYPE, p + IsMatch + (state << kNumPosBitsMax) + posState);
if (bit == 0)
{
probs = p + Literal + (LZMA_LIT_SIZE *
(((totalOut & literalPosMask) << lc) + (previousByte >> (8 - lc))));
if (state < 4) state = 0;
else if (state < 10) state -= 3;
else state -= 6;
if (isPreviousMatch)
{
UInt32 pos = dictionaryPos - rep0;
if (pos >= dictionarySize)
pos += dictionarySize;
matchByte = dictionary[pos];
{
symbol = 1;
do
{
matchBit = (matchByte >> 7) & 1;
matchByte <<= 1;
{
prob = probs + ((1 + matchBit) << 8) + symbol;
RC_GET_BIT2(LZMA_C_LITDM1, prob, symbol, bit = 0, bit = 1)
}
if (matchBit != bit)
{
while (symbol < 0x100)
{
prob = probs + symbol;
RC_GET_BIT(LZMA_C_LITDM2, prob, symbol)
}
break;
}
}
while (symbol < 0x100);
previousByte = symbol;
}
isPreviousMatch = 0;
}
else
{
symbol = 1;
do
{
prob = probs + symbol;
RC_GET_BIT(LZMA_C_LITD, prob, symbol)
}
while (symbol < 0x100);
previousByte = symbol;
}
NEED_OUT(LZMA_C_OUTPUT_1);
PUT_BYTE(previousByte);
dictionary[dictionaryPos] = previousByte;
dictionaryPos = (dictionaryPos + 1) % dictionarySize;
}
/* bit == 1 */
else
{
isPreviousMatch = 1;
DECODE_BIT(LZMA_C_ISREP, p + IsRep + state);
if (bit == 1)
{
DECODE_BIT(LZMA_C_ISREPG0, p + IsRepG0 + state);
if (bit == 0)
{
DECODE_BIT(LZMA_C_ISREP0LONG, p + IsRep0Long + (state << kNumPosBitsMax) + posState);
if (bit == 0)
{
UInt32 pos;
if (totalOut == 0)
return LZMA_DATA_ERROR;
state = state < 7 ? 9 : 11;
NEED_OUT(LZMA_C_OUTPUT_2);
pos = dictionaryPos - rep0;
if (pos >= dictionarySize)
pos += dictionarySize;
previousByte = dictionary[pos];
dictionary[dictionaryPos] = previousByte;
dictionaryPos = (dictionaryPos + 1) % dictionarySize;
PUT_BYTE(previousByte);
mode = LZMA_C_BLOCK;
break;
}
}
else
{
UInt32 distance;
DECODE_BIT(LZMA_C_ISREPG1, p + IsRepG1 + state);
if (bit == 0)
{
distance = rep1;
}
else
{
DECODE_BIT(LZMA_C_ISREPG2, p + IsRepG2 + state);
if (bit == 0)
distance = rep2;
else
{
distance = rep3;
rep3 = rep2;
}
rep2 = rep1;
}
rep1 = rep0;
rep0 = distance;
}
DECODE_LEN(LZMA_C_LEND_C1, p + RepLenCoder);
state = state < 7 ? 8 : 11;
}
else
{
rep3 = rep2;
rep2 = rep1;
rep1 = rep0;
state = state < 7 ? 7 : 10;
DECODE_LEN(LZMA_C_LEND_C2, p + LenCoder);
DECODE_BIT_TREE(
LZMA_C_BTD_C1,
p + PosSlot + ((len < kNumLenToPosStates ? len : kNumLenToPosStates - 1) << kNumPosSlotBits),
kNumPosSlotBits
);
if (posSlot >= kStartPosModelIndex)
{
int numDirectBits = ((posSlot >> 1) - 1);
rep0 = ((2 | ((UInt32)posSlot & 1)) << numDirectBits);
if (posSlot < kEndPosModelIndex)
{
probs = p + SpecPos + rep0 - posSlot - 1;
numLevels = numDirectBits;
}
else
{
int numTotalBits = numDirectBits - kNumAlignBits;
result = 0;
for (i = numTotalBits; i > 0; i--)
{
/* UInt32 t; */
range >>= 1;
result <<= 1;
if (code >= range)
{
code -= range;
result |= 1;
}
/*
t = (code - range) >> 31;
t &= 1;
code -= range & (t - 1);
result = (result + result) | (1 - t);
*/
RC_NORMALIZE(LZMA_C_NORM)
}
rep0 += result << kNumAlignBits;
probs = p + Align;
numLevels = kNumAlignBits;
}
mi = 1;
symbol = 0;
for(i = 0; i < numLevels; i++)
{
prob = probs + mi;
RC_GET_BIT2(LZMA_C_RDRBTD, prob, mi, ; , symbol |= (1 << i));
}
rep0 += symbol;
}
else
rep0 = posSlot;
rep0++;
}
if (rep0 == (UInt32)(0))
{
len = -1;
LEAVE;
}
if (rep0 > totalOut)
{
return LZMA_DATA_ERROR;
}
len += kMatchMinLen;
do
{
UInt32 pos;
NEED_OUT(LZMA_C_OUTPUT_3);
pos = dictionaryPos - rep0;
if (pos >= dictionarySize)
pos += dictionarySize;
previousByte = dictionary[pos];
dictionary[dictionaryPos] = previousByte;
dictionaryPos = (dictionaryPos + 1) % dictionarySize;
PUT_BYTE(previousByte);
len--;
}
while(len > 0);
}
mode = LZMA_C_BLOCK;
break;
case LZMA_C_RDBD:
_LZMA_C_RDBD:
{
UInt32 bound = (range >> kNumBitModelTotalBits) * *prob;
if (code < bound)
{
range = bound;
*prob += (kBitModelTotal - *prob) >> kNumMoveBits;
bit = 0;
}
else
{
range -= bound;
code -= bound;
*prob -= (*prob) >> kNumMoveBits;
bit = 1;
}
RC_NORMALIZE(LZMA_C_RDBD_IN);
}
mode = last;
break;
case LZMA_C_LEND:
_LZMA_C_LEND:
DECODE_BIT(LZMA_C_LEND1, probs + LenChoice);
if (bit == 0)
{
len = 0;
probs += LenLow + (posState << kLenNumLowBits);
numLevels = kLenNumLowBits;
}
else {
DECODE_BIT(LZMA_C_LEND2, probs + LenChoice2);
if (bit == 0)
{
len = kLenNumLowSymbols;
probs += + LenMid + (posState << kLenNumMidBits);
numLevels = kLenNumMidBits;
}
else
{
len = kLenNumLowSymbols + kLenNumMidSymbols;
probs += LenHigh;
numLevels = kLenNumHighBits;
}
}
last3 = LZMA_C_LEND_RES;
case LZMA_C_BTD:
_LZMA_C_BTD:
mi = 1;
for(i = numLevels; i > 0; i--)
{
prob = probs + mi;
RC_GET_BIT(LZMA_C_BTD_LOOP, prob, mi)
}
result = mi - (1 << numLevels);
mode = last3;
break;
case LZMA_C_LEND_RES:
len += result;
mode = last2;
break;
default:
return LZMA_DATA_ERROR;
}
saveStateAndReturn:
/* save decoder state */
*s = _s;
return LZMA_OK;
}

View File

@@ -1,135 +0,0 @@
/*
LzmaDecode.h
LZMA Decoder interface
LZMA SDK 4.01 Copyright (c) 1999-2004 Igor Pavlov (2004-02-15)
Converted to a state machine by Amir Szekely
*/
#ifndef __LZMADECODE_H
#define __LZMADECODE_H
#include "LzmaTypes.h"
/***********************
* Configuration *
***********************/
/* #define _LZMA_PROB32 */
/* It can increase speed on some 32-bit CPUs,
but memory usage will be doubled in that case */
/***********************
* Configuration End *
***********************/
#ifdef __cplusplus
extern "C" {
#endif
#ifndef lzmaalloc
#define lzmaalloc malloc
#endif
#ifndef lzmafree
#define lzmafree free
#endif
#ifndef LZMACALL
# define LZMACALL
#endif
#ifndef malloc
#include <malloc.h>
#endif
#ifndef UInt32
#ifdef _LZMA_UINT32_IS_ULONG
#define UInt32 unsigned long
#else
#define UInt32 unsigned int
#endif
#endif
#ifndef SizeT
#ifdef _LZMA_SYSTEM_SIZE_T
#include <stddef.h>
#define SizeT size_t
#else
#define SizeT UInt32
#endif
#endif
#ifndef CProb
#ifdef _LZMA_PROB32
#define CProb UInt32
#else
#define CProb unsigned short
#endif
#endif
#define LZMA_STREAM_END 1
#define LZMA_OK 0
#define LZMA_DATA_ERROR -1
#define LZMA_NOT_ENOUGH_MEM -2
typedef struct
{
/* mode control */
int mode;
int last;
int last2;
int last3;
/* properties */
UInt32 dynamicDataSize;
UInt32 dictionarySize;
/* io */
Byte *next_in; /* next input byte */
UInt32 avail_in; /* number of bytes available at next_in */
Byte *next_out; /* next output byte should be put there */
UInt32 avail_out; /* remaining free space at next_out */
UInt32 totalOut; /* total output */
/* saved state */
Byte previousByte;
Byte matchByte;
CProb *probs;
CProb *prob;
int mi;
int posState;
int temp1;
int temp2;
int temp3;
int lc;
int state;
int isPreviousMatch;
int len;
UInt32 rep0;
UInt32 rep1;
UInt32 rep2;
UInt32 rep3;
UInt32 posStateMask;
UInt32 literalPosMask;
UInt32 dictionaryPos;
/* range coder */
UInt32 range;
UInt32 code;
/* allocated buffers */
Byte *dictionary;
Byte *dynamicData;
} lzma_stream;
void LZMACALL lzmaCompatInit(lzma_stream *);
int LZMACALL lzmaCompatDecode(lzma_stream *);
#ifdef __cplusplus
}
#endif
#endif

View File

@@ -1,521 +0,0 @@
/*
LzmaStateDecode.c
LZMA Decoder (State version)
LZMA SDK 4.40 Copyright (c) 1999-2006 Igor Pavlov (2006-05-01)
http://www.7-zip.org/
LZMA SDK is licensed under two licenses:
1) GNU Lesser General Public License (GNU LGPL)
2) Common Public License (CPL)
It means that you can select one of these two licenses and
follow rules of that license.
SPECIAL EXCEPTION:
Igor Pavlov, as the author of this Code, expressly permits you to
statically or dynamically link your Code (or bind by name) to the
interfaces of this file without subjecting your linked Code to the
terms of the CPL or GNU LGPL. Any modifications or additions
to this file, however, are subject to the LGPL or CPL terms.
*/
#include "LzmaStateDecode.h"
#define kNumTopBits 24
#define kTopValue ((UInt32)1 << kNumTopBits)
#define kNumBitModelTotalBits 11
#define kBitModelTotal (1 << kNumBitModelTotalBits)
#define kNumMoveBits 5
#define RC_READ_BYTE (*Buffer++)
#define RC_INIT Code = 0; Range = 0xFFFFFFFF; \
{ int i; for(i = 0; i < 5; i++) { Code = (Code << 8) | RC_READ_BYTE; }}
#define RC_NORMALIZE if (Range < kTopValue) { Range <<= 8; Code = (Code << 8) | RC_READ_BYTE; }
#define IfBit0(p) RC_NORMALIZE; bound = (Range >> kNumBitModelTotalBits) * *(p); if (Code < bound)
#define UpdateBit0(p) Range = bound; *(p) += (kBitModelTotal - *(p)) >> kNumMoveBits;
#define UpdateBit1(p) Range -= bound; Code -= bound; *(p) -= (*(p)) >> kNumMoveBits;
#define RC_GET_BIT2(p, mi, A0, A1) IfBit0(p) \
{ UpdateBit0(p); mi <<= 1; A0; } else \
{ UpdateBit1(p); mi = (mi + mi) + 1; A1; }
#define RC_GET_BIT(p, mi) RC_GET_BIT2(p, mi, ; , ;)
#define RangeDecoderBitTreeDecode(probs, numLevels, res) \
{ int i = numLevels; res = 1; \
do { CProb *p = probs + res; RC_GET_BIT(p, res) } while(--i != 0); \
res -= (1 << numLevels); }
#define kNumPosBitsMax 4
#define kNumPosStatesMax (1 << kNumPosBitsMax)
#define kLenNumLowBits 3
#define kLenNumLowSymbols (1 << kLenNumLowBits)
#define kLenNumMidBits 3
#define kLenNumMidSymbols (1 << kLenNumMidBits)
#define kLenNumHighBits 8
#define kLenNumHighSymbols (1 << kLenNumHighBits)
#define LenChoice 0
#define LenChoice2 (LenChoice + 1)
#define LenLow (LenChoice2 + 1)
#define LenMid (LenLow + (kNumPosStatesMax << kLenNumLowBits))
#define LenHigh (LenMid + (kNumPosStatesMax << kLenNumMidBits))
#define kNumLenProbs (LenHigh + kLenNumHighSymbols)
#define kNumStates 12
#define kNumLitStates 7
#define kStartPosModelIndex 4
#define kEndPosModelIndex 14
#define kNumFullDistances (1 << (kEndPosModelIndex >> 1))
#define kNumPosSlotBits 6
#define kNumLenToPosStates 4
#define kNumAlignBits 4
#define kAlignTableSize (1 << kNumAlignBits)
#define kMatchMinLen 2
#define IsMatch 0
#define IsRep (IsMatch + (kNumStates << kNumPosBitsMax))
#define IsRepG0 (IsRep + kNumStates)
#define IsRepG1 (IsRepG0 + kNumStates)
#define IsRepG2 (IsRepG1 + kNumStates)
#define IsRep0Long (IsRepG2 + kNumStates)
#define PosSlot (IsRep0Long + (kNumStates << kNumPosBitsMax))
#define SpecPos (PosSlot + (kNumLenToPosStates << kNumPosSlotBits))
#define Align (SpecPos + kNumFullDistances - kEndPosModelIndex)
#define LenCoder (Align + kAlignTableSize)
#define RepLenCoder (LenCoder + kNumLenProbs)
#define Literal (RepLenCoder + kNumLenProbs)
#if Literal != LZMA_BASE_SIZE
StopCompilingDueBUG
#endif
/* kRequiredInBufferSize = number of required input bytes for worst case:
longest match with longest distance.
kLzmaInBufferSize must be larger than kRequiredInBufferSize
23 bits = 2 (match select) + 10 (len) + 6 (distance) + 4(align) + 1 (RC_NORMALIZE)
*/
#define kRequiredInBufferSize ((23 * (kNumBitModelTotalBits - kNumMoveBits + 1) + 26 + 9) / 8)
#define kLzmaStreamWasFinishedId (-1)
int LzmaDecodeProperties(CLzmaProperties *propsRes, const unsigned char *propsData, int size)
{
unsigned char prop0;
if (size < LZMA_PROPERTIES_SIZE)
return LZMA_RESULT_DATA_ERROR;
prop0 = propsData[0];
if (prop0 >= (9 * 5 * 5))
return LZMA_RESULT_DATA_ERROR;
{
for (propsRes->pb = 0; prop0 >= (9 * 5); propsRes->pb++, prop0 -= (9 * 5));
for (propsRes->lp = 0; prop0 >= 9; propsRes->lp++, prop0 -= 9);
propsRes->lc = prop0;
/*
unsigned char remainder = (unsigned char)(prop0 / 9);
propsRes->lc = prop0 % 9;
propsRes->pb = remainder / 5;
propsRes->lp = remainder % 5;
*/
}
{
int i;
propsRes->DictionarySize = 0;
for (i = 0; i < 4; i++)
propsRes->DictionarySize += (UInt32)(propsData[1 + i]) << (i * 8);
if (propsRes->DictionarySize == 0)
propsRes->DictionarySize = 1;
return LZMA_RESULT_OK;
}
}
int LzmaDecode(
CLzmaDecoderState *vs,
const unsigned char *inStream, SizeT inSize, SizeT *inSizeProcessed,
unsigned char *outStream, SizeT outSize, SizeT *outSizeProcessed,
int finishDecoding)
{
UInt32 Range = vs->Range;
UInt32 Code = vs->Code;
unsigned char *Buffer = vs->Buffer;
int BufferSize = vs->BufferSize; /* don't change it to unsigned int */
CProb *p = vs->Probs;
int state = vs->State;
unsigned char previousByte;
UInt32 rep0 = vs->Reps[0], rep1 = vs->Reps[1], rep2 = vs->Reps[2], rep3 = vs->Reps[3];
SizeT nowPos = 0;
UInt32 posStateMask = (1 << (vs->Properties.pb)) - 1;
UInt32 literalPosMask = (1 << (vs->Properties.lp)) - 1;
int lc = vs->Properties.lc;
int len = vs->RemainLen;
UInt32 globalPos = vs->GlobalPos;
UInt32 distanceLimit = vs->DistanceLimit;
unsigned char *dictionary = vs->Dictionary;
UInt32 dictionarySize = vs->Properties.DictionarySize;
UInt32 dictionaryPos = vs->DictionaryPos;
unsigned char tempDictionary[4];
(*inSizeProcessed) = 0;
(*outSizeProcessed) = 0;
if (len == kLzmaStreamWasFinishedId)
return LZMA_RESULT_OK;
if (dictionarySize == 0)
{
dictionary = tempDictionary;
dictionarySize = 1;
tempDictionary[0] = vs->TempDictionary[0];
}
if (len == kLzmaNeedInitId)
{
while (inSize > 0 && BufferSize < kLzmaInBufferSize)
{
Buffer[BufferSize++] = *inStream++;
(*inSizeProcessed)++;
inSize--;
}
if (BufferSize < 5)
{
vs->BufferSize = BufferSize;
return finishDecoding ? LZMA_RESULT_DATA_ERROR : LZMA_RESULT_OK;
}
{
UInt32 numProbs = Literal + ((UInt32)LZMA_LIT_SIZE << (lc + vs->Properties.lp));
UInt32 i;
for (i = 0; i < numProbs; i++)
p[i] = kBitModelTotal >> 1;
rep0 = rep1 = rep2 = rep3 = 1;
state = 0;
globalPos = 0;
distanceLimit = 0;
dictionaryPos = 0;
dictionary[dictionarySize - 1] = 0;
RC_INIT;
}
len = 0;
}
while(len != 0 && nowPos < outSize)
{
UInt32 pos = dictionaryPos - rep0;
if (pos >= dictionarySize)
pos += dictionarySize;
outStream[nowPos++] = dictionary[dictionaryPos] = dictionary[pos];
if (++dictionaryPos == dictionarySize)
dictionaryPos = 0;
len--;
}
if (dictionaryPos == 0)
previousByte = dictionary[dictionarySize - 1];
else
previousByte = dictionary[dictionaryPos - 1];
while(1)
{
int bufferPos = (int)(Buffer - vs->Buffer);
if (BufferSize - bufferPos < kRequiredInBufferSize)
{
int i;
BufferSize -= bufferPos;
if (BufferSize < 0)
return LZMA_RESULT_DATA_ERROR;
for (i = 0; i < BufferSize; i++)
vs->Buffer[i] = Buffer[i];
Buffer = vs->Buffer;
while (inSize > 0 && BufferSize < kLzmaInBufferSize)
{
Buffer[BufferSize++] = *inStream++;
(*inSizeProcessed)++;
inSize--;
}
if (BufferSize < kRequiredInBufferSize && !finishDecoding)
break;
}
if (nowPos >= outSize)
break;
{
CProb *prob;
UInt32 bound;
int posState = (int)((nowPos + globalPos) & posStateMask);
prob = p + IsMatch + (state << kNumPosBitsMax) + posState;
IfBit0(prob)
{
int symbol = 1;
UpdateBit0(prob)
prob = p + Literal + (LZMA_LIT_SIZE *
((((nowPos + globalPos)& literalPosMask) << lc) + (previousByte >> (8 - lc))));
if (state >= kNumLitStates)
{
int matchByte;
UInt32 pos = dictionaryPos - rep0;
if (pos >= dictionarySize)
pos += dictionarySize;
matchByte = dictionary[pos];
do
{
int bit;
CProb *probLit;
matchByte <<= 1;
bit = (matchByte & 0x100);
probLit = prob + 0x100 + bit + symbol;
RC_GET_BIT2(probLit, symbol, if (bit != 0) break, if (bit == 0) break)
}
while (symbol < 0x100);
}
while (symbol < 0x100)
{
CProb *probLit = prob + symbol;
RC_GET_BIT(probLit, symbol)
}
previousByte = (unsigned char)symbol;
outStream[nowPos++] = previousByte;
if (distanceLimit < dictionarySize)
distanceLimit++;
dictionary[dictionaryPos] = previousByte;
if (++dictionaryPos == dictionarySize)
dictionaryPos = 0;
if (state < 4) state = 0;
else if (state < 10) state -= 3;
else state -= 6;
}
else
{
UpdateBit1(prob);
prob = p + IsRep + state;
IfBit0(prob)
{
UpdateBit0(prob);
rep3 = rep2;
rep2 = rep1;
rep1 = rep0;
state = state < kNumLitStates ? 0 : 3;
prob = p + LenCoder;
}
else
{
UpdateBit1(prob);
prob = p + IsRepG0 + state;
IfBit0(prob)
{
UpdateBit0(prob);
prob = p + IsRep0Long + (state << kNumPosBitsMax) + posState;
IfBit0(prob)
{
UInt32 pos;
UpdateBit0(prob);
if (distanceLimit == 0)
return LZMA_RESULT_DATA_ERROR;
if (distanceLimit < dictionarySize)
distanceLimit++;
state = state < kNumLitStates ? 9 : 11;
pos = dictionaryPos - rep0;
if (pos >= dictionarySize)
pos += dictionarySize;
previousByte = dictionary[pos];
dictionary[dictionaryPos] = previousByte;
if (++dictionaryPos == dictionarySize)
dictionaryPos = 0;
outStream[nowPos++] = previousByte;
continue;
}
else
{
UpdateBit1(prob);
}
}
else
{
UInt32 distance;
UpdateBit1(prob);
prob = p + IsRepG1 + state;
IfBit0(prob)
{
UpdateBit0(prob);
distance = rep1;
}
else
{
UpdateBit1(prob);
prob = p + IsRepG2 + state;
IfBit0(prob)
{
UpdateBit0(prob);
distance = rep2;
}
else
{
UpdateBit1(prob);
distance = rep3;
rep3 = rep2;
}
rep2 = rep1;
}
rep1 = rep0;
rep0 = distance;
}
state = state < kNumLitStates ? 8 : 11;
prob = p + RepLenCoder;
}
{
int numBits, offset;
CProb *probLen = prob + LenChoice;
IfBit0(probLen)
{
UpdateBit0(probLen);
probLen = prob + LenLow + (posState << kLenNumLowBits);
offset = 0;
numBits = kLenNumLowBits;
}
else
{
UpdateBit1(probLen);
probLen = prob + LenChoice2;
IfBit0(probLen)
{
UpdateBit0(probLen);
probLen = prob + LenMid + (posState << kLenNumMidBits);
offset = kLenNumLowSymbols;
numBits = kLenNumMidBits;
}
else
{
UpdateBit1(probLen);
probLen = prob + LenHigh;
offset = kLenNumLowSymbols + kLenNumMidSymbols;
numBits = kLenNumHighBits;
}
}
RangeDecoderBitTreeDecode(probLen, numBits, len);
len += offset;
}
if (state < 4)
{
int posSlot;
state += kNumLitStates;
prob = p + PosSlot +
((len < kNumLenToPosStates ? len : kNumLenToPosStates - 1) <<
kNumPosSlotBits);
RangeDecoderBitTreeDecode(prob, kNumPosSlotBits, posSlot);
if (posSlot >= kStartPosModelIndex)
{
int numDirectBits = ((posSlot >> 1) - 1);
rep0 = (2 | ((UInt32)posSlot & 1));
if (posSlot < kEndPosModelIndex)
{
rep0 <<= numDirectBits;
prob = p + SpecPos + rep0 - posSlot - 1;
}
else
{
numDirectBits -= kNumAlignBits;
do
{
RC_NORMALIZE
Range >>= 1;
rep0 <<= 1;
if (Code >= Range)
{
Code -= Range;
rep0 |= 1;
}
}
while (--numDirectBits != 0);
prob = p + Align;
rep0 <<= kNumAlignBits;
numDirectBits = kNumAlignBits;
}
{
int i = 1;
int mi = 1;
do
{
CProb *prob3 = prob + mi;
RC_GET_BIT2(prob3, mi, ; , rep0 |= i);
i <<= 1;
}
while(--numDirectBits != 0);
}
}
else
rep0 = posSlot;
if (++rep0 == (UInt32)(0))
{
/* it's for stream version */
len = kLzmaStreamWasFinishedId;
break;
}
}
len += kMatchMinLen;
if (rep0 > distanceLimit)
return LZMA_RESULT_DATA_ERROR;
if (dictionarySize - distanceLimit > (UInt32)len)
distanceLimit += len;
else
distanceLimit = dictionarySize;
do
{
UInt32 pos = dictionaryPos - rep0;
if (pos >= dictionarySize)
pos += dictionarySize;
previousByte = dictionary[pos];
dictionary[dictionaryPos] = previousByte;
if (++dictionaryPos == dictionarySize)
dictionaryPos = 0;
len--;
outStream[nowPos++] = previousByte;
}
while(len != 0 && nowPos < outSize);
}
}
}
RC_NORMALIZE;
BufferSize -= (int)(Buffer - vs->Buffer);
if (BufferSize < 0)
return LZMA_RESULT_DATA_ERROR;
{
int i;
for (i = 0; i < BufferSize; i++)
vs->Buffer[i] = Buffer[i];
}
vs->BufferSize = BufferSize;
vs->Range = Range;
vs->Code = Code;
vs->DictionaryPos = dictionaryPos;
vs->GlobalPos = (UInt32)(globalPos + nowPos);
vs->DistanceLimit = distanceLimit;
vs->Reps[0] = rep0;
vs->Reps[1] = rep1;
vs->Reps[2] = rep2;
vs->Reps[3] = rep3;
vs->State = state;
vs->RemainLen = len;
vs->TempDictionary[0] = tempDictionary[0];
(*outSizeProcessed) = nowPos;
return LZMA_RESULT_OK;
}

View File

@@ -1,96 +0,0 @@
/*
LzmaStateDecode.h
LZMA Decoder interface (State version)
LZMA SDK 4.40 Copyright (c) 1999-2006 Igor Pavlov (2006-05-01)
http://www.7-zip.org/
LZMA SDK is licensed under two licenses:
1) GNU Lesser General Public License (GNU LGPL)
2) Common Public License (CPL)
It means that you can select one of these two licenses and
follow rules of that license.
SPECIAL EXCEPTION:
Igor Pavlov, as the author of this code, expressly permits you to
statically or dynamically link your code (or bind by name) to the
interfaces of this file without subjecting your linked code to the
terms of the CPL or GNU LGPL. Any modifications or additions
to this file, however, are subject to the LGPL or CPL terms.
*/
#ifndef __LZMASTATEDECODE_H
#define __LZMASTATEDECODE_H
#include "LzmaTypes.h"
/* #define _LZMA_PROB32 */
/* It can increase speed on some 32-bit CPUs,
but memory usage will be doubled in that case */
#ifdef _LZMA_PROB32
#define CProb UInt32
#else
#define CProb UInt16
#endif
#define LZMA_RESULT_OK 0
#define LZMA_RESULT_DATA_ERROR 1
#define LZMA_BASE_SIZE 1846
#define LZMA_LIT_SIZE 768
#define LZMA_PROPERTIES_SIZE 5
typedef struct _CLzmaProperties
{
int lc;
int lp;
int pb;
UInt32 DictionarySize;
}CLzmaProperties;
int LzmaDecodeProperties(CLzmaProperties *propsRes, const unsigned char *propsData, int size);
#define LzmaGetNumProbs(lzmaProps) (LZMA_BASE_SIZE + (LZMA_LIT_SIZE << ((lzmaProps)->lc + (lzmaProps)->lp)))
#define kLzmaInBufferSize 64 /* don't change it. it must be larger than kRequiredInBufferSize */
#define kLzmaNeedInitId (-2)
typedef struct _CLzmaDecoderState
{
CLzmaProperties Properties;
CProb *Probs;
unsigned char *Dictionary;
unsigned char Buffer[kLzmaInBufferSize];
int BufferSize;
UInt32 Range;
UInt32 Code;
UInt32 DictionaryPos;
UInt32 GlobalPos;
UInt32 DistanceLimit;
UInt32 Reps[4];
int State;
int RemainLen; /* -2: decoder needs internal initialization
-1: stream was finished,
0: ok
> 0: need to write RemainLen bytes as match Reps[0],
*/
unsigned char TempDictionary[4]; /* it's required when DictionarySize = 0 */
} CLzmaDecoderState;
#define LzmaDecoderInit(vs) { (vs)->RemainLen = kLzmaNeedInitId; (vs)->BufferSize = 0; }
/* LzmaDecode: decoding from input stream to output stream.
If finishDecoding != 0, then there are no more bytes in input stream
after inStream[inSize - 1]. */
int LzmaDecode(CLzmaDecoderState *vs,
const unsigned char *inStream, SizeT inSize, SizeT *inSizeProcessed,
unsigned char *outStream, SizeT outSize, SizeT *outSizeProcessed,
int finishDecoding);
#endif

View File

@@ -1,32 +0,0 @@
/*
LzmaTypes.h
Types for LZMA Decoder
This file written and distributed to public domain by Igor Pavlov.
This file is part of LZMA SDK 4.40 (2006-05-01)
*/
#ifndef __LZMATYPES_H
#define __LZMATYPES_H
typedef unsigned char Byte;
typedef unsigned short UInt16;
#ifdef _LZMA_UINT32_IS_ULONG
typedef unsigned long UInt32;
#else
typedef unsigned int UInt32;
#endif
/* #define _LZMA_SYSTEM_SIZE_T */
/* Use system's size_t. You can use it to enable 64-bit sizes supporting */
#ifdef _LZMA_SYSTEM_SIZE_T
#include <stddef.h>
typedef size_t SizeT;
#else
typedef UInt32 SizeT;
#endif
#endif

View File

@@ -1,18 +0,0 @@
// Windows/Defs.h
#ifndef __WINDOWS_DEFS_H
#define __WINDOWS_DEFS_H
inline bool BOOLToBool(BOOL value)
{ return (value != FALSE); }
inline BOOL BoolToBOOL(bool value)
{ return (value ? TRUE: FALSE); }
inline VARIANT_BOOL BoolToVARIANT_BOOL(bool value)
{ return (value ? VARIANT_TRUE: VARIANT_FALSE); }
inline bool VARIANT_BOOLToBool(VARIANT_BOOL value)
{ return (value != VARIANT_FALSE); }
#endif

View File

@@ -1,37 +0,0 @@
// Windows/Handle.h
#ifndef __WINDOWS_HANDLE_H
#define __WINDOWS_HANDLE_H
namespace NWindows {
class CHandle
{
protected:
HANDLE _handle;
public:
operator HANDLE() { return _handle; }
CHandle(): _handle(NULL) {}
~CHandle() { Close(); }
bool Close()
{
if (_handle == NULL)
return true;
if (!::CloseHandle(_handle))
return false;
_handle = NULL;
return true;
}
void Attach(HANDLE handle)
{ _handle = handle; }
HANDLE Detach()
{
HANDLE handle = _handle;
_handle = NULL;
return handle;
}
};
}
#endif

View File

@@ -1,9 +0,0 @@
// StdAfx.h
#ifndef __STDAFX_H
#define __STDAFX_H
#include "../Common/MyWindows.h"
#include "../Common/NewHandler.h"
#endif

View File

@@ -1,17 +0,0 @@
// Windows/Synchronization.cpp
#include "StdAfx.h"
#include "Synchronization.h"
namespace NWindows {
namespace NSynchronization {
CEvent::CEvent(bool manualReset, bool initiallyOwn, LPCTSTR name,
LPSECURITY_ATTRIBUTES securityAttributes)
{
if (!Create(manualReset, initiallyOwn, name, securityAttributes))
throw "CreateEvent error";
}
}}

View File

@@ -1,114 +0,0 @@
// Windows/Synchronization.h
#ifndef __WINDOWS_SYNCHRONIZATION_H
#define __WINDOWS_SYNCHRONIZATION_H
#include "Defs.h"
#include "Handle.h"
namespace NWindows {
namespace NSynchronization {
class CObject: public CHandle
{
public:
bool Lock(DWORD timeoutInterval = INFINITE)
{ return (::WaitForSingleObject(_handle, timeoutInterval) == WAIT_OBJECT_0); }
};
class CBaseEvent: public CObject
{
public:
bool Create(bool manualReset, bool initiallyOwn, LPCTSTR name = NULL,
LPSECURITY_ATTRIBUTES securityAttributes = NULL)
{
_handle = ::CreateEvent(securityAttributes, BoolToBOOL(manualReset),
BoolToBOOL(initiallyOwn), name);
return (_handle != 0);
}
bool Open(DWORD desiredAccess, bool inheritHandle, LPCTSTR name)
{
_handle = ::OpenEvent(desiredAccess, BoolToBOOL(inheritHandle), name);
return (_handle != 0);
}
bool Set() { return BOOLToBool(::SetEvent(_handle)); }
bool Pulse() { return BOOLToBool(::PulseEvent(_handle)); }
bool Reset() { return BOOLToBool(::ResetEvent(_handle)); }
};
class CEvent: public CBaseEvent
{
public:
CEvent() {};
CEvent(bool manualReset, bool initiallyOwn,
LPCTSTR name = NULL, LPSECURITY_ATTRIBUTES securityAttributes = NULL);
};
class CManualResetEvent: public CEvent
{
public:
CManualResetEvent(bool initiallyOwn = false, LPCTSTR name = NULL,
LPSECURITY_ATTRIBUTES securityAttributes = NULL):
CEvent(true, initiallyOwn, name, securityAttributes) {};
};
class CAutoResetEvent: public CEvent
{
public:
CAutoResetEvent(bool initiallyOwn = false, LPCTSTR name = NULL,
LPSECURITY_ATTRIBUTES securityAttributes = NULL):
CEvent(false, initiallyOwn, name, securityAttributes) {};
};
class CMutex: public CObject
{
public:
bool Create(bool initiallyOwn, LPCTSTR name = NULL,
LPSECURITY_ATTRIBUTES securityAttributes = NULL)
{
_handle = ::CreateMutex(securityAttributes, BoolToBOOL(initiallyOwn), name);
return (_handle != 0);
}
bool Open(DWORD desiredAccess, bool inheritHandle, LPCTSTR name)
{
_handle = ::OpenMutex(desiredAccess, BoolToBOOL(inheritHandle), name);
return (_handle != 0);
}
bool Release() { return BOOLToBool(::ReleaseMutex(_handle)); }
};
class CMutexLock
{
CMutex &_object;
public:
CMutexLock(CMutex &object): _object(object) { _object.Lock(); }
~CMutexLock() { _object.Release(); }
};
class CCriticalSection
{
CRITICAL_SECTION _object;
// void Initialize() { ::InitializeCriticalSection(&_object); }
// void Delete() { ::DeleteCriticalSection(&_object); }
public:
CCriticalSection() { ::InitializeCriticalSection(&_object); }
~CCriticalSection() { ::DeleteCriticalSection(&_object); }
void Enter() { ::EnterCriticalSection(&_object); }
void Leave() { ::LeaveCriticalSection(&_object); }
};
class CCriticalSectionLock
{
CCriticalSection &_object;
void Unlock() { _object.Leave(); }
public:
CCriticalSectionLock(CCriticalSection &object): _object(object)
{_object.Enter(); }
~CCriticalSectionLock() { Unlock(); }
};
}}
#endif

View File

@@ -1,52 +0,0 @@
// Windows/Thread.h
#ifndef __WINDOWS_THREAD_H
#define __WINDOWS_THREAD_H
#include "Handle.h"
#include "Defs.h"
namespace NWindows {
class CThread: public CHandle
{
bool IsOpen() const { return _handle != 0; }
public:
bool Create(LPSECURITY_ATTRIBUTES threadAttributes,
SIZE_T stackSize, LPTHREAD_START_ROUTINE startAddress,
LPVOID parameter, DWORD creationFlags, LPDWORD threadId)
{
_handle = ::CreateThread(threadAttributes, stackSize, startAddress,
parameter, creationFlags, threadId);
return (_handle != NULL);
}
bool Create(LPTHREAD_START_ROUTINE startAddress, LPVOID parameter)
{
DWORD threadId;
return Create(NULL, 0, startAddress, parameter, 0, &threadId);
}
DWORD Resume()
{ return ::ResumeThread(_handle); }
DWORD Suspend()
{ return ::SuspendThread(_handle); }
bool Terminate(DWORD exitCode)
{ return BOOLToBool(::TerminateThread(_handle, exitCode)); }
int GetPriority()
{ return ::GetThreadPriority(_handle); }
bool SetPriority(int priority)
{ return BOOLToBool(::SetThreadPriority(_handle, priority)); }
bool Wait()
{
if (!IsOpen())
return true;
return (::WaitForSingleObject(_handle, INFINITE) == WAIT_OBJECT_0);
}
};
}
#endif

View File

@@ -1,504 +0,0 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
not price. Our General Public Licenses are designed to make sure that
you have the freedom to distribute copies of free software (and charge
for this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser General Public License from time to time.
Such new versions will be similar in spirit to the present version,
but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Libraries
If you develop a new library, and you want it to be of the greatest
possible use to the public, we recommend making it free software that
everyone can redistribute and change. You can do so by permitting
redistribution under these terms (or, alternatively, under the terms of the
ordinary General Public License).
To apply these terms, attach the following notices to the library. It is
safest to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.
<one line to give the library's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Also add information on how to contact you by electronic and paper mail.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the library, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the
library `Frob' (a library for tweaking knobs) written by James Random Hacker.
<signature of Ty Coon>, 1 April 1990
Ty Coon, President of Vice
That's all there is to it!

View File

@@ -1,226 +0,0 @@
7-Zip 4.42 Sources
------------------
7-Zip is a file archiver for Windows 95/98/ME/NT/2000/2003/XP.
7-Zip Copyright (C) 1999-2006 Igor Pavlov.
License Info
------------
Most of 7-Zip source code is under GNU LGPL.
Files in folders
7zip/Compress/Rar20
7zip/Compress/Rar29
7zip/Compress/Rar29/Original
are licensed under "unRAR license + GNU LGPL" license.
Source code files in all other folders of this package are under GNU LGPL.
"unRAR license + GNU LGPL" means that you must follow
GNU LGPL in all aspects while it is in agreement
with unRAR license. But you can not break unRAR license rules.
It means that unRAR license is main license in that pair.
You can find unRAR license in file unrarLicense.txt
You can find GNU LGPL license in file copying.txt
GNU LGPL information:
---------------------
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
unRAR license + GNU LGPL Notes
------------------------------
Please check main restriction from unRar license:
2. The unRAR sources may be used in any software to handle RAR
archives without limitations free of charge, but cannot be used
to re-create the RAR compression algorithm, which is proprietary.
Distribution of modified unRAR sources in separate form or as a
part of other software is permitted, provided that it is clearly
stated in the documentation and source comments that the code may
not be used to develop a RAR (WinRAR) compatible archiver.
In brief it means:
1) You can compile and use compiled files under GNU LGPL rules, since
unRAR license almost has no restrictions for compiled files.
You can link these compiled files to LGPL programs.
2) You can fix bugs in source code and use compiled fixed version.
3) You can not use unRAR sources to re-create the RAR compression algorithm.
7zip\Compress\Rar29\Original folder contains files that are modified
versions of original unRAR source code files.
License notes
-------------
You can support development of 7-Zip by registering.
7-Zip is free software distributed under the GNU LGPL.
If you need license with other conditions, write to
http://www.7-zip.org/support.html
---
Also this package contains files from LZMA SDK
you can download LZMA SDK from this page:
http://www.7-zip.org/sdk.html
read about addtional licenses for LZMA SDK in file
DOC/lzma.txt
How to compile
--------------
To compile sources you need Visual C++ 6.0.
For compiling some files you also need
new Platform SDK from Microsoft' Site:
http://www.microsoft.com/msdownload/platformsdk/sdkupdate/psdk-full.htm
or
http://www.microsoft.com/msdownload/platformsdk/sdkupdate/XPSP2FULLInstall.htm
or
http://www.microsoft.com/msdownload/platformsdk/sdkupdate/
If you use MSVC6, specify SDK directories at top of directories lists:
Tools / Options / Directories
- Include files
- Library files
To compile 7-Zip for AMD64 and IA64 you need:
Windows Server 2003 SP1 Platform SDK from microsoft.com
Compiling under Unix/Linux
--------------------------
Check this site for Posix/Linux version:
http://sourceforge.net/projects/p7zip/
Notes:
------
7-Zip consists of COM modules (DLL files).
But 7-Zip doesn't use standard COM interfaces for creating objects.
Look at
7zip\UI\Client7z folder for example of using DLL files of 7-Zip.
Some DLL files can use other DLL files from 7-Zip.
If you don't like it, you must use standalone version of DLL.
To compile standalone version of DLL you must include all used parts
to project and define some defs.
For example, 7zip\Bundles\Format7z is a standalone version of 7z.dll
that works with 7z format. So you can use such DLL in your project
without additional DLL files.
Description of 7-Zip sources package
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
DOC Documentation
---
7zFormat.txt - 7z format description
copying.txt - GNU LGPL license
unRarLicense.txt - License for unRAR part of source code
history.txt - Sources history
Methods.txt - Compression method IDs
readme.txt - Readme file
lzma.txt - LZMA SDK description
7zip.nsi - installer script for NSIS
Common Common modules
Windows Win32 wrappers
7zip
-------
Common Common modules for 7-zip
Archive 7-Zip Archive Format Plugins
--------
Common
7z
Arj
BZip2
Cab
Cpio
GZip
Rar
Rpm
Split
Tar
Zip
Bundle Modules that are bundles of other modules
------
Alone 7za.exe: Standalone version of 7z
Alone7z 7zr.exe: Standalone version of 7z that supports only 7z/LZMA/BCJ/BCJ2
SFXCon 7zCon.sfx: Console 7z SFX module
SFXWin 7z.sfx: Windows 7z SFX module
SFXSetup 7zS.sfx: Windows 7z SFX module for Installers
Format7z 7za.dll: Standalone version of 7z.dll
UI
--
Agent Intermediary modules for FAR plugin and Explorer plugin
Console 7z.exe Console version
Explorer Explorer plugin
Resource Resources
Far FAR plugin
Client7z Test application for 7za.dll
Compress
--------
BZip2 BZip2 compressor
Original Download BZip2 compression sources from
http://sources.redhat.com/bzip2/index.html
to that folder.
Branch Branch converter
ByteSwap Byte Swap converter
Copy Copy coder
Deflate
Implode
Arj
LZMA
PPMd Dmitry Shkarin's PPMdH with small changes.
LZ Lempel - Ziv
MT Multi Thread Match finder
BinTree Match Finder based on Binary Tree
Patricia Match Finder based on Patricia algoritm
HashChain Match Finder based on Hash Chains
Crypto Crypto modules
------
7zAES Cipher for 7z
AES AES Cipher
Rar20 Cipher for Rar 2.0
RarAES Cipher for Rar 3.0
Zip Cipher for Zip
FileManager File Manager
---
Igor Pavlov
http://www.7-zip.org
---
End of document

View File

@@ -1,10 +0,0 @@
This directory contains only a part of the original LZMA sources.
Some files were modified and are not an exact replica of the original
files in order to be compiled with the PyLZMA library.
If you are looking for the original LZMA sources, please visit the
official homepage at http://www.7-zip.org.
--
Joachim Bauch / mail@joachim-bauch.de

View File

@@ -1,504 +0,0 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
not price. Our General Public Licenses are designed to make sure that
you have the freedom to distribute copies of free software (and charge
for this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser General Public License from time to time.
Such new versions will be similar in spirit to the present version,
but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Libraries
If you develop a new library, and you want it to be of the greatest
possible use to the public, we recommend making it free software that
everyone can redistribute and change. You can do so by permitting
redistribution under these terms (or, alternatively, under the terms of the
ordinary General Public License).
To apply these terms, attach the following notices to the library. It is
safest to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.
<one line to give the library's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Also add information on how to contact you by electronic and paper mail.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the library, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the
library `Frob' (a library for tweaking knobs) written by James Random Hacker.
<signature of Ty Coon>, 1 April 1990
Ty Coon, President of Vice
That's all there is to it!

View File

@@ -1,204 +0,0 @@
$Id: usage.txt 103 2006-01-08 18:07:53Z jojo $
In this document, some samples of the PyLZMA library will be given.
First, we need to import the module::
>>> import pylzma
The easiest usage is compression and decompression in one step::
>>> compressed = pylzma.compress('Hello world!')
>>> pylzma.decompress(compressed)
'Hello world!'
For compression, additional parameters can be specified::
>>> compressed = pylzma.compress('Hello world!', dictionary=10)
>>> pylzma.decompress(compressed)
'Hello world!'
Other available parameters are:
dictionary
Dictionary size (Range 0-28, Default: 23 (8MB))
The maximum value for dictionary size is 256 MB = 2^28 bytes.
Dictionary size is calculated as DictionarySize = 2^N bytes.
For decompressing file compressed by LZMA method with dictionary
size D = 2^N you need about D bytes of memory (RAM).
fastBytes
Range 5-255, default 128
Usually big number gives a little bit better compression ratio and slower
compression process.
literalContextBits
Range 0-8, default 3
Sometimes literalContextBits=4 gives gain for big files.
literalPosBits
Range 0-4, default 0
This switch is intended for periodical data when period is equal 2^N.
For example, for 32-bit (4 bytes) periodical data you can use
literalPosBits=2. Often it's better to set literalContextBits=0, if you
change the literalPosBits switch.
posBits
Range 0-4, default 2
This switch is intended for periodical data when period is equal 2^N.
algorithm
Compression mode 0 = fast, 1 = normal, 2 = max (Default: 2)
The lower the number specified for algorithm, the faster compression will
perform.
multithreading
Use multithreading if available? (Default yes)
Currently, multithreading is only available on Windows platforms.
matchfinder
Matchfinder algorithm to use. Possible values are bt2, bt3, bt4, bt4b,
pat2r, pat2, pat2h, pat3h, pat4h, hc3, hc4 (Default: bt4).
Compression ratio for all bt* and pat* almost the same. Algorithms from hc*
group don't provide good compression ratio, but they often work pretty fast
in combination with fast mode (algorithm=0). Methods from bt* group require
less memory than methods from pat* group. Usually bt4 works faster than
any pat*, but for some types of files pat* can work faster.
Memory requirements depend from dictionary size (parameter "d" in table below).
===== ============ =======================================================
MF_ID Memory Description
===== ============ =======================================================
bt2 d*9.5 + 1MB Binary Tree with 2 bytes hashing.
bt3 d*9.5 + 65MB Binary Tree with 2-3(full) bytes hashing.
bt4 d*9.5 + 6MB Binary Tree with 2-3-4 bytes hashing.
bt4b d*9.5 + 34MB Binary Tree with 2-3-4(big) bytes hashing.
pat2r d*26 + 1MB Patricia Tree with 2-bits nodes, removing.
pat2 d*38 + 1MB Patricia Tree with 2-bits nodes.
pat2h d*38 + 77MB Patricia Tree with 2-bits nodes, 2-3 bytes hashing.
pat3h d*62 + 85MB Patricia Tree with 3-bits nodes, 2-3 bytes hashing.
pat4h d*110 +101MB Patricia Tree with 4-bits nodes, 2-3 bytes hashing.
hc3 d*5.5 + 1MB Hash Chain with 2-3 bytes hashing.
hc4 d*5.5 + 6MB Hash Chain with 2-3-4 bytes hashing.
===== ============ =======================================================
eos
Should the `End Of Stream` marker be written? (Default yes)
You can save some bytes if the marker is omitted, but the total uncompressed
size must be stored by the application and used when decompressing:
>>> compressed1 = pylzma.compress('Hello world!', eos=1)
>>> compressed2 = pylzma.compress('Hello world!', eos=0)
>>> len(compressed1) > len(compressed2)
True
>>> pylzma.decompress(compressed2)
Traceback (most recent call last):
...
ValueError: data error during decompression
>>> pylzma.decompress(compressed2, maxlength=12)
'Hello world!'
If you don't know the total uncompressed size, you can use the compatibility
decompression function from pylzma version 0.0.3. Be aware that this old
method is slower than the new decompression function, so you should use
`pylzma.decompress` whenever possible.
>>> pylzma.decompress_compat(compressed2)
'Hello world!'
If you need to compress larger amounts of data, you should use the streaming
version of the library. If supports compressing any file-like objects::
>>> from cStringIO import StringIO
>>> fp = StringIO('Hello world!')
>>> c_fp = pylzma.compressfile(fp, eos=1)
>>> compressed = ''
>>> while True:
... tmp = c_fp.read(1)
... if not tmp: break
... compressed += tmp
...
>>> pylzma.decompress(compressed)
'Hello world!'
Using a similar technique, you can decompress large amounts of data without
keeping everything in memory::
>>> from cStringIO import StringIO
>>> fp = StringIO(pylzma.compress('Hello world!'))
>>> obj = pylzma.decompressobj()
>>> plain = ''
>>> while True:
... tmp = fp.read(1)
... if not tmp: break
... plain += obj.decompress(tmp)
...
>>> plain += obj.flush()
>>> plain
'Hello world!'
However this only works for streams that contain the `End Of Stream` marker.
You must provide the size of the decompressed data if you don't include the
EOS marker::
>>> from cStringIO import StringIO
>>> fp = StringIO(pylzma.compress('Hello world!', eos=0))
>>> obj = pylzma.decompressobj(maxlength=13)
>>> plain = ''
>>> while True:
... tmp = fp.read(1)
... if not tmp: break
... plain += obj.decompress(tmp)
...
>>> plain += obj.flush()
Traceback (most recent call last):
...
ValueError: data error during decompression
>>> obj.reset(maxlength=12)
>>> fp.seek(0)
>>> plain = ''
>>> while True:
... tmp = fp.read(1)
... if not tmp: break
... plain += obj.decompress(tmp)
...
>>> plain += obj.flush()
>>> plain
'Hello world!'
Please note that the compressed data is not compatible to the lzma.exe command
line utility! To get compatible data, you can use the following utility
function::
>>> import struct
>>> from cStringIO import StringIO
>>> def compress_compatible(data):
... c = pylzma.compressfile(StringIO(data))
... # LZMA header
... result = c.read(5)
... # size of uncompressed data
... result += struct.pack('<Q', len(data))
... # compressed data
... return result + c.read()

View File

@@ -1,594 +0,0 @@
#!/usr/bin/python -u
#
# Python Bindings for LZMA
#
# Copyright (c) 2004-2006 by Joachim Bauch, mail@joachim-bauch.de
# 7-Zip Copyright (C) 1999-2005 Igor Pavlov
# LZMA SDK Copyright (C) 1999-2005 Igor Pavlov
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# $Id: py7zlib.py 115 2006-06-18 10:53:56Z jojo $
#
"""Read from and write to 7zip format archives.
"""
import pylzma
from struct import pack, unpack
from zlib import crc32
from cStringIO import StringIO
MAGIC_7Z = '7z\xbc\xaf\x27\x1c'
PROPERTY_END = '\x00'
PROPERTY_HEADER = '\x01'
PROPERTY_ARCHIVE_PROPERTIES = '\x02'
PROPERTY_ADDITIONAL_STREAMS_INFO = '\x03'
PROPERTY_MAIN_STREAMS_INFO = '\x04'
PROPERTY_FILES_INFO = '\x05'
PROPERTY_PACK_INFO = '\x06'
PROPERTY_UNPACK_INFO = '\x07'
PROPERTY_SUBSTREAMS_INFO = '\x08'
PROPERTY_SIZE = '\x09'
PROPERTY_CRC = '\x0a'
PROPERTY_FOLDER = '\x0b'
PROPERTY_CODERS_UNPACK_SIZE = '\x0c'
PROPERTY_NUM_UNPACK_STREAM = '\x0d'
PROPERTY_EMPTY_STREAM = '\x0e'
PROPERTY_EMPTY_FILE = '\x0f'
PROPERTY_ANTI = '\x10'
PROPERTY_NAME = '\x11'
PROPERTY_CREATION_TIME = '\x12'
PROPERTY_LAST_ACCESS_TIME = '\x13'
PROPERTY_LAST_WRITE_TIME = '\x14'
PROPERTY_ATTRIBUTES = '\x15'
PROPERTY_COMMENT = '\x16'
PROPERTY_ENCODED_HEADER = '\x17'
class FormatError(Exception):
pass
class Base:
""" base class with support for various basic read/write functions """
def _readReal64Bit(self, file):
res = file.read(8)
a, b = unpack('<LL', res)
return b << 32 | a, res
def _read64Bit(self, file):
b = ord(file.read(1))
mask = 0x80
for i in xrange(8):
if b & mask == 0:
bytes = list(unpack('%dB' % i, file.read(i)))
bytes.reverse()
value = (bytes and reduce(lambda x, y: long(x) << 8 | y, bytes)) or 0L
highpart = b & (mask - 1)
return value + (long(highpart) << (i * 8))
mask >>= 1
def _readBoolean(self, file, count, checkall=0):
if checkall:
alldefined = file.read(1)
if alldefined != '\x00':
return [True] * count
result = []
b = 0
mask = 0
for i in xrange(count):
if mask == 0:
b = ord(file.read(1))
mask = 0x80
result.append(b & mask != 0)
mask >>= 1
return result
class PackInfo(Base):
""" informations about packed streams """
def __init__(self, file):
self.packpos = self._read64Bit(file)
self.numstreams = self._read64Bit(file)
id = file.read(1)
if id == PROPERTY_SIZE:
self.packsizes = [self._read64Bit(file) for x in xrange(self.numstreams)]
id = file.read(1)
if id == PROPERTY_CRC:
self.crcs = [self._read64Bit(file) for x in xrange(self.numstreams)]
id = file.read(1)
if id != PROPERTY_END:
raise FormatError, 'end id expected but %s found' % repr(id)
class Folder(Base):
""" a "Folder" represents a stream of compressed data """
def __init__(self, file):
numcoders = self._read64Bit(file)
self.coders = []
self.digestdefined = False
totalin = 0
self.totalout = 0
for i in xrange(numcoders):
while True:
b = ord(file.read(1))
methodsize = b & 0xf
issimple = b & 0x10 == 0
noattributes = b & 0x20 == 0
last_alternative = b & 0x80 == 0
c = {}
c['method'] = file.read(methodsize)
if not issimple:
c['numinstreams'] = self._read64Bit(file)
c['numoutstreams'] = self._read64Bit(file)
else:
c['numinstreams'] = 1
c['numoutstreams'] = 1
totalin += c['numinstreams']
self.totalout += c['numoutstreams']
if c['method'][0] != '\x00':
c['properties'] = file.read(self._read64Bit(file))
self.coders.append(c)
if last_alternative:
break
numbindpairs = self.totalout - 1
self.bindpairs = []
for i in xrange(numbindpairs):
self.bindpairs.append((self._read64Bit(file), self._read64Bit(file), ))
numpackedstreams = totalin - numbindpairs
self.packed_indexes = []
if numpackedstreams == 1:
for i in xrange(totalin):
if self.findInBindPair(i) < 0:
self.packed_indexes.append(i)
elif numpackedstreams > 1:
for i in xrange(numpackedstreams):
self.packed_indexes.append(self._read64Bit(file))
def getUnpackSize(self):
if not self.unpacksizes:
return 0
r = range(len(self.unpacksizes))
r.reverse()
for i in r:
if self.findOutBindPair(i):
return self.unpacksizes[i]
raise 'not found'
def findInBindPair(self, index):
for idx in xrange(len(self.bindpairs)):
a, b = self.bindpairs[idx]
if a == index:
return idx
return -1
def findOutBindPair(self, index):
for idx in xrange(len(self.bindpairs)):
a, b = self.bindpairs[idx]
if b == index:
return idx
return -1
class Digests(Base):
""" holds a list of checksums """
def __init__(self, file, count):
self.defined = self._readBoolean(file, count, checkall=1)
self.crcs = [unpack('<l', file.read(4))[0] for x in xrange(count)]
UnpackDigests = Digests
class UnpackInfo(Base):
""" combines multiple folders """
def __init__(self, file):
id = file.read(1)
if id != PROPERTY_FOLDER:
raise FormatError, 'folder id expected but %s found' % repr(id)
self.numfolders = self._read64Bit(file)
self.folders = []
external = file.read(1)
if external == '\x00':
self.folders = [Folder(file) for x in xrange(self.numfolders)]
elif external == '\x01':
self.datastreamidx = self._read64Bit(file)
else:
raise FormatError, '0x00 or 0x01 expected but %s found' % repr(external)
id = file.read(1)
if id != PROPERTY_CODERS_UNPACK_SIZE:
raise FormatError, 'coders unpack size id expected but %s found' % repr(id)
for folder in self.folders:
folder.unpacksizes = [self._read64Bit(file) for x in xrange(folder.totalout)]
id = file.read(1)
if id == PROPERTY_CRC:
digests = UnpackDigests(file, self.numfolders)
for idx in xrange(self.numfolders):
folder = self.folders[idx]
folder.digestdefined = digests.defined[idx]
folder.crc = digests.crcs[idx]
id = file.read(1)
if id != PROPERTY_END:
raise FormatError, 'end id expected but %s found' % repr(id)
class SubstreamsInfo(Base):
""" defines the substreams of a folder """
def __init__(self, file, numfolders, folders):
self.digests = []
self.digestsdefined = []
id = file.read(1)
if id == PROPERTY_NUM_UNPACK_STREAM:
self.numunpackstreams = [self._read64Bit(file) for x in xrange(numfolders)]
id = file.read(1)
else:
self.numunpackstreams = []
for idx in xrange(numfolders):
self.numunpackstreams.append(1)
if id == PROPERTY_SIZE:
sum = 0
self.unpacksizes = []
for i in xrange(len(self.numunpackstreams)):
for j in xrange(1, self.numunpackstreams[i]):
size = self._read64Bit(file)
self.unpacksizes.append(size)
sum += size
self.unpacksizes.append(folders[i].getUnpackSize() - sum)
id = file.read(1)
if id == PROPERTY_CRC:
numdigests = 0
numdigeststotal = 0
for i in xrange(numfolders):
numsubstreams = self.numunpackstreams[i]
if numsubstreams != 1 or not folders[i].digestdefined:
numdigests += numsubstreams
numdigeststotal += numsubstreams
digests = Digests(file, numdigests)
didx = 0
for i in xrange(numfolders):
folder = folders[i]
numsubstreams = self.numunpackstreams[i]
if numsubstreams == 1 and folder.digestdefined:
self.digestsdefined.append(True)
self.digests.append(folder.crc)
else:
for j in xrange(numsubstreams):
self.digestsdefined.append(digests.defined[didx])
self.digests.append(digests.crcs[didx])
didx += 1
id = file.read(1)
if id != PROPERTY_END:
raise FormatError, 'end id expected but %s found' % repr(id)
if not self.digestsdefined:
self.digestsdefined = [False] * numdigeststotal
self.digests = [0] * numdigeststotal
class StreamsInfo(Base):
""" informations about compressed streams """
def __init__(self, file):
id = file.read(1)
if id == PROPERTY_PACK_INFO:
self.packinfo = PackInfo(file)
id = file.read(1)
if id == PROPERTY_UNPACK_INFO:
self.unpackinfo = UnpackInfo(file)
id = file.read(1)
if id == PROPERTY_SUBSTREAMS_INFO:
self.substreamsinfo = SubstreamsInfo(file, self.unpackinfo.numfolders, self.unpackinfo.folders)
id = file.read(1)
if id != PROPERTY_END:
raise FormatError, 'end id expected but %s found' % repr(id)
class FilesInfo(Base):
""" holds file properties """
def _readTimes(self, file, files, name):
defined = self._readBoolean(file, len(files), checkall=1)
for i in xrange(len(files)):
if defined[i]:
files[i][name] = self._readReal64Bit(file)[0] #unpack('<L', file.read(4))[0]
else:
files[i][name] = None
def __init__(self, file):
self.numfiles = self._read64Bit(file)
self.files = [{'emptystream': False} for x in xrange(self.numfiles)]
numemptystreams = 0
while True:
typ = self._read64Bit(file)
if typ > 255:
raise FormatError, 'invalid type, must be below 256, is %d' % typ
typ = chr(typ)
if typ == PROPERTY_END:
break
size = self._read64Bit(file)
buffer = StringIO(file.read(size))
if typ == PROPERTY_EMPTY_STREAM:
isempty = self._readBoolean(buffer, self.numfiles)
map(lambda x, y: x.update({'emptystream': y}), self.files, isempty)
for x in isempty:
if x: numemptystreams += 1
emptyfiles = [False] * numemptystreams
antifiles = [False] * numemptystreams
elif typ == PROPERTY_EMPTY_FILE:
emptyfiles = self._readBoolean(buffer, numemptystreams)
elif typ == PROPERTY_ANTI:
antifiles = self._readBoolean(buffer, numemptystreams)
elif typ == PROPERTY_NAME:
external = buffer.read(1)
if external != '\x00':
self.dataindex = self._read64Bit(buffer)
# XXX: evaluate external
raise NotImplementedError
for f in self.files:
name = ''
while True:
ch = buffer.read(2)
if ch == '\0\0':
f['filename'] = unicode(name, 'utf-16')
break
name += ch
elif typ == PROPERTY_CREATION_TIME:
self._readTimes(buffer, self.files, 'creationtime')
elif typ == PROPERTY_LAST_ACCESS_TIME:
self._readTimes(buffer, self.files, 'lastaccesstime')
elif typ == PROPERTY_LAST_WRITE_TIME:
self._readTimes(buffer, self.files, 'lastwritetime')
elif typ == PROPERTY_ATTRIBUTES:
defined = self._readBoolean(buffer, self.numfiles, checkall=1)
for i in xrange(self.numfiles):
f = self.files[i]
if defined[i]:
f['attributes'] = unpack('<L', buffer.read(4))[0]
else:
f['attributes'] = None
else:
raise FormatError, 'invalid type %s' % repr(typ)
class Header(Base):
""" the archive header """
def __init__(self, file):
id = file.read(1)
if id == PROPERTY_ARCHIVE_PROPERTIES:
self.properties = ArchiveProperties(file)
id = file.read(1)
if id == PROPERTY_ADDITIONAL_STREAMS_INFO:
self.additional_streams = StreamsInfo(file)
id = file.read(1)
if id == PROPERTY_MAIN_STREAMS_INFO:
self.main_streams = StreamsInfo(file)
id = file.read(1)
if id == PROPERTY_FILES_INFO:
self.files = FilesInfo(file)
id = file.read(1)
if id != PROPERTY_END:
raise FormatError, 'end id expected but %s found' % (repr(id))
class ArchiveFile:
""" wrapper around a file in the archive """
def __init__(self, info, start, src_start, size, folder, archive, maxsize=None):
self.digest = None
self._archive = archive
self._file = archive._file
self._start = start
self._src_start = src_start
self._folder = folder
self.size = size
# maxsize is only valid for solid archives
self._maxsize = maxsize
for k, v in info.items():
setattr(self, k, v)
self.reset()
def reset(self):
self.pos = 0
def read(self):
data = ''
idx = 0
cnt = 0
dec = pylzma.decompressobj(maxlength=self._start+self.size)
self._file.seek(self._src_start)
dec.decompress(self._folder.coders[0]['properties'])
total = self.compressed
if total is None:
remaining = self._start+self.size
out = StringIO()
while remaining > 0:
data = self._file.read(1024)
tmp = dec.decompress(data, remaining)
out.write(tmp)
remaining -= len(tmp)
data = out.getvalue()
else:
data = dec.decompress(self._file.read(total), self._start+self.size)
return data[self._start:self._start+self.size]
def checkcrc(self):
if self.digest is None:
return True
self.reset()
data = self.read()
crc = crc32(data)
# make crc unsigned
# XXX: better way to do this?
crc = unpack('<l', pack('<L', crc))[0]
return crc == self.digest
class Archive7z(Base):
""" the archive itself """
def __init__(self, file):
self._file = file
self.header = file.read(len(MAGIC_7Z))
if self.header != MAGIC_7Z:
raise FormatError, 'not a 7z file'
self.version = unpack('BB', file.read(2))
self.startheadercrc = unpack('<l', file.read(4))[0]
self.nextheaderofs, data = self._readReal64Bit(file)
crc = crc32(data)
self.nextheadersize, data = self._readReal64Bit(file)
crc = crc32(data, crc)
data = file.read(4)
self.nextheadercrc = unpack('<l', data)[0]
crc = crc32(data, crc)
if crc != self.startheadercrc:
raise FormatError, 'invalid header data'
self.afterheader = file.tell()
file.seek(self.nextheaderofs, 1)
buffer = StringIO(file.read(self.nextheadersize))
if crc32(buffer.getvalue()) != self.nextheadercrc:
raise FormatError, 'invalid header data'
while True:
id = buffer.read(1)
if id == PROPERTY_HEADER:
break
if id != PROPERTY_ENCODED_HEADER:
raise 'Unknown field:', repr(id)
streams = StreamsInfo(buffer)
file.seek(self.afterheader + 0)
data = ''
idx = 0
for folder in streams.unpackinfo.folders:
file.seek(streams.packinfo.packpos, 1)
props = folder.coders[0]['properties']
for idx in xrange(len(streams.packinfo.packsizes)):
tmp = file.read(streams.packinfo.packsizes[idx])
data += pylzma.decompress(props+tmp, maxlength=folder.unpacksizes[idx])
if folder.digestdefined:
if folder.crc != crc32(data):
raise FormatError, 'invalid block data'
buffer = StringIO(data)
self.header = Header(buffer)
self.files = []
files = self.header.files
folders = self.header.main_streams.unpackinfo.folders
packinfo = self.header.main_streams.packinfo
subinfo = self.header.main_streams.substreamsinfo
packsizes = packinfo.packsizes
self.solid = packinfo.numstreams == 1
if self.solid:
# the files are stored in substreams
if hasattr(subinfo, 'unpacksizes'):
unpacksizes = subinfo.unpacksizes
else:
unpacksizes = [x.unpacksizes[0] for x in folders]
else:
# every file has it's own folder with compressed data
unpacksizes = [x.unpacksizes[0] for x in folders]
fidx = 0
obidx = 0
src_pos = self.afterheader
pos = 0
maxsize = (self.solid and packinfo.packsizes[0]) or None
for idx in xrange(files.numfiles):
info = files.files[idx]
folder = folders[fidx]
if not info['emptystream']:
info['compressed'] = (not self.solid and packsizes[obidx]) or None
info['uncompressed'] = unpacksizes[obidx]
file = ArchiveFile(info, pos, src_pos, unpacksizes[obidx], folder, self, maxsize=maxsize)
if subinfo.digestsdefined[obidx]:
file.digest = subinfo.digests[obidx]
self.files.append(file)
if self.solid:
pos += unpacksizes[obidx]
else:
src_pos += packsizes[obidx]
obidx += 1
if not self.solid:
fidx += 1
self.numfiles = len(self.files)
self.filenames = map(lambda x: x.filename, self.files)
# interface like TarFile
def getmember(self, name):
# XXX: store files in dictionary
for f in self.files:
if f.filename == name:
return f
return None
def getmembers(self):
return self.files
def getnames(self):
return self.filenames
def list(self, verbose=True):
print 'total %d files in %sarchive' % (self.numfiles, (self.solid and 'solid ') or '')
if not verbose:
print '\n'.join(self.filenames)
return
for f in self.files:
extra = (f.compressed and '%10d ' % (f.compressed)) or ' '
print '%10d%s%s %s' % (f.size, extra, hex(f.digest)[2:-1], f.filename)
if __name__ == '__main__':
f = Archive7z(open('test.7z', 'rb'))
#f = Archive7z(open('pylzma.7z', 'rb'))
f.list()

View File

@@ -1,99 +0,0 @@
/*
* Python Bindings for LZMA
*
* Copyright (c) 2004-2006 by Joachim Bauch, mail@joachim-bauch.de
* 7-Zip Copyright (C) 1999-2005 Igor Pavlov
* LZMA SDK Copyright (C) 1999-2005 Igor Pavlov
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* $Id: pylzma.c 116 2006-09-28 21:46:20Z jojo $
*
*/
#include <Python.h>
#include <cStringIO.h>
#include "pylzma.h"
#include "pylzma_compress.h"
#include "pylzma_decompress.h"
#include "pylzma_decompressobj.h"
#include "pylzma_compressobj.h"
#include "pylzma_compressfile.h"
#ifdef WITH_COMPAT
#include "pylzma_decompress_compat.h"
#include "pylzma_decompressobj_compat.h"
#endif
#if defined(WITH_THREAD) && !defined(PYLZMA_USE_GILSTATE)
PyInterpreterState* _pylzma_interpreterState = NULL;
#endif
static void insint(PyObject *d, char *name, int value)
{
PyObject *v = PyInt_FromLong((long) value);
if (!v || PyDict_SetItemString(d, name, v))
PyErr_Clear();
Py_XDECREF(v);
}
PyMethodDef methods[] = {
// exported functions
{"compress", (PyCFunction)pylzma_compress, METH_VARARGS | METH_KEYWORDS, (char *)&doc_compress},
{"decompress", (PyCFunction)pylzma_decompress, METH_VARARGS | METH_KEYWORDS, (char *)&doc_decompress},
// XXX: compression through an object doesn't work, yet
//{"compressobj", (PyCFunction)pylzma_compressobj, METH_VARARGS | METH_KEYWORDS, (char *)&doc_compressobj},
#ifdef WITH_COMPAT
// compatibility functions
{"decompress_compat", (PyCFunction)pylzma_decompress_compat, METH_VARARGS | METH_KEYWORDS, (char *)&doc_decompress_compat},
{"decompressobj_compat", (PyCFunction)pylzma_decompressobj_compat, METH_VARARGS, (char *)&doc_decompressobj_compat},
#endif
{NULL, NULL},
};
DL_EXPORT(void) initpylzma(void)
{
PyObject *m, *d;
CDecompressionObject_Type.tp_new = PyType_GenericNew;
if (PyType_Ready(&CDecompressionObject_Type) < 0)
return;
if (PyType_Ready(&CCompressionFileObject_Type) < 0)
return;
m = Py_InitModule("pylzma", methods);
Py_INCREF(&CDecompressionObject_Type);
PyModule_AddObject(m, "decompressobj", (PyObject *)&CDecompressionObject_Type);
Py_INCREF(&CCompressionFileObject_Type);
PyModule_AddObject(m, "compressfile", (PyObject *)&CCompressionFileObject_Type);
d = PyModule_GetDict(m);
PycString_IMPORT;
#if defined(WITH_THREAD)
PyEval_InitThreads();
#if !defined(PYLZMA_USE_GILSTATE)
/* Save the current interpreter, so compressing file objects works. */
_pylzma_interpreterState = PyThreadState_Get()->interp;
#endif
#endif
}

View File

@@ -1,77 +0,0 @@
/*
* Python Bindings for LZMA
*
* Copyright (c) 2004-2006 by Joachim Bauch, mail@joachim-bauch.de
* 7-Zip Copyright (C) 1999-2005 Igor Pavlov
* LZMA SDK Copyright (C) 1999-2005 Igor Pavlov
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* $Id: pylzma.h 104 2006-01-08 18:17:14Z jojo $
*
*/
#ifndef ___PYLZMA__H___
#define ___PYLZMA__H___
#include <Python.h>
#ifndef min
#define min(a, b) ((a) < (b) ? (a) : (b))
#endif
#define BLOCK_SIZE 65536
#define CHECK_NULL(a) if ((a) == NULL) { PyErr_NoMemory(); goto exit; }
#define DEC_AND_NULL(a) { Py_XDECREF(a); a = NULL; }
#define DELETE_AND_NULL(a) if (a != NULL) { delete a; a = NULL; }
#define FREE_AND_NULL(a) if (a != NULL) { free(a); a = NULL; }
#define CHECK_RANGE(x, a, b, msg) if ((x) < (a) || (x) > (b)) { PyErr_SetString(PyExc_ValueError, msg); goto exit; }
#if defined(WITH_THREAD)
/* For Python 2.3 and above, use the PyGILState_ calls */
#if (PY_VERSION_HEX >= 0x02030000)
#define PYLZMA_USE_GILSTATE
#endif
#if defined(PYLZMA_USE_GILSTATE)
// Python 2.3 and above
#define START_BLOCK_THREADS \
PyGILState_STATE __savestate = PyGILState_Ensure();
#define END_BLOCK_THREADS \
PyGILState_Release(__savestate);
#else
// Before Python 2.3
PyInterpreterState* _pylzma_interpreterState;
#define START_BLOCK_THREADS { \
PyThreadState* prevState; \
PyThreadState* newState; \
PyEval_AcquireLock(); \
newState = PyThreadState_New(_pylzma_interpreterState);\
prevState = PyThreadState_Swap(newState);
#define END_BLOCK_THREADS \
newState = PyThreadState_Swap(prevState); \
PyThreadState_Clear(newState); \
PyEval_ReleaseLock(); \
PyThreadState_Delete(newState); \
}
#endif
#else // WITH_THREADS
#define START_BLOCK_THREADS
#define END_BLOCK_THREADS
#endif
#endif

View File

@@ -1,179 +0,0 @@
/*
* Python Bindings for LZMA
*
* Copyright (c) 2004-2006 by Joachim Bauch, mail@joachim-bauch.de
* 7-Zip Copyright (C) 1999-2005 Igor Pavlov
* LZMA SDK Copyright (C) 1999-2005 Igor Pavlov
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* $Id: pylzma_compress.cpp 104 2006-01-08 18:17:14Z jojo $
*
*/
#include <Python.h>
#include <7zip/Common/MyWindows.h>
#include <7zip/7zip/IStream.h>
#include <7zip/7zip/Compress/LZMA/LZMAEncoder.h>
#include "pylzma.h"
#include "pylzma_streams.h"
int set_encoder_properties(NCompress::NLZMA::CEncoder *encoder, int dictionary, int posBits,
int literalContextBits, int literalPosBits, int algorithm, int fastBytes, int eos,
int multithreading, const char *matchfinder)
{
wchar_t tmp[10];
unsigned int i;
encoder->SetWriteEndMarkerMode(eos ? true : false);
PROPID propIDs[] =
{
NCoderPropID::kDictionarySize,
NCoderPropID::kPosStateBits,
NCoderPropID::kLitContextBits,
NCoderPropID::kLitPosBits,
NCoderPropID::kAlgorithm,
NCoderPropID::kNumFastBytes,
NCoderPropID::kMatchFinder
#ifdef COMPRESS_MF_MT
, NCoderPropID::kMultiThread
#endif
};
const int kNumProps = sizeof(propIDs) / sizeof(propIDs[0]);
PROPVARIANT props[kNumProps];
// NCoderProp::kDictionarySize;
props[0].vt = VT_UI4;
props[0].ulVal = 1 << dictionary;
// NCoderProp::kPosStateBits;
props[1].vt = VT_UI4;
props[1].ulVal = posBits;
// NCoderProp::kLitContextBits;
props[2].vt = VT_UI4;
props[2].ulVal = literalContextBits;
// NCoderProp::kLitPosBits;
props[3].vt = VT_UI4;
props[3].ulVal = literalPosBits;
// NCoderProp::kAlgorithm;
props[4].vt = VT_UI4;
props[4].ulVal = algorithm;
// NCoderProp::kNumFastBytes;
props[5].vt = VT_UI4;
props[5].ulVal = fastBytes;
// NCoderProp::kMatchFinder;
if (strlen(matchfinder) > (sizeof(tmp)/2)-1)
return 1;
props[6].vt = VT_BSTR;
for (i=0; i<strlen(matchfinder); i++)
tmp[i] = matchfinder[i];
tmp[i] = 0;
props[6].bstrVal = (BSTR)(const wchar_t *)&tmp;
#ifdef COMPRESS_MF_MT
// NCoderPropID::kMultiThread
props[7].vt = VT_BOOL;
props[7].boolVal = (multithreading != 0) ? VARIANT_TRUE : VARIANT_FALSE;
#endif
return encoder->SetCoderProperties(propIDs, props, kNumProps);
}
#ifdef __cplusplus
extern "C"
#endif
const char doc_compress[] = \
"compress(string, dictionary=23, fastBytes=128, literalContextBits=3, literalPosBits=0, posBits=2, algorithm=2, eos=1, multithreading=1, matchfinder='bt4') -- Compress the data in string using the given parameters, returning a string containing the compressed data.";
#ifdef __cplusplus
extern "C" {
#endif
PyObject *pylzma_compress(PyObject *self, PyObject *args, PyObject *kwargs)
{
PyObject *result = NULL;
NCompress::NLZMA::CEncoder *encoder = NULL;
CInStream *inStream = NULL;
COutStream *outStream = NULL;
int res;
// possible keywords for this function
static char *kwlist[] = {"data", "dictionary", "fastBytes", "literalContextBits",
"literalPosBits", "posBits", "algorithm", "eos", "multithreading", "matchfinder", NULL};
int dictionary = 23; // [0,28], default 23 (8MB)
int fastBytes = 128; // [5,255], default 128
int literalContextBits = 3; // [0,8], default 3
int literalPosBits = 0; // [0,4], default 0
int posBits = 2; // [0,4], default 2
int eos = 1; // write "end of stream" marker?
int multithreading = 1; // use multithreading if available?
char *matchfinder = "bt4"; // matchfinder algorithm
int algorithm = 2;
char *data;
int length;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s#|iiiiiiiis", kwlist, &data, &length, &dictionary, &fastBytes,
&literalContextBits, &literalPosBits, &posBits, &algorithm, &eos, &multithreading, &matchfinder))
return NULL;
CHECK_RANGE(dictionary, 0, 28, "dictionary must be between 0 and 28");
CHECK_RANGE(fastBytes, 5, 255, "fastBytes must be between 5 and 255");
CHECK_RANGE(literalContextBits, 0, 8, "literalContextBits must be between 0 and 8");
CHECK_RANGE(literalPosBits, 0, 4, "literalPosBits must be between 0 and 4");
CHECK_RANGE(posBits, 0, 4, "posBits must be between 0 and 4");
CHECK_RANGE(algorithm, 0, 2, "algorithm must be between 0 and 2");
encoder = new NCompress::NLZMA::CEncoder();
CHECK_NULL(encoder);
if ((res = set_encoder_properties(encoder, dictionary, posBits, literalContextBits, literalPosBits, algorithm, fastBytes, eos, multithreading, matchfinder) != 0))
{
PyErr_SetString(PyExc_TypeError, "can't set coder properties");
goto exit;
}
inStream = new CInStream((BYTE *)data, length);
CHECK_NULL(inStream);
outStream = new COutStream();
CHECK_NULL(outStream);
Py_BEGIN_ALLOW_THREADS
encoder->SetStreams(inStream, outStream, 0, 0);
encoder->WriteCoderProperties(outStream);
while(true)
{
UInt64 processedInSize;
UInt64 processedOutSize;
Int32 finished;
if ((res = encoder->CodeOneBlock(&processedInSize, &processedOutSize, &finished)) != S_OK)
{
PyErr_Format(PyExc_TypeError, "Error during compressing: %d", res);
goto exit;
}
if (finished != 0)
break;
}
Py_END_ALLOW_THREADS
result = PyString_FromStringAndSize((const char *)outStream->getData(), outStream->getLength());
exit:
DELETE_AND_NULL(encoder);
DELETE_AND_NULL(inStream);
return result;
}
#ifdef __cplusplus
}
#endif

View File

@@ -1,34 +0,0 @@
/*
* Python Bindings for LZMA
*
* Copyright (c) 2004-2006 by Joachim Bauch, mail@joachim-bauch.de
* 7-Zip Copyright (C) 1999-2005 Igor Pavlov
* LZMA SDK Copyright (C) 1999-2005 Igor Pavlov
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* $Id: pylzma_compress.h 104 2006-01-08 18:17:14Z jojo $
*
*/
#ifndef ___PYLZMA_COMPRESS__H___
#define ___PYLZMA_COMPRESS__H___
#include <Python.h>
extern const char doc_compress[];
PyObject *pylzma_compress(PyObject *self, PyObject *args, PyObject *kwargs);
#endif

View File

@@ -1,254 +0,0 @@
/*
* Python Bindings for LZMA
*
* Copyright (c) 2004-2006 by Joachim Bauch, mail@joachim-bauch.de
* 7-Zip Copyright (C) 1999-2005 Igor Pavlov
* LZMA SDK Copyright (C) 1999-2005 Igor Pavlov
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* $Id: pylzma_compressfile.cpp 104 2006-01-08 18:17:14Z jojo $
*
*/
#include <Python.h>
#include <cStringIO.h>
#include <7zip/Common/MyWindows.h>
#include <7zip/7zip/IStream.h>
#include <7zip/7zip/Compress/LZMA/LZMAEncoder.h>
#include "pylzma.h"
#include "pylzma_streams.h"
#include "pylzma_compress.h"
#include "pylzma_compressfile.h"
int set_encoder_properties(NCompress::NLZMA::CEncoder *encoder, int dictionary, int posBits,
int literalContextBits, int literalPosBits, int algorithm, int fastBytes, int eos,
int multithreading, const char *matchfinder);
typedef struct {
PyObject_HEAD
NCompress::NLZMA::CEncoder *encoder;
CInStream *inStream;
COutStream *outStream;
PyObject *inFile;
} CCompressionFileObject;
static char *doc_compfile_read = \
"docstring is todo\n";
static PyObject *pylzma_compfile_read(CCompressionFileObject *self, PyObject *args)
{
PyObject *result = NULL;
int length, bufsize=0;
if (!PyArg_ParseTuple(args, "|l", &bufsize))
return NULL;
while (!bufsize || self->outStream->getMaxRead() < bufsize)
{
UInt64 processedInSize;
UInt64 processedOutSize;
INT32 finished;
Py_BEGIN_ALLOW_THREADS
self->encoder->CodeOneBlock(&processedInSize, &processedOutSize, &finished);
Py_END_ALLOW_THREADS
if (finished)
break;
}
if (bufsize)
length = min(bufsize, self->outStream->getMaxRead());
else
length = self->outStream->getMaxRead();
result = PyString_FromStringAndSize((const char *)self->outStream->getReadPtr(), length);
if (result == NULL) {
PyErr_NoMemory();
goto exit;
}
self->outStream->increaseReadPos(length);
exit:
return result;
}
static PyMethodDef pylzma_compfile_methods[] = {
{"read", (PyCFunction)pylzma_compfile_read, METH_VARARGS, doc_compfile_read},
{NULL, NULL},
};
static void pylzma_compfile_dealloc(CCompressionFileObject *self)
{
DEC_AND_NULL(self->inFile);
DELETE_AND_NULL(self->encoder);
DELETE_AND_NULL(self->inStream);
self->ob_type->tp_free((PyObject*)self);
}
#ifdef __cplusplus
extern "C" {
#endif
static PyObject* pylzma_compfile_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
CCompressionFileObject *self;
self = (CCompressionFileObject*)type->tp_alloc(type, 0);
if (self != NULL) {
self->encoder = NULL;
self->inStream = NULL;
self->outStream = NULL;
self->inFile = NULL;
}
return (PyObject*)self;
}
int pylzma_compfile_init(CCompressionFileObject *self, PyObject *args, PyObject *kwargs)
{
PyObject *inFile;
NCompress::NLZMA::CEncoder *encoder;
int result = -1;
// possible keywords for this function
static char *kwlist[] = {"infile", "dictionary", "fastBytes", "literalContextBits",
"literalPosBits", "posBits", "algorithm", "eos", "multithreading", "matchfinder", NULL};
int dictionary = 23; // [0,28], default 23 (8MB)
int fastBytes = 128; // [5,255], default 128
int literalContextBits = 3; // [0,8], default 3
int literalPosBits = 0; // [0,4], default 0
int posBits = 2; // [0,4], default 2
int eos = 1; // write "end of stream" marker?
int multithreading = 1; // use multithreading if available?
char *matchfinder = "bt4"; // matchfinder algorithm
int algorithm = 2;
int res;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|iiiiiiiis", kwlist, &inFile, &dictionary, &fastBytes,
&literalContextBits, &literalPosBits, &posBits, &algorithm, &eos, &multithreading, &matchfinder))
return -1;
CHECK_RANGE(dictionary, 0, 28, "dictionary must be between 0 and 28");
CHECK_RANGE(fastBytes, 5, 255, "fastBytes must be between 5 and 255");
CHECK_RANGE(literalContextBits, 0, 8, "literalContextBits must be between 0 and 8");
CHECK_RANGE(literalPosBits, 0, 4, "literalPosBits must be between 0 and 4");
CHECK_RANGE(posBits, 0, 4, "posBits must be between 0 and 4");
CHECK_RANGE(algorithm, 0, 2, "algorithm must be between 0 and 2");
if (PyString_Check(inFile)) {
// create new cStringIO object from string
inFile = PycStringIO->NewInput(inFile);
if (inFile == NULL)
{
PyErr_NoMemory();
return -1;
}
} else if (!PyObject_HasAttrString(inFile, "read")) {
PyErr_SetString(PyExc_ValueError, "first parameter must be a file-like object");
return -1;
} else
// protect object from being refcounted out...
Py_XINCREF(inFile);
encoder = new NCompress::NLZMA::CEncoder();
CHECK_NULL(encoder);
if ((res = set_encoder_properties(encoder, dictionary, posBits, literalContextBits, literalPosBits, algorithm, fastBytes, eos, multithreading, matchfinder) != 0))
{
Py_XDECREF(inFile);
DELETE_AND_NULL(encoder);
PyErr_SetString(PyExc_TypeError, "can't set coder properties");
goto exit;
}
self->inFile = inFile;
self->encoder = encoder;
self->inStream = new CInStream(inFile);
if (self->inStream == NULL)
{
DEC_AND_NULL(self->inFile);
DELETE_AND_NULL(encoder);
DEC_AND_NULL(self);
PyErr_NoMemory();
goto exit;
}
self->outStream = new COutStream();
if (self->outStream == NULL)
{
DEC_AND_NULL(self->inFile);
DELETE_AND_NULL(encoder);
DELETE_AND_NULL(self->inStream);
DEC_AND_NULL(self);
PyErr_NoMemory();
goto exit;
}
Py_BEGIN_ALLOW_THREADS
encoder->SetStreams(self->inStream, self->outStream, 0, 0);
encoder->WriteCoderProperties(self->outStream);
Py_END_ALLOW_THREADS
result = 0;
exit:
return result;
}
#ifdef __cplusplus
}
#endif
PyTypeObject CCompressionFileObject_Type = {
//PyObject_HEAD_INIT(&PyType_Type)
PyObject_HEAD_INIT(NULL)
0,
"LZMACompressFile", /* char *tp_name; */
sizeof(CCompressionFileObject), /* int tp_basicsize; */
0, /* int tp_itemsize; // not used much */
(destructor)pylzma_compfile_dealloc, /* destructor tp_dealloc; */
NULL, /* printfunc tp_print; */
NULL, /* getattrfunc tp_getattr; // __getattr__ */
NULL, /* setattrfunc tp_setattr; // __setattr__ */
NULL, /* cmpfunc tp_compare; // __cmp__ */
NULL, /* reprfunc tp_repr; // __repr__ */
NULL, /* PyNumberMethods *tp_as_number; */
NULL, /* PySequenceMethods *tp_as_sequence; */
NULL, /* PyMappingMethods *tp_as_mapping; */
NULL, /* hashfunc tp_hash; // __hash__ */
NULL, /* ternaryfunc tp_call; // __call__ */
NULL, /* reprfunc tp_str; // __str__ */
0, /* tp_getattro*/
0, /* tp_setattro*/
0, /* tp_as_buffer*/
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
"File compression class", /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
pylzma_compfile_methods, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)pylzma_compfile_init, /* tp_init */
0, /* tp_alloc */
pylzma_compfile_new, /* tp_new */
};

View File

@@ -1,42 +0,0 @@
/*
* Python Bindings for LZMA
*
* Copyright (c) 2004-2006 by Joachim Bauch, mail@joachim-bauch.de
* 7-Zip Copyright (C) 1999-2005 Igor Pavlov
* LZMA SDK Copyright (C) 1999-2005 Igor Pavlov
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* $Id: pylzma_compressfile.h 104 2006-01-08 18:17:14Z jojo $
*
*/
#ifndef ___PYLZMA_COMPRESSFILE__H___
#define ___PYLZMA_COMPRESSFILE__H___
#ifdef __cplusplus
extern "C" {
#endif
extern PyTypeObject CCompressionFileObject_Type;
#define CompressionFileObject_Check(v) ((v)->ob_type == &CCompressionFileObject_Type)
#ifdef __cplusplus
}
#endif
#endif

View File

@@ -1,244 +0,0 @@
/*
* Python Bindings for LZMA
*
* Copyright (c) 2004-2006 by Joachim Bauch, mail@joachim-bauch.de
* 7-Zip Copyright (C) 1999-2005 Igor Pavlov
* LZMA SDK Copyright (C) 1999-2005 Igor Pavlov
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* $Id: pylzma_compressobj.cpp 104 2006-01-08 18:17:14Z jojo $
*
*/
#include <Python.h>
#include <Platform.h>
#include <7zip/7zip/IStream.h>
#include <7zip/7zip/Compress/LZMA/LZMAEncoder.h>
#include "pylzma.h"
#include "pylzma_streams.h"
#include "pylzma_compress.h"
#include "pylzma_encoder.h"
int set_encoder_properties(NCompress::NLZMA::CEncoder *encoder, int dictionary, int posBits,
int literalContextBits, int literalPosBits, int algorithm, int fastBytes, int eos,
int multithreading, const char *matchfinder);
typedef struct {
PyObject_HEAD
NCompress::NLZMA::CPYLZMAEncoder *encoder;
CInStream *inStream;
COutStream *outStream;
} CCompressionObject;
static char *doc_comp_compress = \
"docstring is todo\n";
static PyObject *pylzma_comp_compress(CCompressionObject *self, PyObject *args)
{
PyObject *result = NULL;
char *data;
int length, bufsize=BLOCK_SIZE, finished;
UINT64 inSize, outSize;
if (!PyArg_ParseTuple(args, "s#|l", &data, &length, &bufsize))
return NULL;
if (!self->inStream->AppendData((BYTE *)data, length))
{
PyErr_NoMemory();
goto exit;
}
while (true)
{
self->encoder->CodeOneBlock(&inSize, &outSize, &finished, false);
if (finished || self->outStream->getMaxRead() >= bufsize)
break;
}
length = min(self->outStream->getMaxRead(), bufsize);
result = PyString_FromStringAndSize((const char *)self->outStream->getReadPtr(), length);
if (result == NULL) {
PyErr_NoMemory();
goto exit;
}
self->outStream->increaseReadPos(length);
exit:
return result;
}
static char *doc_comp_flush = \
"flush() -- Finishes the compression and returns any remaining compressed data.";
static PyObject *pylzma_comp_flush(CCompressionObject *self, PyObject *args)
{
PyObject *result = NULL;
int finished=0;
UINT64 inSize, outSize;
if (!PyArg_ParseTuple(args, ""))
return NULL;
while (!finished)
{
self->encoder->CodeOneBlock(&inSize, &outSize, &finished, true);
}
self->encoder->FinishStream();
result = PyString_FromStringAndSize(NULL, self->outStream->getMaxRead());
self->outStream->Read(PyString_AS_STRING(result), self->outStream->getMaxRead());
return result;
}
PyMethodDef pylzma_comp_methods[] = {
{"compress", (PyCFunction)pylzma_comp_compress, METH_VARARGS, doc_comp_compress},
{"flush", (PyCFunction)pylzma_comp_flush, METH_VARARGS, doc_comp_flush},
{NULL, NULL},
};
static void pylzma_comp_dealloc(CCompressionObject *self)
{
DELETE_AND_NULL(self->encoder);
DELETE_AND_NULL(self->inStream);
DELETE_AND_NULL(self->outStream);
PyObject_Del(self);
}
static PyObject *pylzma_comp_getattr(CCompressionObject *self, char *attrname)
{
return Py_FindMethod(pylzma_comp_methods, (PyObject *)self, attrname);
}
static int pylzma_comp_setattr(CCompressionObject *self, char *attrname, PyObject *value)
{
// disable setting of attributes
PyErr_Format(PyExc_AttributeError, "no attribute named '%s'", attrname);
return -1;
}
PyTypeObject CompressionObject_Type = {
//PyObject_HEAD_INIT(&PyType_Type)
PyObject_HEAD_INIT(NULL)
0,
"LZMACompress", /* char *tp_name; */
sizeof(CCompressionObject), /* int tp_basicsize; */
0, /* int tp_itemsize; // not used much */
(destructor)pylzma_comp_dealloc, /* destructor tp_dealloc; */
NULL, /* printfunc tp_print; */
(getattrfunc)pylzma_comp_getattr, /* getattrfunc tp_getattr; // __getattr__ */
(setattrfunc)pylzma_comp_setattr, /* setattrfunc tp_setattr; // __setattr__ */
NULL, /* cmpfunc tp_compare; // __cmp__ */
NULL, /* reprfunc tp_repr; // __repr__ */
NULL, /* PyNumberMethods *tp_as_number; */
NULL, /* PySequenceMethods *tp_as_sequence; */
NULL, /* PyMappingMethods *tp_as_mapping; */
NULL, /* hashfunc tp_hash; // __hash__ */
NULL, /* ternaryfunc tp_call; // __call__ */
NULL, /* reprfunc tp_str; // __str__ */
};
#ifdef __cplusplus
extern "C"
#endif
const char doc_compressobj[] = \
"compressobj() -- Returns object that can be used for compression.";
#ifdef __cplusplus
extern "C" {
#endif
PyObject *pylzma_compressobj(PyObject *self, PyObject *args, PyObject *kwargs)
{
CCompressionObject *result=NULL;
NCompress::NLZMA::CPYLZMAEncoder *encoder;
// possible keywords for this function
static char *kwlist[] = {"dictionary", "fastBytes", "literalContextBits",
"literalPosBits", "posBits", "algorithm", "eos", "multithreading", "matchfinder", NULL};
int dictionary = 23; // [0,28], default 23 (8MB)
int fastBytes = 128; // [5,255], default 128
int literalContextBits = 3; // [0,8], default 3
int literalPosBits = 0; // [0,4], default 0
int posBits = 2; // [0,4], default 2
int eos = 1; // write "end of stream" marker?
int multithreading = 1; // use multithreading if available?
char *matchfinder = "bt4"; // matchfinder algorithm
int algorithm = 2;
int res;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|iiiiiiiis", kwlist, &dictionary, &fastBytes,
&literalContextBits, &literalPosBits, &posBits, &algorithm, &eos, &multithreading, &matchfinder))
return NULL;
CHECK_RANGE(dictionary, 0, 28, "dictionary must be between 0 and 28");
CHECK_RANGE(fastBytes, 5, 255, "fastBytes must be between 5 and 255");
CHECK_RANGE(literalContextBits, 0, 8, "literalContextBits must be between 0 and 8");
CHECK_RANGE(literalPosBits, 0, 4, "literalPosBits must be between 0 and 4");
CHECK_RANGE(posBits, 0, 4, "posBits must be between 0 and 4");
encoder = new NCompress::NLZMA::CPYLZMAEncoder();
CHECK_NULL(encoder);
if ((res = set_encoder_properties(encoder, dictionary, posBits, literalContextBits, literalPosBits, algorithm, fastBytes, eos, multithreading, matchfinder) != 0))
{
delete encoder;
PyErr_SetString(PyExc_TypeError, "can't set coder properties");
goto exit;
}
result = PyObject_New(CCompressionObject, &CompressionObject_Type);
if (result == NULL)
{
DELETE_AND_NULL(encoder);
PyErr_NoMemory();
goto exit;
}
result->encoder = encoder;
result->inStream = new CInStream();
if (result->inStream == NULL)
{
DELETE_AND_NULL(encoder);
DEC_AND_NULL(result);
PyErr_NoMemory();
goto exit;
}
result->outStream = new COutStream();
if (result->outStream == NULL)
{
DELETE_AND_NULL(encoder);
DELETE_AND_NULL(result->inStream);
DEC_AND_NULL(result);
PyErr_NoMemory();
goto exit;
}
Py_BEGIN_ALLOW_THREADS
encoder->SetStreams(result->inStream, result->outStream, 0, 0);
encoder->WriteCoderProperties(result->outStream);
Py_END_ALLOW_THREADS
exit:
return (PyObject *)result;
}
#ifdef __cplusplus
}
#endif

View File

@@ -1,36 +0,0 @@
/*
* Python Bindings for LZMA
*
* Copyright (c) 2004-2006 by Joachim Bauch, mail@joachim-bauch.de
* 7-Zip Copyright (C) 1999-2005 Igor Pavlov
* LZMA SDK Copyright (C) 1999-2005 Igor Pavlov
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* $Id: pylzma_compressobj.h 104 2006-01-08 18:17:14Z jojo $
*
*/
#ifndef ___PYLZMA_COMPRESSOBJ__H___
#define ___PYLZMA_COMPRESSOBJ__H___
extern PyTypeObject CCompressionObject_Type;
#define CompressionObject_Check(v) ((v)->ob_type == &CCompressionObject_Type)
extern const char doc_compressobj[];
PyObject *pylzma_compressobj(PyObject *self, PyObject *args);
#endif

View File

@@ -1,157 +0,0 @@
/*
* Python Bindings for LZMA
*
* Copyright (c) 2004-2006 by Joachim Bauch, mail@joachim-bauch.de
* 7-Zip Copyright (C) 1999-2005 Igor Pavlov
* LZMA SDK Copyright (C) 1999-2005 Igor Pavlov
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* $Id: pylzma_decompress.c 104 2006-01-08 18:17:14Z jojo $
*
*/
#include <Python.h>
#include <7zip/LzmaStateDecode.h>
#include "pylzma.h"
void free_lzma_state(CLzmaDecoderState *state)
{
if (state->Probs)
free(state->Probs);
state->Probs = NULL;
if (state->Dictionary)
free(state->Dictionary);
state->Dictionary = NULL;
}
const char doc_decompress[] = \
"decompress(data[, maxlength]) -- Decompress the data, returning a string containing the decompressed data. "\
"If the string has been compressed without an EOS marker, you must provide the maximum length as keyword parameter.\n" \
"decompress(data, bufsize[, maxlength]) -- Decompress the data using an initial output buffer of size bufsize. "\
"If the string has been compressed without an EOS marker, you must provide the maximum length as keyword parameter.\n";
PyObject *pylzma_decompress(PyObject *self, PyObject *args, PyObject *kwargs)
{
unsigned char *data, *tmp;
int length, blocksize=BLOCK_SIZE, outsize, outavail, totallength=-1, bufsize;
PyObject *result = NULL, *output=NULL;
CLzmaDecoderState state;
unsigned char properties[LZMA_PROPERTIES_SIZE];
int res;
// possible keywords for this function
static char *kwlist[] = {"data", "bufsize", "maxlength", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s#|ll", kwlist, &data, &length, &blocksize, &totallength))
return NULL;
memset(&state, 0, sizeof(state));
if (!(output = PyString_FromStringAndSize(NULL, blocksize)))
{
PyErr_NoMemory();
goto exit;
}
// Initialize LZMA state decoder
memcpy(&properties, data, sizeof(properties));
data += sizeof(properties);
length -= sizeof(properties);
if (LzmaDecodeProperties(&state.Properties, properties, LZMA_PROPERTIES_SIZE) != LZMA_RESULT_OK)
{
PyErr_SetString(PyExc_TypeError, "Incorrect stream properties");
goto exit;
}
state.Probs = (CProb *)malloc(LzmaGetNumProbs(&state.Properties) * sizeof(CProb));
if (state.Probs == 0) {
PyErr_NoMemory();
goto exit;
}
if (state.Properties.DictionarySize == 0)
state.Dictionary = 0;
else {
state.Dictionary = (unsigned char *)malloc(state.Properties.DictionarySize);
if (state.Dictionary == 0) {
free(state.Probs);
state.Probs = NULL;
PyErr_NoMemory();
goto exit;
}
}
LzmaDecoderInit(&state);
// decompress data
tmp = (unsigned char *)PyString_AS_STRING(output);
outsize = 0;
outavail = blocksize;
while (1)
{
SizeT inProcessed, outProcessed;
int finishDecoding = 1;
bufsize = outavail;
Py_BEGIN_ALLOW_THREADS
if (totallength != -1)
// We know the total size of the decompressed string
res = LzmaDecode(&state, data, length, &inProcessed,
tmp, outavail > totallength ? totallength : outavail, &outProcessed, finishDecoding);
else
// Decompress until EOS marker is reached
res = LzmaDecode(&state, data, length, &inProcessed,
tmp, outavail, &outProcessed, finishDecoding);
Py_END_ALLOW_THREADS
if (res != 0) {
PyErr_SetString(PyExc_ValueError, "data error during decompression");
goto exit;
}
length -= inProcessed;
data += inProcessed;
outsize += outProcessed;
tmp += outProcessed;
outavail -= outProcessed;
if (totallength != -1)
totallength -= outProcessed;
if (length > 0 || outProcessed == bufsize) {
// Target block is full, increase size...
if (_PyString_Resize(&output, outsize+outavail+BLOCK_SIZE) != 0)
goto exit;
outavail += BLOCK_SIZE;
tmp = (unsigned char *)&PyString_AS_STRING(output)[outsize];
} else
// Finished decompressing
break;
}
// Decrease length of result to total output size
if (_PyString_Resize(&output, outsize) != 0)
goto exit;
result = output;
output = NULL;
exit:
free_lzma_state(&state);
Py_XDECREF(output);
return result;
}

View File

@@ -1,36 +0,0 @@
/*
* Python Bindings for LZMA
*
* Copyright (c) 2004-2006 by Joachim Bauch, mail@joachim-bauch.de
* 7-Zip Copyright (C) 1999-2005 Igor Pavlov
* LZMA SDK Copyright (C) 1999-2005 Igor Pavlov
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* $Id: pylzma_decompress.h 104 2006-01-08 18:17:14Z jojo $
*
*/
#ifndef ___PYLZMA_DECOMPRESS__H___
#define ___PYLZMA_DECOMPRESS__H___
#include <Python.h>
#include <7zip/LzmaStateDecode.h>
extern const char doc_decompress[];
void free_lzma_state(CLzmaDecoderState *stream);
PyObject *pylzma_decompress(PyObject *self, PyObject *args);
#endif

View File

@@ -1,115 +0,0 @@
/*
* Python Bindings for LZMA
*
* Copyright (c) 2004-2006 by Joachim Bauch, mail@joachim-bauch.de
* 7-Zip Copyright (C) 1999-2005 Igor Pavlov
* LZMA SDK Copyright (C) 1999-2005 Igor Pavlov
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* $Id: pylzma_decompress_compat.c 104 2006-01-08 18:17:14Z jojo $
*
*/
#include <Python.h>
#include <7zip/LzmaCompatDecode.h>
#include "pylzma.h"
void free_lzma_stream(lzma_stream *stream)
{
if (stream->dynamicData)
lzmafree(stream->dynamicData);
stream->dynamicData = NULL;
if (stream->dictionary)
lzmafree(stream->dictionary);
stream->dictionary = NULL;
}
const char doc_decompress_compat[] = \
"decompress_compat(string) -- Decompress the data in string, returning a string containing the decompressed data.\n" \
"decompress_compat(string, bufsize) -- Decompress the data in string using an initial output buffer of size bufsize.\n";
PyObject *pylzma_decompress_compat(PyObject *self, PyObject *args)
{
char *data;
int length, blocksize=BLOCK_SIZE;
PyObject *result = NULL;
lzma_stream stream;
int res;
char *output;
if (!PyArg_ParseTuple(args, "s#|l", &data, &length, &blocksize))
return NULL;
memset(&stream, 0, sizeof(stream));
if (!(output = (char *)malloc(blocksize)))
{
PyErr_NoMemory();
goto exit;
}
lzmaCompatInit(&stream);
stream.next_in = (Byte *)data;
stream.avail_in = length;
stream.next_out = (Byte *)output;
stream.avail_out = blocksize;
// decompress data
while (1)
{
Py_BEGIN_ALLOW_THREADS
res = lzmaCompatDecode(&stream);
Py_END_ALLOW_THREADS
if (res == LZMA_STREAM_END) {
break;
} else if (res == LZMA_NOT_ENOUGH_MEM) {
// out of memory during decompression
PyErr_NoMemory();
goto exit;
} else if (res == LZMA_DATA_ERROR) {
PyErr_SetString(PyExc_ValueError, "data error during decompression");
goto exit;
} else if (res == LZMA_OK) {
// check if we need to adjust the output buffer
if (stream.avail_out == 0)
{
output = (char *)realloc(output, blocksize+BLOCK_SIZE);
stream.avail_out = BLOCK_SIZE;
stream.next_out = (Byte *)&output[blocksize];
blocksize += BLOCK_SIZE;
};
} else {
PyErr_Format(PyExc_ValueError, "unknown return code from lzmaDecode: %d", res);
goto exit;
}
// if we exit here, decompression finished without returning LZMA_STREAM_END
// XXX: why is this sometimes?
if (stream.avail_in == 0)
break;
}
result = PyString_FromStringAndSize(output, stream.totalOut);
exit:
free_lzma_stream(&stream);
if (output != NULL)
free(output);
return result;
}

View File

@@ -1,36 +0,0 @@
/*
* Python Bindings for LZMA
*
* Copyright (c) 2004-2006 by Joachim Bauch, mail@joachim-bauch.de
* 7-Zip Copyright (C) 1999-2005 Igor Pavlov
* LZMA SDK Copyright (C) 1999-2005 Igor Pavlov
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* $Id: pylzma_decompress_compat.h 104 2006-01-08 18:17:14Z jojo $
*
*/
#ifndef ___PYLZMA_DECOMPRESS_COMPAT__H___
#define ___PYLZMA_DECOMPRESS_COMPAT__H___
#include <Python.h>
#include <7zip/LzmaCompatDecode.h>
extern const char doc_decompress_compat[];
void free_lzma_stream(lzma_stream *stream);
PyObject *pylzma_decompress_compat(PyObject *self, PyObject *args);
#endif

View File

@@ -1,362 +0,0 @@
/*
* Python Bindings for LZMA
*
* Copyright (c) 2004-2006 by Joachim Bauch, mail@joachim-bauch.de
* 7-Zip Copyright (C) 1999-2005 Igor Pavlov
* LZMA SDK Copyright (C) 1999-2005 Igor Pavlov
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* $Id: pylzma_decompressobj.c 116 2006-09-28 21:46:20Z jojo $
*
*/
#include <Python.h>
#include <7zip/LzmaStateDecode.h>
#include "pylzma.h"
#include "pylzma_decompress.h"
#include "pylzma_decompressobj.h"
int pylzma_decomp_init(CDecompressionObject *self, PyObject *args, PyObject *kwargs)
{
int max_length = -1;
// possible keywords for this function
static char *kwlist[] = {"maxlength", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|i", kwlist, &max_length))
return -1;
if (max_length == 0 || max_length < -1) {
PyErr_SetString(PyExc_ValueError, "the decompressed size must be greater than zero");
return -1;
}
self->unconsumed_tail = NULL;
self->unconsumed_length = 0;
self->need_properties = 1;
self->max_length = max_length;
self->total_out = 0;
memset(&self->state, 0, sizeof(self->state));
return 0;
}
static const char doc_decomp_decompress[] = \
"decompress(data[, bufsize]) -- Returns a string containing the up to bufsize decompressed bytes of the data.\n" \
"After calling, some of the input data may be available in internal buffers for later processing.";
static PyObject *pylzma_decomp_decompress(CDecompressionObject *self, PyObject *args)
{
PyObject *result=NULL;
unsigned char *data, *next_in, *next_out;
int length, start_total_out, res, max_length=BLOCK_SIZE;
SizeT avail_in, avail_out;
unsigned char properties[LZMA_PROPERTIES_SIZE];
SizeT inProcessed, outProcessed;
if (!PyArg_ParseTuple(args, "s#|l", &data, &length, &max_length))
return NULL;
if (max_length <= 0)
{
PyErr_SetString(PyExc_ValueError, "bufsize must be greater than zero");
return NULL;
}
start_total_out = self->total_out;
if (self->unconsumed_length > 0) {
self->unconsumed_tail = (unsigned char *)realloc(self->unconsumed_tail, self->unconsumed_length + length);
next_in = (unsigned char *)self->unconsumed_tail;
memcpy(next_in + self->unconsumed_length, data, length);
} else
next_in = data;
avail_in = self->unconsumed_length + length;
if (self->need_properties && avail_in < sizeof(properties)) {
// we need enough bytes to read the properties
if (!self->unconsumed_length) {
self->unconsumed_tail = (unsigned char *)malloc(length);
memcpy(self->unconsumed_tail, data, length);
}
self->unconsumed_length += length;
return PyString_FromString("");
}
if (self->need_properties) {
self->need_properties = 0;
memcpy(&properties, next_in, sizeof(properties));
avail_in -= sizeof(properties);
next_in += sizeof(properties);
if (self->unconsumed_length >= sizeof(properties)-length) {
self->unconsumed_length -= sizeof(properties)-length;
if (self->unconsumed_length > 0) {
memcpy(self->unconsumed_tail, self->unconsumed_tail+sizeof(properties), self->unconsumed_length);
self->unconsumed_tail = (unsigned char *)realloc(self->unconsumed_tail, self->unconsumed_length);
} else
FREE_AND_NULL(self->unconsumed_tail);
}
if (LzmaDecodeProperties(&self->state.Properties, properties, LZMA_PROPERTIES_SIZE) != LZMA_RESULT_OK)
{
PyErr_SetString(PyExc_TypeError, "Incorrect stream properties");
goto exit;
}
self->state.Probs = (CProb *)malloc(LzmaGetNumProbs(&self->state.Properties) * sizeof(CProb));
if (self->state.Probs == 0) {
PyErr_NoMemory();
goto exit;
}
if (self->state.Properties.DictionarySize == 0)
self->state.Dictionary = 0;
else {
self->state.Dictionary = (unsigned char *)malloc(self->state.Properties.DictionarySize);
if (self->state.Dictionary == 0) {
free(self->state.Probs);
self->state.Probs = NULL;
PyErr_NoMemory();
goto exit;
}
}
LzmaDecoderInit(&self->state);
}
if (avail_in == 0)
// no more bytes to decompress
return PyString_FromString("");
if (!(result = PyString_FromStringAndSize(NULL, max_length)))
return NULL;
next_out = (unsigned char *)PyString_AS_STRING(result);
avail_out = max_length;
Py_BEGIN_ALLOW_THREADS
// Decompress until EOS marker is reached
res = LzmaDecode(&self->state, next_in, avail_in, &inProcessed,
next_out, avail_out, &outProcessed, 0);
Py_END_ALLOW_THREADS
self->total_out += outProcessed;
next_in += inProcessed;
avail_in -= inProcessed;
next_out += outProcessed;
avail_out -= outProcessed;
if (res != LZMA_RESULT_OK) {
PyErr_SetString(PyExc_ValueError, "data error during decompression");
DEC_AND_NULL(result);
goto exit;
}
/* Not all of the compressed data could be accomodated in the output buffer
of specified size. Return the unconsumed tail in an attribute.*/
if (avail_in > 0)
{
if (avail_in != self->unconsumed_length) {
if (avail_in > self->unconsumed_length) {
self->unconsumed_tail = (unsigned char *)realloc(self->unconsumed_tail, avail_in);
memcpy(self->unconsumed_tail, next_in, avail_in);
}
if (avail_in < self->unconsumed_length) {
memcpy(self->unconsumed_tail, next_in, avail_in);
self->unconsumed_tail = (unsigned char *)realloc(self->unconsumed_tail, avail_in);
}
}
if (!self->unconsumed_tail) {
PyErr_NoMemory();
DEC_AND_NULL(result);
goto exit;
}
} else
FREE_AND_NULL(self->unconsumed_tail);
self->unconsumed_length = avail_in;
_PyString_Resize(&result, self->total_out - start_total_out);
exit:
return result;
}
static const char doc_decomp_flush[] = \
"flush() -- Return remaining data.";
static PyObject *pylzma_decomp_flush(CDecompressionObject *self, PyObject *args)
{
PyObject *result=NULL;
int res;
SizeT avail_out, outsize;
unsigned char *tmp;
SizeT inProcessed, outProcessed;
if (!PyArg_ParseTuple(args, ""))
return NULL;
if (self->max_length != -1)
avail_out = self->max_length - self->total_out;
else
avail_out = BLOCK_SIZE;
if (avail_out == 0)
// no more remaining data
return PyString_FromString("");
result = PyString_FromStringAndSize(NULL, avail_out);
if (result == NULL)
return NULL;
tmp = (unsigned char *)PyString_AS_STRING(result);
outsize = 0;
while (1) {
Py_BEGIN_ALLOW_THREADS
if (self->unconsumed_length == 0)
// No remaining data
res = LzmaDecode(&self->state, (unsigned char *)"", 0, &inProcessed,
tmp, avail_out, &outProcessed, 1);
else {
// Decompress remaining data
res = LzmaDecode(&self->state, self->unconsumed_tail, self->unconsumed_length, &inProcessed,
tmp, avail_out, &outProcessed, 1);
self->unconsumed_length -= inProcessed;
if (self->unconsumed_length > 0)
memcpy(self->unconsumed_tail, self->unconsumed_tail + inProcessed, self->unconsumed_length);
else
FREE_AND_NULL(self->unconsumed_tail);
}
Py_END_ALLOW_THREADS
if (res != LZMA_RESULT_OK) {
PyErr_SetString(PyExc_ValueError, "data error during decompression");
DEC_AND_NULL(result);
goto exit;
}
self->total_out += outProcessed;
outsize += outProcessed;
if (outProcessed < avail_out || (outProcessed == avail_out && self->max_length != -1))
break;
if (self->max_length != -1) {
PyErr_SetString(PyExc_ValueError, "not enough input data for decompression");
DEC_AND_NULL(result);
goto exit;
}
avail_out -= outProcessed;
// Output buffer is full, might be more data for decompression
if (_PyString_Resize(&result, outsize+BLOCK_SIZE) != 0)
goto exit;
avail_out += BLOCK_SIZE;
tmp = (unsigned char *)PyString_AS_STRING(result) + outsize;
}
if (outsize != PyString_GET_SIZE(result))
_PyString_Resize(&result, outsize);
exit:
return result;
}
static const char doc_decomp_reset[] = \
"reset([maxlength]) -- Resets the decompression object.";
static PyObject *pylzma_decomp_reset(CDecompressionObject *self, PyObject *args, PyObject *kwargs)
{
PyObject *result=NULL;
int max_length = -1;
// possible keywords for this function
static char *kwlist[] = {"maxlength", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|i", kwlist, &max_length))
return NULL;
free_lzma_state(&self->state);
memset(&self->state, 0, sizeof(self->state));
FREE_AND_NULL(self->unconsumed_tail);
self->unconsumed_length = 0;
self->need_properties = 1;
self->total_out = 0;
self->max_length = max_length;
result = Py_None;
Py_XINCREF(result);
return result;
}
static PyMethodDef pylzma_decomp_methods[] = {
{"decompress", (PyCFunction)pylzma_decomp_decompress, METH_VARARGS, (char *)&doc_decomp_decompress},
{"flush", (PyCFunction)pylzma_decomp_flush, METH_VARARGS, (char *)&doc_decomp_flush},
{"reset", (PyCFunction)pylzma_decomp_reset, METH_VARARGS | METH_KEYWORDS, (char *)&doc_decomp_reset},
{NULL, NULL},
};
static void pylzma_decomp_dealloc(CDecompressionObject *self)
{
free_lzma_state(&self->state);
FREE_AND_NULL(self->unconsumed_tail);
self->ob_type->tp_free((PyObject*)self);
}
PyTypeObject CDecompressionObject_Type = {
//PyObject_HEAD_INIT(&PyType_Type)
PyObject_HEAD_INIT(NULL)
0,
"LZMADecompress", /* char *tp_name; */
sizeof(CDecompressionObject), /* int tp_basicsize; */
0, /* int tp_itemsize; // not used much */
(destructor)pylzma_decomp_dealloc, /* destructor tp_dealloc; */
NULL, /* printfunc tp_print; */
NULL, /* getattrfunc tp_getattr; // __getattr__ */
NULL, /* setattrfunc tp_setattr; // __setattr__ */
NULL, /* cmpfunc tp_compare; // __cmp__ */
NULL, /* reprfunc tp_repr; // __repr__ */
NULL, /* PyNumberMethods *tp_as_number; */
NULL, /* PySequenceMethods *tp_as_sequence; */
NULL, /* PyMappingMethods *tp_as_mapping; */
NULL, /* hashfunc tp_hash; // __hash__ */
NULL, /* ternaryfunc tp_call; // __call__ */
NULL, /* reprfunc tp_str; // __str__ */
0, /* tp_getattro*/
0, /* tp_setattro*/
0, /* tp_as_buffer*/
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
"Decompression class", /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
pylzma_decomp_methods, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)pylzma_decomp_init, /* tp_init */
0, /* tp_alloc */
0, /* tp_new */
};

View File

@@ -1,46 +0,0 @@
/*
* Python Bindings for LZMA
*
* Copyright (c) 2004-2006 by Joachim Bauch, mail@joachim-bauch.de
* 7-Zip Copyright (C) 1999-2005 Igor Pavlov
* LZMA SDK Copyright (C) 1999-2005 Igor Pavlov
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* $Id: pylzma_decompressobj.h 104 2006-01-08 18:17:14Z jojo $
*
*/
#ifndef ___PYLZMA_DECOMPRESSOBJ__H___
#define ___PYLZMA_DECOMPRESSOBJ__H___
#include <Python.h>
#include <7zip/LzmaStateDecode.h>
typedef struct {
PyObject_HEAD
CLzmaDecoderState state;
SizeT max_length;
SizeT total_out;
unsigned char *unconsumed_tail;
SizeT unconsumed_length;
int need_properties;
} CDecompressionObject;
extern PyTypeObject CDecompressionObject_Type;
#define DecompressionObject_Check(v) ((v)->ob_type == &CDecompressionObject_Type)
#endif

View File

@@ -1,259 +0,0 @@
/*
* Python Bindings for LZMA
*
* Copyright (c) 2004-2006 by Joachim Bauch, mail@joachim-bauch.de
* 7-Zip Copyright (C) 1999-2005 Igor Pavlov
* LZMA SDK Copyright (C) 1999-2005 Igor Pavlov
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* $Id: pylzma_decompressobj_compat.c 104 2006-01-08 18:17:14Z jojo $
*
*/
#include <Python.h>
#include <7zip/LzmaCompatDecode.h>
#include "pylzma.h"
#include "pylzma_decompress_compat.h"
#include "pylzma_decompressobj_compat.h"
static const char doc_decomp_decompress[] = \
"decompress(data[, bufsize]) -- Returns a string containing the up to bufsize decompressed bytes of the data.\n" \
"After calling, some of the input data may be available in internal buffers for later processing.";
static PyObject *pylzma_decomp_decompress(CCompatDecompressionObject *self, PyObject *args)
{
PyObject *result=NULL;
char *data;
int length, old_length, start_total_out, res, max_length=BLOCK_SIZE;
if (!PyArg_ParseTuple(args, "s#|l", &data, &length, &max_length))
return NULL;
if (max_length < 0)
{
PyErr_SetString(PyExc_ValueError, "bufsize must be greater than zero");
return NULL;
}
start_total_out = self->stream.totalOut;
if (self->unconsumed_length > 0) {
self->unconsumed_tail = (char *)realloc(self->unconsumed_tail, self->unconsumed_length + length);
self->stream.next_in = (Byte *)self->unconsumed_tail;
memcpy(self->stream.next_in + self->unconsumed_length, data, length);
} else
self->stream.next_in = (Byte *)data;
self->stream.avail_in = self->unconsumed_length + length;
if (max_length && max_length < length)
length = max_length;
if (!(result = PyString_FromStringAndSize(NULL, length)))
return NULL;
self->stream.next_out = (unsigned char *)PyString_AS_STRING(result);
self->stream.avail_out = length;
Py_BEGIN_ALLOW_THREADS
res = lzmaCompatDecode(&self->stream);
Py_END_ALLOW_THREADS
while (res == LZMA_OK && self->stream.avail_out == 0)
{
if (max_length && length >= max_length)
break;
old_length = length;
length <<= 1;
if (max_length && length > max_length)
length = max_length;
if (_PyString_Resize(&result, length) < 0)
goto exit;
self->stream.avail_out = length - old_length;
self->stream.next_out = (Byte *)PyString_AS_STRING(result) + old_length;
Py_BEGIN_ALLOW_THREADS
res = lzmaCompatDecode(&self->stream);
Py_END_ALLOW_THREADS
}
if (res == LZMA_NOT_ENOUGH_MEM) {
// out of memory during decompression
PyErr_NoMemory();
DEC_AND_NULL(result);
goto exit;
} else if (res == LZMA_DATA_ERROR) {
PyErr_SetString(PyExc_ValueError, "data error during decompression");
DEC_AND_NULL(result);
goto exit;
} else if (res != LZMA_OK && res != LZMA_STREAM_END) {
PyErr_Format(PyExc_ValueError, "unknown return code from lzmaDecode: %d", res);
DEC_AND_NULL(result);
goto exit;
}
/* Not all of the compressed data could be accomodated in the output buffer
of specified size. Return the unconsumed tail in an attribute.*/
if (max_length != 0) {
if (self->stream.avail_in > 0)
{
if (self->stream.avail_in != self->unconsumed_length)
self->unconsumed_tail = (char *)realloc(self->unconsumed_tail, self->stream.avail_in);
if (!self->unconsumed_tail) {
PyErr_NoMemory();
DEC_AND_NULL(result);
goto exit;
}
memcpy(self->unconsumed_tail, self->stream.next_in, self->stream.avail_in);
} else
FREE_AND_NULL(self->unconsumed_tail);
self->unconsumed_length = self->stream.avail_in;
}
/* The end of the compressed data has been reached, so set the
unused_data attribute to a string containing the remainder of the
data in the string. Note that this is also a logical place to call
inflateEnd, but the old behaviour of only calling it on flush() is
preserved.
*/
if (res == LZMA_STREAM_END) {
Py_XDECREF(self->unused_data); /* Free original empty string */
self->unused_data = PyString_FromStringAndSize((char *)self->stream.next_in, self->stream.avail_in);
if (self->unused_data == NULL) {
PyErr_NoMemory();
DEC_AND_NULL(result);
goto exit;
}
}
_PyString_Resize(&result, self->stream.totalOut - start_total_out);
exit:
return result;
}
static const char doc_decomp_reset[] = \
"reset() -- Resets the decompression object.";
static PyObject *pylzma_decomp_reset(CCompatDecompressionObject *self, PyObject *args)
{
PyObject *result=NULL;
if (!PyArg_ParseTuple(args, ""))
return NULL;
lzmaCompatInit(&self->stream);
FREE_AND_NULL(self->unconsumed_tail);
self->unconsumed_length = 0;
Py_DECREF(self->unused_data);
self->unused_data = PyString_FromString("");
CHECK_NULL(self->unused_data);
result = Py_None;
Py_XINCREF(result);
exit:
return result;
}
PyMethodDef pylzma_decomp_compat_methods[] = {
{"decompress", (PyCFunction)pylzma_decomp_decompress, METH_VARARGS, (char *)&doc_decomp_decompress},
{"reset", (PyCFunction)pylzma_decomp_reset, METH_VARARGS, (char *)&doc_decomp_reset},
{NULL, NULL},
};
static void pylzma_decomp_dealloc(CCompatDecompressionObject *self)
{
free_lzma_stream(&self->stream);
FREE_AND_NULL(self->unconsumed_tail);
DEC_AND_NULL(self->unused_data);
PyObject_Del(self);
}
static PyObject *pylzma_decomp_getattr(CCompatDecompressionObject *self, char *attrname)
{
if (strcmp(attrname, "unused_data") == 0) {
Py_INCREF(self->unused_data);
return self->unused_data;
} else
return Py_FindMethod(pylzma_decomp_compat_methods, (PyObject *)self, attrname);
}
static int pylzma_decomp_setattr(CCompatDecompressionObject *self, char *attrname, PyObject *value)
{
// disable setting of attributes
PyErr_Format(PyExc_AttributeError, "no attribute named '%s'", attrname);
return -1;
}
PyTypeObject CompatDecompressionObject_Type = {
//PyObject_HEAD_INIT(&PyType_Type)
PyObject_HEAD_INIT(NULL)
0,
"LZMACompatDecompress", /* char *tp_name; */
sizeof(CCompatDecompressionObject), /* int tp_basicsize; */
0, /* int tp_itemsize; // not used much */
(destructor)pylzma_decomp_dealloc, /* destructor tp_dealloc; */
NULL, /* printfunc tp_print; */
(getattrfunc)pylzma_decomp_getattr, /* getattrfunc tp_getattr; // __getattr__ */
(setattrfunc)pylzma_decomp_setattr, /* setattrfunc tp_setattr; // __setattr__ */
NULL, /* cmpfunc tp_compare; // __cmp__ */
NULL, /* reprfunc tp_repr; // __repr__ */
NULL, /* PyNumberMethods *tp_as_number; */
NULL, /* PySequenceMethods *tp_as_sequence; */
NULL, /* PyMappingMethods *tp_as_mapping; */
NULL, /* hashfunc tp_hash; // __hash__ */
NULL, /* ternaryfunc tp_call; // __call__ */
NULL, /* reprfunc tp_str; // __str__ */
};
const char doc_decompressobj_compat[] = \
"decompressobj_compat() -- Returns object that can be used for decompression.";
PyObject *pylzma_decompressobj_compat(PyObject *self, PyObject *args)
{
CCompatDecompressionObject *result=NULL;
if (!PyArg_ParseTuple(args, ""))
goto exit;
result = PyObject_New(CCompatDecompressionObject, &CompatDecompressionObject_Type);
CHECK_NULL(result);
result->unconsumed_tail = NULL;
result->unconsumed_length = 0;
result->unused_data = PyString_FromString("");
if (result->unused_data == NULL)
{
PyErr_NoMemory();
PyObject_Del(result);
result = NULL;
goto exit;
}
memset(&result->stream, 0, sizeof(result->stream));
lzmaCompatInit(&result->stream);
exit:
return (PyObject *)result;
}

View File

@@ -1,47 +0,0 @@
/*
* Python Bindings for LZMA
*
* Copyright (c) 2004-2006 by Joachim Bauch, mail@joachim-bauch.de
* 7-Zip Copyright (C) 1999-2005 Igor Pavlov
* LZMA SDK Copyright (C) 1999-2005 Igor Pavlov
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* $Id: pylzma_decompressobj_compat.h 104 2006-01-08 18:17:14Z jojo $
*
*/
#ifndef ___PYLZMA_DECOMPRESSOBJ_COMPAT__H___
#define ___PYLZMA_DECOMPRESSOBJ_COMPAT__H___
#include <Python.h>
#include <7zip/LzmaCompatDecode.h>
typedef struct {
PyObject_HEAD
lzma_stream stream;
char *unconsumed_tail;
int unconsumed_length;
PyObject *unused_data;
} CCompatDecompressionObject;
extern PyTypeObject CCompatDecompressionObject_Type;
#define CompatDecompressionObject_Check(v) ((v)->ob_type == &CCompatDecompressionObject_Type)
extern const char doc_decompressobj_compat[];
PyObject *pylzma_decompressobj_compat(PyObject *self, PyObject *args);
#endif

View File

@@ -1,226 +0,0 @@
/*
* Python Bindings for LZMA
*
* Copyright (c) 2004-2006 by Joachim Bauch, mail@joachim-bauch.de
* 7-Zip Copyright (C) 1999-2005 Igor Pavlov
* LZMA SDK Copyright (C) 1999-2005 Igor Pavlov
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* $Id: pylzma_encoder.cpp 104 2006-01-08 18:17:14Z jojo $
*
*/
#include <stdio.h>
#include "Platform.h"
#include "pylzma_encoder.h"
#include <7zip/7zip/Compress/LZMA/LZMAEncoder.h>
#include <7zip/7zip/Compress/LZ/LZInWindow.h>
namespace NCompress {
namespace NLZMA {
HRESULT CPYLZMAEncoder::CodeOneBlock(UINT64 *inSize, UINT64 *outSize, INT32 *finished, bool flush)
{
if (_inStream != 0)
{
RINOK(_matchFinder->Init(_inStream));
_inStream = 0;
state = 0;
}
*finished = 1;
if (state > 0 && state < 4)
_matchFinder->ResetStreamEndReached();
switch (state)
{
case 0: goto state0;
case 1: goto state1;
case 2: goto state2;
case 3: goto state3;
case 4: goto state4;
}
state0:
if (_finished)
{
return S_OK;
}
_finished = true;
progressPosValuePrev = nowPos64;
if (nowPos64 == 0)
{
state1:
if (_matchFinder->GetNumAvailableBytes() == 0)
{
state = 1;
return S_OK;
}
ReadMatchDistances();
UINT32 posState = UINT32(nowPos64) & _posStateMask;
_mainChoiceEncoders[_state.Index][posState].Encode(&_rangeEncoder, kMainChoiceLiteralIndex);
_state.UpdateChar();
BYTE curByte = _matchFinder->GetIndexByte(0 - _additionalOffset);
_literalEncoder.Encode(&_rangeEncoder, UINT32(nowPos64), _previousByte,
false, 0, curByte);
_previousByte = curByte;
_additionalOffset--;
nowPos64++;
}
state2:
if (_matchFinder->GetNumAvailableBytes() == 0)
{
state = 2;
return S_OK;
}
while(true)
{
state4:
posState = UINT32(nowPos64) & _posStateMask;
if (_fastMode)
len = GetOptimumFast(pos, UINT32(nowPos64));
else
len = GetOptimum(pos, UINT32(nowPos64));
if(len == 1 && pos == (UINT32)(-1))
{
_mainChoiceEncoders[_state.Index][posState].Encode(&_rangeEncoder, kMainChoiceLiteralIndex);
_state.UpdateChar();
BYTE matchByte = 0;
if(_peviousIsMatch)
matchByte = _matchFinder->GetIndexByte(0 - _repDistances[0] - 1 - _additionalOffset);
BYTE curByte = _matchFinder->GetIndexByte(0 - _additionalOffset);
_literalEncoder.Encode(&_rangeEncoder, UINT32(nowPos64), _previousByte, _peviousIsMatch,
matchByte, curByte);
_previousByte = curByte;
_peviousIsMatch = false;
}
else
{
_peviousIsMatch = true;
_mainChoiceEncoders[_state.Index][posState].Encode(&_rangeEncoder, kMainChoiceMatchIndex);
if(pos < kNumRepDistances)
{
_matchChoiceEncoders[_state.Index].Encode(&_rangeEncoder, kMatchChoiceRepetitionIndex);
if(pos == 0)
{
_matchRepChoiceEncoders[_state.Index].Encode(&_rangeEncoder, 0);
if(len == 1)
_matchRepShortChoiceEncoders[_state.Index][posState].Encode(&_rangeEncoder, 0);
else
_matchRepShortChoiceEncoders[_state.Index][posState].Encode(&_rangeEncoder, 1);
}
else
{
_matchRepChoiceEncoders[_state.Index].Encode(&_rangeEncoder, 1);
if (pos == 1)
_matchRep1ChoiceEncoders[_state.Index].Encode(&_rangeEncoder, 0);
else
{
_matchRep1ChoiceEncoders[_state.Index].Encode(&_rangeEncoder, 1);
_matchRep2ChoiceEncoders[_state.Index].Encode(&_rangeEncoder, pos - 2);
}
}
if (len == 1)
_state.UpdateShortRep();
else
{
_repMatchLenEncoder.Encode(&_rangeEncoder, len - kMatchMinLen, posState);
_state.UpdateRep();
}
UINT32 distance = _repDistances[pos];
if (pos != 0)
{
for(UINT32 i = pos; i >= 1; i--)
_repDistances[i] = _repDistances[i - 1];
_repDistances[0] = distance;
}
}
else
{
_matchChoiceEncoders[_state.Index].Encode(&_rangeEncoder, kMatchChoiceDistanceIndex);
_state.UpdateMatch();
_lenEncoder.Encode(&_rangeEncoder, len - kMatchMinLen, posState);
pos -= kNumRepDistances;
UINT32 posSlot = GetPosSlot(pos);
UINT32 lenToPosState = GetLenToPosState(len);
_posSlotEncoder[lenToPosState].Encode(&_rangeEncoder, posSlot);
if (posSlot >= kStartPosModelIndex)
{
UINT32 footerBits = ((posSlot >> 1) - 1);
UINT32 posReduced = pos - ((2 | (posSlot & 1)) << footerBits);
if (posSlot < kEndPosModelIndex)
_posEncoders[posSlot - kStartPosModelIndex].Encode(&_rangeEncoder, posReduced);
else
{
_rangeEncoder.EncodeDirectBits(posReduced >> kNumAlignBits, footerBits - kNumAlignBits);
_posAlignEncoder.Encode(&_rangeEncoder, posReduced & kAlignMask);
if (!_fastMode)
if (--_alignPriceCount == 0)
FillAlignPrices();
}
}
UINT32 distance = pos;
for(UINT32 i = kNumRepDistances - 1; i >= 1; i--)
_repDistances[i] = _repDistances[i - 1];
_repDistances[0] = distance;
}
_previousByte = _matchFinder->GetIndexByte(len - 1 - _additionalOffset);
}
_additionalOffset -= len;
nowPos64 += len;
if (!_fastMode)
if (nowPos64 - lastPosSlotFillingPos >= (1 << 9))
{
FillPosSlotPrices();
FillDistancesPrices();
lastPosSlotFillingPos = nowPos64;
}
if (_additionalOffset == 0)
{
*inSize = nowPos64;
*outSize = _rangeEncoder.GetProcessedSize();
state3:
if (_matchFinder->GetNumAvailableBytes() == 0)
{
state = 3;
return S_OK;
}
if (nowPos64 - progressPosValuePrev >= (1 << 12))
{
_finished = false;
*finished = 0;
state = 0;
return S_OK;
}
}
state = 4;
}
}
HRESULT CPYLZMAEncoder::FinishStream()
{
_finished = true;
_matchFinder->ReleaseStream();
WriteEndMarker(UINT32(nowPos64) & _posStateMask);
return Flush();
}
}}

View File

@@ -1,51 +0,0 @@
/*
* Python Bindings for LZMA
*
* Copyright (c) 2004-2006 by Joachim Bauch, mail@joachim-bauch.de
* 7-Zip Copyright (C) 1999-2005 Igor Pavlov
* LZMA SDK Copyright (C) 1999-2005 Igor Pavlov
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* $Id: pylzma_encoder.h 104 2006-01-08 18:17:14Z jojo $
*
*/
#ifndef ___PYLZMA_ENCODER__H___
#define ___PYLZMA_ENCODER__H___
#include <7zip/7zip/Compress/LZMA/LZMAEncoder.h>
namespace NCompress {
namespace NLZMA {
class CPYLZMAEncoder :
public CEncoder
{
private:
UINT64 progressPosValuePrev;
UINT32 pos;
UINT32 posState;
UINT32 len;
int state;
public:
HRESULT CodeOneBlock(UINT64 *inSize, UINT64 *outSize, INT32 *finished, bool flush);
HRESULT FinishStream();
};
}}
#endif

View File

@@ -1,103 +0,0 @@
/*
* Python Bindings for LZMA
*
* Copyright (c) 2004-2006 by Joachim Bauch, mail@joachim-bauch.de
* 7-Zip Copyright (C) 1999-2005 Igor Pavlov
* LZMA SDK Copyright (C) 1999-2005 Igor Pavlov
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* $Id: pylzma_filestreams.h 104 2006-01-08 18:17:14Z jojo $
*
*/
#ifndef ___PYLZMA_FILESTREAMS__H___
#define ___PYLZMA_FILESTREAMS__H___
#include <Python.h>
#include <7zip/7zip/IStream.h>
#include <7zip/Common/MyCom.h>
class CFileInStream :
public IInStream,
public CMyUnknownImp
{
private:
PyObject *m_file;
public:
MY_UNKNOWN_IMP
CFileInStream(PyObject *file)
{
m_file = file;
Py_XINCREF(m_file);
}
virtual ~CFileInStream()
{
Py_XDECREF(m_file);
}
STDMETHOD(Read)(void *data, UINT32 size, UINT32 *processedSize)
{
return ReadPart(data, size, processedSize);
}
STDMETHOD(ReadPart)(void *data, UINT32 size, UINT32 *processedSize)
{
// read from file-like object
PyObject *result = PyObject_CallMethod(m_file, "read", "l", size);
if (result == NULL)
return E_FAIL;
if (!PyString_Check(result))
{
PyObject *str = PyObject_Str(result);
Py_XDECREF(result);
if (str == NULL)
return E_FAIL;
result = str;
}
memcpy(data, PyString_AS_STRING(result), PyString_Size(result));
if (processedSize)
*processedSize = PyString_Size(result);
Py_XDECREF(result);
return S_OK;
}
STDMETHOD(Seek)(INT64 offset, UINT32 seekOrigin, UINT64 *newPosition)
{
PyObject *result = PyObject_CallMethod(m_file, "seek", "Ki", offset, seekOrigin);
if (result == NULL)
return E_FAIL;
Py_XDECREF(result);
if (newPosition)
{
result = PyObject_CallMethod(m_file, "tell", "");
if (result == NULL)
return E_FAIL;
*newPosition = PyLong_AsLongLong(result);
Py_XDECREF(result);
}
return S_OK;
}
};
#endif

View File

@@ -1,30 +0,0 @@
/*
* Python Bindings for LZMA
*
* Copyright (c) 2004-2006 by Joachim Bauch, mail@joachim-bauch.de
* 7-Zip Copyright (C) 1999-2005 Igor Pavlov
* LZMA SDK Copyright (C) 1999-2005 Igor Pavlov
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* $Id: pylzma_guids.cpp 104 2006-01-08 18:17:14Z jojo $
*
*/
// Initialize LZMA GUIDs
#define INITGUID
#include <7zip/Common/MyWindows.h>
#include "7zip/7zip/ICoder.h"
#include "7zip/7zip/Compress/LZ/IMatchFinder.h"

View File

@@ -1,270 +0,0 @@
/*
* Python Bindings for LZMA
*
* Copyright (c) 2004-2006 by Joachim Bauch, mail@joachim-bauch.de
* 7-Zip Copyright (C) 1999-2005 Igor Pavlov
* LZMA SDK Copyright (C) 1999-2005 Igor Pavlov
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* $Id: pylzma_streams.h 104 2006-01-08 18:17:14Z jojo $
*
*/
#ifndef ___PYLZMA_STREAMS__H___
#define ___PYLZMA_STREAMS__H___
#include <Python.h>
#include <7zip/Common/MyWindows.h>
#include <7zip/7zip/IStream.h>
#include <7zip/Common/MyCom.h>
class CInStream :
public ISequentialInStream,
public CMyUnknownImp
{
private:
BYTE *next_in;
UINT32 avail_in;
BYTE *origin;
UINT32 original_size;
UINT32 free_space;
bool allocated;
PyObject *sourceFile;
public:
MY_UNKNOWN_IMP
CInStream(BYTE *data, UINT32 length)
{
SetData(data, length);
allocated = false;
}
CInStream()
{
SetData(NULL, 0);
}
CInStream(PyObject *source)
{
SetData(NULL, 0);
sourceFile = source;
}
virtual ~CInStream()
{
if (allocated)
free(origin);
}
void SetData(BYTE *data, UINT32 length)
{
sourceFile = NULL;
origin = data;
next_in = data;
avail_in = length;
original_size = length;
free_space = 0;
}
int getAvailIn() { return avail_in; }
bool AppendData(BYTE *data, UINT32 length)
{
void *insert;
if (origin == NULL || free_space < (UINT32)length) {
// we need to resize the temporary buffer
int add = length - free_space;
int ofs = next_in - origin;
origin = (BYTE *)realloc(origin, original_size + add);
if (origin == NULL)
return false;
allocated = true;
free_space += add;
original_size += add;
next_in = &origin[ofs];
insert = &origin[avail_in];
} else
insert = &next_in[avail_in];
memcpy(insert, data, length);
avail_in += length;
free_space -= length;
return true;
}
STDMETHOD(Read)(void *data, UINT32 size, UINT32 *processedSize)
{
return ReadPart(data, size, processedSize);
}
STDMETHOD(ReadPart)(void *data, UINT32 size, UINT32 *processedSize)
{
if (sourceFile)
{
// read from file-like object
HRESULT res = E_FAIL;
// we might be calling into Python code from outside the main thread, so block threads...
START_BLOCK_THREADS
PyObject *result = PyObject_CallMethod(sourceFile, "read", "l", size);
if (result == NULL)
goto exit;
if (!PyString_Check(result))
{
PyObject *str = PyObject_Str(result);
Py_XDECREF(result);
if (str == NULL)
goto exit;
result = str;
}
memcpy(data, PyString_AS_STRING(result), PyString_Size(result));
if (processedSize)
*processedSize = PyString_Size(result);
Py_XDECREF(result);
res = S_OK;
exit:
END_BLOCK_THREADS
return res;
}
if (processedSize)
*processedSize = 0;
while (size)
{
if (!avail_in)
return S_OK;
UINT32 len = size < avail_in ? size : avail_in;
memcpy(data, next_in, len);
avail_in -= len;
size -= len;
next_in += len;
if (allocated)
{
memmove(origin, next_in, avail_in);
next_in = origin;
free_space += len;
}
data = (BYTE *)(data) + len;
if (processedSize)
*processedSize += len;
}
return S_OK;
}
};
class COutStream :
public ISequentialOutStream,
public CMyUnknownImp
{
private:
BYTE *buffer;
BYTE *next_out;
UINT32 avail_out;
UINT32 count;
UINT32 readpos;
public:
MY_UNKNOWN_IMP
COutStream()
{
buffer = (BYTE *)malloc(BLOCK_SIZE);
next_out = buffer;
avail_out = BLOCK_SIZE;
count = 0;
readpos = 0;
}
virtual ~COutStream()
{
if (buffer)
free(buffer);
buffer = NULL;
}
char *getData()
{
return (char *)buffer;
}
int getLength()
{
return count;
}
int getMaxRead()
{
return count - readpos;
}
void Read(void *dest, UINT32 size)
{
memcpy(dest, &buffer[readpos], size);
increaseReadPos(size);
}
void *getReadPtr()
{
return &buffer[readpos];
}
void increaseReadPos(UINT32 count)
{
readpos += count;
}
STDMETHOD(Write)(const void *data, UINT32 size, UINT32 *processedSize)
{
return WritePart(data, size, processedSize);
}
STDMETHOD(WritePart)(const void *data, UINT32 size, UINT32 *processedSize)
{
if (processedSize)
*processedSize = 0;
while (size)
{
if (!avail_out)
{
buffer = (BYTE *)realloc(buffer, count + BLOCK_SIZE);
avail_out += BLOCK_SIZE;
next_out = &buffer[count];
}
UINT32 len = size < avail_out ? size : avail_out;
memcpy(next_out, data, len);
avail_out -= len;
size -= len;
next_out += len;
count += len;
data = (BYTE *)(data) + len;
if (processedSize)
*processedSize += len;
}
return S_OK;
}
};
#endif

View File

@@ -1,24 +0,0 @@
Python bindings for LZMA
------------------------
PyLZMA Copyright (C) 2004-2006 Joachim Bauch
Initial Linux port of LZMA encoder Copyright (C) 1999-2004 Nullsoft, Inc.
7-Zip Copyright (C) 1999-2005 Igor Pavlov
LZMA SDK Copyright (C) 1999-2005 Igor Pavlov
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
For the latest releases of PyLZMA visit http://www.joachim-bauch.de/

View File

@@ -1,35 +0,0 @@
%define name pylzma
%define version 0.0.3
%define release 1
%define python python2.3
Summary: pylzma package
Name: %{name}
Version: %{version}
Release: %{release}
Source0: %{name}-%{version}.tar.gz
License: LGPL
Group: Development/Libraries
BuildRoot: %{_tmppath}/%{name}-buildroot
Prefix: %{_prefix}
Vendor: Joachim Bauch <mail@joachim-bauch.de>
Url: http://www.joachim-bauch.de
Requires: /usr/bin/python2.3
%description
Python bindings for the LZMA library by Igor Pavlov.
%prep
%setup
%build
env CFLAGS="$RPM_OPT_FLAGS" %{python} setup.py build
%install
%{python} setup.py install --root=$RPM_BUILD_ROOT --record=INSTALLED_FILES
%clean
rm -rf $RPM_BUILD_ROOT
%files -f INSTALLED_FILES
%defattr(-,root,root)

View File

@@ -1,58 +0,0 @@
#!/usr/bin/python -u
#
# Python Bindings for LZMA
#
# Copyright (c) 2004-2006 by Joachim Bauch, mail@joachim-bauch.de
# 7-Zip Copyright (C) 1999-2005 Igor Pavlov
# LZMA SDK Copyright (C) 1999-2005 Igor Pavlov
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# $Id: tarball.py 105 2006-01-08 18:18:27Z jojo $
#
"""Helper script for creating release tarballs."""
import os, sys
import tempfile
from distutils.dir_util import remove_tree
def runCommand(cmd, *args):
cmd = [cmd] + list(args)
assert os.system(' '.join(cmd)) == 0, 'command failed'
def main():
if len(sys.argv) != 2:
print 'Syntax is "tarball version"'
return
version = sys.argv[1]
tempdir = tempfile.mkdtemp()
pylzma = 'pylzma-%s' % version
print 'Exporting version %s from subversion...' % version
runCommand('svn', 'export', '-q', 'http://svn.fancycode.com/repos/python/pylzma/tags/v%s' % version.replace('.', '_'), os.path.join(tempdir, pylzma))
file(os.path.join(tempdir, pylzma, 'version.txt'), 'wb').write(version)
olddir = os.getcwd()
os.chdir(tempdir)
try:
print 'Creating tarball %s' % os.path.join(olddir, pylzma+'.tar.gz')
runCommand('tar', 'czf', os.path.join(olddir, pylzma+'.tar.gz'), pylzma)
finally:
os.chdir(olddir)
remove_tree(tempdir)
if __name__ == '__main__':
main()

View File

@@ -1,156 +0,0 @@
#!/usr/bin/python -u
#
# Python Bindings for LZMA
#
# Copyright (c) 2004-2006 by Joachim Bauch, mail@joachim-bauch.de
# 7-Zip Copyright (C) 1999-2005 Igor Pavlov
# LZMA SDK Copyright (C) 1999-2005 Igor Pavlov
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# $Id: setup.py 120 2006-09-29 21:14:23Z jojo $
#
import sys, os
from warnings import warn
# are we building an egg package?
BUILD_EGG = 'bdist_egg' in sys.argv
kw = {}
if BUILD_EGG:
from setuptools import setup, Extension
kw['test_suite'] = 'tests'
kw['zip_safe'] = False
else:
from distutils.core import setup, Extension
PYTHON_VERSION=sys.version[:3]
PYTHON_PREFIX=sys.prefix
class UnsupportedPlatformWarning(Warning):
pass
# set this to any true value to enable multithreaded compression
ENABLE_MULTITHREADING = True
# set this to any true value to add the compatibility decoder
# from version 0.0.3 to be able to decompress strings without
# the end of stream mark and you don't know their lengths
ENABLE_COMPATIBILITY = True
# compile including debug symbols on Windows?
COMPILE_DEBUG = False
if os.name == 'posix':
# This is the directory, your Python is installed in. It must contain the header and include files.
PYTHON_INCLUDE_DIR="%s/include/python%s" % (PYTHON_PREFIX, PYTHON_VERSION)
PYTHON_LIB_DIR="%s/lib/python%s" % (PYTHON_PREFIX, PYTHON_VERSION)
libraries=[]
else:
PYTHON_INCLUDE_DIR="%s\\include" % (PYTHON_PREFIX)
PYTHON_LIB_DIR="%s\\libs" % (PYTHON_PREFIX)
libraries=['user32', 'oleaut32']
include_dirs = [
PYTHON_INCLUDE_DIR,
".",
]
library_dirs = [
PYTHON_LIB_DIR,
".",
]
mt_platforms = (
'win32',
)
if ENABLE_MULTITHREADING and not sys.platform in mt_platforms:
warn("""\
Multithreading is not supported on the platform "%s",
please contact mail@joachim-bauch.de for more informations.""" % (sys.platform), UnsupportedPlatformWarning)
ENABLE_MULTITHREADING = 0
descr = "Python bindings for the LZMA library by Igor Pavlov."
long_descr = """PyLZMA provides a platform independent way to read and write data
that has been compressed or can be decompressed by the LZMA library by Igor Pavlov."""
try: version = open('version.txt', 'rb').read().strip()
except: version = 'unknown'
modules = ['py7zlib']
c_files = ['pylzma.c', 'pylzma_decompressobj.c', 'pylzma_compressfile.cpp',
'pylzma_decompress.c', 'pylzma_compress.cpp', 'pylzma_guids.cpp']
compile_args = []
link_args = []
macros = []
if 'win' in sys.platform:
macros.append(('WIN32', 1))
if COMPILE_DEBUG:
compile_args.append('/Zi')
compile_args.append('/MTd')
link_args.append('/DEBUG')
else:
compile_args.append('/MT')
if not 'win' in sys.platform:
# disable gcc warning about virtual functions with non-virtual destructors
compile_args.append(('-Wno-non-virtual-dtor'))
if ENABLE_MULTITHREADING:
macros.append(('COMPRESS_MF_MT', 1))
lzma_files = ('7zip/LzmaStateDecode.c', '7zip/7zip/Compress/LZMA/LZMAEncoder.cpp',
'7zip/7zip/Compress/RangeCoder/RangeCoderBit.cpp', '7zip/Common/CRC.cpp',
'7zip/7zip/Compress/LZ/LZInWindow.cpp', '7zip/7zip/Common/StreamUtils.cpp',
'7zip/7zip/Common/OutBuffer.cpp', '7zip/Common/Alloc.cpp', '7zip/Common/NewHandler.cpp', )
if ENABLE_MULTITHREADING:
lzma_files += ('7zip/7zip/Compress/LZ/MT/MT.cpp', '7zip/OS/Synchronization.cpp', )
if ENABLE_COMPATIBILITY:
c_files += ('pylzma_decompress_compat.c', 'pylzma_decompressobj_compat.c', )
lzma_files += ('7zip/LzmaCompatDecode.c', )
macros.append(('WITH_COMPAT', 1))
join = os.path.join
normalize = os.path.normpath
c_files += map(lambda x: normalize(join('.', x)), lzma_files)
extens=[Extension('pylzma', c_files, include_dirs=include_dirs, libraries=libraries,
library_dirs=library_dirs, define_macros=macros, extra_compile_args=compile_args,
extra_link_args=link_args)]
if sys.platform == 'win32':
operating_system = 'Microsoft :: Windows'
else:
operating_system = 'POSIX :: Linux'
setup(
name = "pylzma",
version = version,
description = descr,
author = "Joachim Bauch",
author_email = "mail@joachim-bauch.de",
url = "http://www.joachim-bauch.de",
license = 'LGPL',
keywords = "lzma compression",
long_description = long_descr,
platforms = sys.platform,
classifiers = [
'Development Status :: 5 - Production/Stable',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)',
'Operating System :: %s' % operating_system,
],
py_modules = modules,
ext_modules = extens,
**kw
)
sys.exit(0)

View File

@@ -1 +0,0 @@
## make this a module

Binary file not shown.

Binary file not shown.

Binary file not shown.

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