473,792 Members | 3,076 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Copying zlib compression objects

I'm writing a program in python that creates tar files of a certain
maximum size (to fit onto CD/DVD). One of the problems I'm running
into is that when using compression, it's pretty much impossible to
determine if a file, once added to an archive, will cause the archive
size to exceed the maximum size.

I believe that to do this properly, you need to copy the state of tar
file (basically the current file offset as well as the state of the
compression object), then add the file. If the new size of the archive
exceeds the maximum, you need to restore the original state.

The critical part is being able to copy the compression object.
Without compression it is trivial to determine if a given file will
"fit" inside the archive. When using compression, the compression
ratio of a file depends partially on all the data that has been
compressed prior to it.

The current implementation in the standard library does not allow you
to copy these compression objects in a useful way, so I've made some
minor modifications (patch follows) to the standard 2.4.2 library:
- Add copy() method to zlib compression object. This returns a new
compression object with the same internal state. I named it copy() to
keep it consistent with things like sha.copy().
- Add snapshot() / restore() methods to GzipFile and TarFile. These
work only in write mode. snapshot() returns a state object. Passing
in this state object to restore() will restore the state of the
GzipFile / TarFile to the state represented by the object.

Future work:
- Decompression objects could use a copy() method too
- Add support for copying bzip2 compression objects

Does this seem like a good approach?

Cheers,
Chris

diff -ur Python-2.4.2.orig/Lib/gzip.py Python-2.4.2/Lib/gzip.py
--- Python-2.4.2.orig/Lib/gzip.py 2005-06-09 10:22:07.000000 000 -0400
+++ Python-2.4.2/Lib/gzip.py 2006-02-14 13:12:29.000000 000 -0500
@@ -433,6 +433,17 @@
else:
raise StopIteration

+ def snapshot(self):
+ if self.mode == READ:
+ raise IOError("Can't create a snapshot in READ mode")
+ return (self.size, self.crc, self.fileobj.te ll(), self.offset,
self.compress.c opy())
+
+ def restore(self, s):
+ if self.mode == READ:
+ raise IOError("Can't restore a snapshot in READ mode")
+ self.size, self.crc, offset, self.offset, self.compress = s
+ self.fileobj.se ek(offset)
+ self.fileobj.tr uncate()

