@@ -57,19 +57,13 @@ def open(filename, mode="rb", compresslevel=igzip._COMPRESS_LEVEL_TRADEOFF,
57
57
except : # noqa: E722
58
58
threads = 1
59
59
open_mode = mode .replace ("t" , "b" )
60
- if isinstance (filename , (str , bytes )) or hasattr (filename , "__fspath__" ):
61
- binary_file = builtins .open (filename , open_mode )
62
- elif hasattr (filename , "read" ) or hasattr (filename , "write" ):
63
- binary_file = filename
64
- else :
65
- raise TypeError ("filename must be a str or bytes object, or a file" )
66
60
if "r" in mode :
67
61
gzip_file = io .BufferedReader (
68
- _ThreadedGzipReader (binary_file , block_size = block_size ))
62
+ _ThreadedGzipReader (filename , block_size = block_size ))
69
63
else :
70
64
gzip_file = io .BufferedWriter (
71
65
_ThreadedGzipWriter (
72
- fp = binary_file ,
66
+ filename ,
73
67
block_size = block_size ,
74
68
level = compresslevel ,
75
69
threads = threads
@@ -81,10 +75,20 @@ def open(filename, mode="rb", compresslevel=igzip._COMPRESS_LEVEL_TRADEOFF,
81
75
return gzip_file
82
76
83
77
78
+ def open_as_binary_stream (filename , open_mode ):
79
+ if isinstance (filename , (str , bytes )) or hasattr (filename , "__fspath__" ):
80
+ binary_file = builtins .open (filename , open_mode )
81
+ elif hasattr (filename , "read" ) or hasattr (filename , "write" ):
82
+ binary_file = filename
83
+ else :
84
+ raise TypeError ("filename must be a str or bytes object, or a file" )
85
+ return binary_file
86
+
87
+
84
88
class _ThreadedGzipReader (io .RawIOBase ):
85
- def __init__ (self , fp , queue_size = 2 , block_size = 1024 * 1024 ):
86
- self .raw = fp
87
- self .fileobj = igzip ._IGzipReader (fp , buffersize = 8 * block_size )
89
+ def __init__ (self , filename , queue_size = 2 , block_size = 1024 * 1024 ):
90
+ self .raw = open_as_binary_stream ( filename , "rb" )
91
+ self .fileobj = igzip ._IGzipReader (self . raw , buffersize = 8 * block_size )
88
92
self .pos = 0
89
93
self .read_file = False
90
94
self .queue = queue .Queue (queue_size )
@@ -193,15 +197,14 @@ class _ThreadedGzipWriter(io.RawIOBase):
193
197
compressing and output is handled in one thread.
194
198
"""
195
199
def __init__ (self ,
196
- fp : BinaryIO ,
200
+ filename ,
197
201
level : int = isal_zlib .ISAL_DEFAULT_COMPRESSION ,
198
202
threads : int = 1 ,
199
203
queue_size : int = 1 ,
200
204
block_size : int = 1024 * 1024 ,
201
205
):
202
206
self .lock = threading .Lock ()
203
207
self .exception : Optional [Exception ] = None
204
- self .raw = fp
205
208
self .level = level
206
209
self .previous_block = b""
207
210
# Deflating random data results in an output a little larger than the
@@ -236,6 +239,7 @@ def __init__(self,
236
239
self .running = False
237
240
self ._size = 0
238
241
self ._closed = False
242
+ self .raw = open_as_binary_stream (filename , "wb" )
239
243
self ._write_gzip_header ()
240
244
self .start ()
241
245
0 commit comments