# -*- coding: utf-8 -*- __authors__ = ["Sylvain Hellegouarch (sh _at_ defuze _dot_ org)"] __copyright__ = """ Copyright (c) 2006, Sylvain Hellegouarch All rights reserved. """ __license__ = """ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Sylvain Hellegouarch nor the names of his contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ import sys from StringIO import StringIO import System from System import Array from System.IO import File, Stream, MemoryStream, FileStream, FileMode, SeekOrigin import clr clr.AddReference("ICSharpCode.SharpZipLib") from ICSharpCode.SharpZipLib.GZip import GZipInputStream, GZipOutputStream from System.Text import Encoding raw = Encoding.GetEncoding('iso-8859-1') __all__ = ["GzipFile", "open"] def open(filename=None, mode='rb', compresslevel=9): return GzipFile(filename, mode, compresslevel) class GzipFile: def __init__(self, filename=None, mode='rb', compresslevel=9, fileobj=None): if mode not in ['r', 'rb', 'w', 'wb']: raise IOError, "Mode %s not supported" % mode if mode in ['r', 'rb']: GZStreamHandler = GZipInputStream self.min_readsize = 100 self.extrabuf = "" self.extrasize = 0 self.offset = 0 elif mode in ['w', 'wb']: GZStreamHandler = GZipOutputStream if not fileobj and not filename: raise ValueError, "You must provide either a filename or a fileobj" if fileobj is None: self.fileobj = FileStream(filename, FileMode.Open) elif isinstance(fileobj, StringIO): if mode in ['r', 'rb']: self.fileobj = MemoryStream(raw.GetBytes(fileobj.read())) elif mode in ['w', 'wb']: self.fileobj = MemoryStream() elif isinstance(fileobj, Stream): self.fileobj = fileobj if filename is None: if hasattr(self.fileobj, 'Name'): filename = self.fileobj.Name else: filename = '' self.gzstream = GZStreamHandler(self.fileobj) def __repr__(self): s = repr(self.fileobj) return '' def close(self): self.gzstream.Close() self.fileobj.Close() self.gzstream = None self.fileobj = None def read(self, size=-1): if size < 0: result = [] readsize = 1 buf = Array.CreateInstance(System.Byte, 2048) while readsize > 0: readsize = self.gzstream.Read(buf, 0, 2048) if readsize > 0 and readsize < 2048: tmp = Array.CreateInstance(System.Byte, readsize) Array.Copy(buf, 0, tmp, 0, readsize) result.append(raw.GetString(tmp)) elif readsize > 0: result.append(raw.GetString(buf)) return ''.join([chunk for chunk in result]) else: buf = Array.CreateInstance(System.Byte, size) readsize = self.gzstream.Read(buf, 0, size) if readsize > 0 and readsize < 2048: tmp = Array.CreateInstance(System.Byte, readsize) Array.Copy(buf, 0, tmp, 0, readsize) return raw.GetString(tmp) else: return raw.GetString(buf) def write(self, data): if self.fileobj is None: raise ValueError, "write() on closed GzipFile object" if len(data) > 0: bytes = raw.GetBytes(data) self.gzstream.Write(bytes, 0, bytes.Length) def fileno(self): return self.fileobj.Handle.ToInt32() def isatty(self): return False def flush(self): if self.fileobj.CanWrite: self.fileobj.Flush() def tell(self): return self.fileobj.Position def rewind(self): if not self.fileobj.CanRead: raise IOError("Can't rewind in write mode") self.fileobj.Seek(0, SeekOrigin.Begin) def seek(self, offset): if not self.fileobj.CanSeek: raise IOError('Cannot seek') if self.fileobj.CanWrite: if offset < self.fileobj.Position: raise IOError('Negative seek in write mode') self.fileobj.Seek(offset, SeekOrigin.Current) elif self.fileobj.CanRead: if offset < self.fileobj.Position: self.rewind() self.fileobj.Seek(offset, SeekOrigin.Current) def _unread(self, buf): self.extrabuf = buf + self.extrabuf self.extrasize = len(buf) + self.extrasize self.offset -= len(buf) def readline(self, size=-1): if size < 0: size = sys.maxint readsize = self.min_readsize else: readsize = size bufs = [] while size != 0: c = self.read(readsize) i = c.find('\n') # We set i=size to break out of the loop under two # conditions: 1) there's no newline, and the chunk is # larger than size, or 2) there is a newline, but the # resulting line would be longer than 'size'. if (size <= i) or (i == -1 and len(c) > size): i = size - 1 if i >= 0 or c == '': bufs.append(c[:i + 1]) # Add portion of last chunk self._unread(c[i + 1:]) # Push back rest of chunk break # Append chunk to list, decrease 'size', bufs.append(c) size = size - len(c) readsize = min(size, readsize * 2) if readsize > self.min_readsize: self.min_readsize = min(readsize, self.min_readsize * 2, 512) return ''.join(bufs) # Return resulting line def readlines(self, sizehint=0): # Negative numbers result in reading all the lines if sizehint <= 0: sizehint = sys.maxint L = [] while sizehint > 0: line = self.readline() if line == "": break L.append(line) sizehint = sizehint - len(line) return L def __iter__(self): return self def next(self): line = self.readline() if line: return line else: raise StopIteration def __del__(self): try: if (self.gzstream is None and self.fileobj is None): return except AttributeError: return self.close()