def _test():
# Act like gzip; with -d, act like gunzip.
diff -ur Python-2.4.2.orig/Lib/tarfile.py Python-2.4.2/Lib/tarfile.py
--- Python-2.4.2.orig/Lib/tarfile.py 2005-08-27 06:08:21.000000 000
-0400
+++ Python-2.4.2/Lib/tarfile.py 2006-02-14 16:50:41.000000 000 -0500
@@ -1825,6 +1825,28 @@
"""
if level <= self.debug:
print >> sys.stderr, msg
+
+ def snapshot(self):
+ """Save the current state of the tarfile
+ """
+ self._check("_a w")
+ if hasattr(self.fi leobj, "snapshot") :
+ return self.fileobj.sn apshot(), self.offset,
self.members[:]
+ else:
+ return self.fileobj.te ll(), self.offset, self.members[:]
+
+ def restore(self, s):
+ """Restore the state of the tarfile from a previous snapshot
+ """
+ self._check("_a w")
+ if hasattr(self.fi leobj, "restore"):
+ snapshot, self.offset, self.members = s
+ self.fileobj.re store(snapshot)
+ else:
+ offset, self.offset, self.members = s
+ self.fileobj.se ek(offset)
+ self.fileobj.tr uncate()
+
# class TarFile

class TarIter:
diff -ur Python-2.4.2.orig/Modules/zlibmodule.c
Python-2.4.2/Modules/zlibmodule.c
--- Python-2.4.2.orig/Modules/zlibmodule.c 2004-12-28
15:12:31.000000 000 -0500
+++ Python-2.4.2/Modules/zlibmodule.c 2006-02-14 14:05:35.000000 000
-0500
@@ -653,6 +653,36 @@
return RetVal;
}

+PyDoc_STRVAR(c omp_copy__doc__ ,
+"copy() -- Return a copy of the compression object.");
+
+static PyObject *
+PyZlib_copy(co mpobject *self, PyObject *args)
+{
+ compobject *retval;
+
+ retval = newcompobject(& Comptype);
+
+ /* Copy the zstream state */
+ /* TODO: Are the ENTER / LEAVE needed? */
+ ENTER_ZLIB
+ deflateCopy(&re tval->zst, &self->zst);
+ LEAVE_ZLIB
+
+ /* Make references to the original unused_data and unconsumed_tail
+ * They're not used by compression objects so we don't have to do
+ * anything special here */
+ retval->unused_data = self->unused_data;
+ retval->unconsumed_tai l = self->unconsumed_tai l;
+ Py_INCREF(retva l->unused_data) ;
+ Py_INCREF(retva l->unconsumed_tai l);
+
+ /* Mark it as being initialized */
+ retval->is_initialis ed = 1;
+
+ return (PyObject*)retv al;
+}
+
PyDoc_STRVAR(de comp_flush__doc __,
"flush() -- Return a string containing any remaining decompressed
data.\n"
"\n"
@@ -723,6 +753,8 @@
comp_compress__ doc__},
{"flush", (binaryfunc)PyZ lib_flush, METH_VARARGS,
comp_flush__doc __},
+ {"copy", (binaryfunc)PyZ lib_copy, METH_VARARGS,
+ comp_copy__doc_ _},
{NULL, NULL}
};

Feb 14 '06 #1
1 2351
No comments?

I found a small bug in TarFile.snapsho t() / restore() - they need to
save and restore self.inodes as well.

Feb 16 '06 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
2183
by: Kirsten | last post by:
Hi @all, today I have implemented the ZLib library (1.2.1) in my C++ project. Using the function compress2(...) (Compression level 1) I have encoded my string. Then I wanted to uncompress the string with PHP on my server, but here the error: Warning: gzuncompress(): buffer error in ...
3
3751
by: Alan Toppen | last post by:
I was unable to use the ZipFile class in the zipfile module in Python2.4. I got an error that zlib could not be found. Comparing my Python 2.2 installation I noticed Python 2.4 was missing a certain file: /usr/lib/python2.2/lib-dynload/zlibmodule.so. Unable to find a more elegant solution, I copied the file from my Python 2.2 directory into my Python 2.4 directory. When running my Python script it gives a warning: ...
1
6768
by: MuZZy | last post by:
Hello, I am pretty new to .NET programming and probably my question has an obvious answer: I am starting to port an existing c++ application to c#.NET The first problem i am facing is that the app uses two open-source "c" compression libraries: zlib.lib and libjpeg.lib. I would really want ot avoid rewriting those libraries, because it's a huge
1
7944
by: Dennis Powell | last post by:
Does anyone have a successful implementaion of the zlib.dll in VB. Net they can show me. I'm writting a class encaplsulating zlib functionality and I keep getting a System.NullReferenceException (Object reference not set to an instance of an object) when I try to call the dll's compress function. The function in the dll is declared as such: int compress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen) I've...
1
2473
by: Leif Wessman | last post by:
I enabled automatic gzip compression with the following lines in ..htaccess: php_value zlib.output_compression On php_value zlib.output_compression_level 5 The problem is that the Content-Encoding header does not get set at all in the response. Therefore, a browser that advertises itself as supporting gzip compression (Accept-Encoding: gzip,deflate) receives compressed content but does not know it is compressed.
1
4502
by: DLPnet | last post by:
Hello all, I m not sure if it is the good newsgroup, please fu to the correct one if you know (already tried comp.compression with no answer) I m really knew to the use of the zlib in C++ to compress files. I think I understand how to compress a single file but not how to compress a whole folder containing subfolder and files.
4
2880
by: Anonymous | last post by:
Slightly OT, but can't find a zlib specific ng - so hopefuly, someone can point out why uncompressed strings are not matching the original strings (lots of strange characters at end of string). Heres a little prog that demonstrates the problem: //include zlib header etc int main(int argc, char * argv) {
0
1355
by: Bint | last post by:
Hello, I am trying to decompress some data in a file, from PHP. It's data that has been zlib-compressed on a handheld device and sent wirelessly to the PHP server. I can open the file and read some regular data from it. When I get to the position where my zlib compressed information starts, I make these calls: $zlib_filter = stream_filter_append($cellfile, 'zlib.inflate',
5
4815
by: tombrogan3 | last post by:
Hi, I need to implement in-memory zlib compression in c# to replace an old c++ app. Pre-requisites.. 1) The performance must be FAST (with source memory sizes from a few k to a meg). 2) The output must match exactly compression generated with the c++ zlib.org code with default compression. zlib.org c# code is as slow as hell! Not sure if I'm doing anything
0
9518
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10430
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10211
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10159
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9033
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5436
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5560
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4111
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2917
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.