Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

IO.py 8.2 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
  1. import io
  2. import pickle
  3. import struct
  4. from pathlib import Path
  5. from typing import Union
  6. class FormattedIOBase:
  7. """
  8. base class for formatting IO-like objects
  9. methods should be implemented:
  10. write
  11. read
  12. seek
  13. tell
  14. """
  15. def get_file_size(self):
  16. c = self.tell()
  17. result = self.seek(0,2)
  18. self.seek(c)
  19. return result
  20. def fill(self, byte, size : int):
  21. """fills a byte with length of size"""
  22. c_size = 16384
  23. n_count = size // c_size
  24. m_count = size % c_size
  25. f = bytes([byte]) * c_size
  26. if n_count >= 1:
  27. for _ in range(n_count):
  28. self.write(f)
  29. if m_count > 0:
  30. self.write(f[:m_count])
  31. return size
  32. def write_bytes(self, b_bytes):
  33. """writes compact bytes() object"""
  34. self.write_fmt('Q', len(b_bytes))
  35. self.write(b_bytes)
  36. def read_bytes(self):
  37. """reads bytes() object"""
  38. return self.read( self.read_fmt('Q')[0] )
  39. def write_utf8(self, s):
  40. """write compact string as utf8. Length must be not larger than 4Gb"""
  41. b = s.encode('utf-8')
  42. self.write_fmt('I', len(b))
  43. self.write(b)
  44. def read_utf8(self):
  45. """read string from utf8"""
  46. return self.read(self.read_fmt('I')[0]).decode('utf-8')
  47. def calc_fmt(self, fmt):
  48. """calc size for _fmt functions"""
  49. return struct.calcsize(fmt)
  50. def write_fmt_at(self, offset, fmt, *args):
  51. """
  52. write_fmt at offset and return cursor where it was
  53. """
  54. c = self.tell()
  55. self.seek(offset,0)
  56. n = self.write_fmt(fmt, *args)
  57. self.seek(c)
  58. return n
  59. def write_fmt(self, fmt, *args):
  60. """
  61. write compact data using struct.pack
  62. """
  63. b = struct.pack(fmt, *args)
  64. n_written = self.write(b)
  65. if n_written != len(b):
  66. raise IOError('Not enough room for write_fmt')
  67. return n_written
  68. def get_fmt(self, fmt):
  69. """read using struct.unpack without incrementing a cursor"""
  70. c = self.tell()
  71. result = self.read_fmt(fmt)
  72. self.seek(c)
  73. return result
  74. def read_fmt(self, fmt):
  75. """
  76. read using struct.unpack
  77. """
  78. size = struct.calcsize(fmt)
  79. b = self.read(size)
  80. if size != len(b):
  81. raise IOError('Not enough room for read_fmt')
  82. return struct.unpack (fmt, b)
  83. def read_backward_fmt(self, fmt):
  84. """
  85. read using struct.unpack in backward direction
  86. """
  87. size = struct.calcsize(fmt)
  88. cursor = self.tell()
  89. new_cursor = self.seek(-size,1)
  90. if size != cursor-new_cursor:
  91. raise IOError('Not enough room for read_backward_fmt')
  92. b = self.read(size)
  93. self.seek(-size,1)
  94. return struct.unpack (fmt, b)
  95. def write_pickled(self, obj):
  96. """
  97. write pickled obj
  98. """
  99. c = self.tell()
  100. self.write_fmt('Q', 0)
  101. pickle.dump(obj, self, 4)
  102. size = self.tell() - c
  103. self.write_fmt_at(c, 'Q', size)
  104. return size
  105. def read_pickled(self, suppress_error=True):
  106. """
  107. read pickled object
  108. suppress_error(True) ignore unpickling errors
  109. the stream will not be corrupted
  110. """
  111. c = self.tell()
  112. size, = self.read_fmt('Q')
  113. if suppress_error:
  114. try:
  115. obj = pickle.load(self)
  116. except:
  117. obj = None
  118. else:
  119. obj = pickle.load(self)
  120. self.seek(c+size)
  121. return obj
  122. class FormattedFileIO(io.FileIO, FormattedIOBase):
  123. """
  124. FileIO to use with formatting methods
  125. """
  126. def __init__(self, file, mode: str, closefd: bool = True, opener = None):
  127. filepath = Path(file)
  128. plus = '+' if '+' in mode else ''
  129. if 'a' in mode:
  130. if filepath.exists():
  131. mode = 'r' + plus
  132. else:
  133. mode = 'w' + plus
  134. io.FileIO.__init__(self, file, mode, closefd=closefd, opener=opener)
  135. def seek(self, offset, whence=0):
  136. """
  137. seek to offset
  138. whence 0(default) : from begin , offset >= 0
  139. 1 : from current , offset any
  140. 2 : from end , offset any
  141. returns cursor after seek
  142. """
  143. # reimplement method to allow to expand with zeros
  144. offset_cur = self.tell()
  145. offset_max = io.FileIO.seek(self, 0,2)
  146. if whence == 1:
  147. offset += offset_cur
  148. elif whence == 2:
  149. offset += offset_max
  150. expand = offset - offset_max
  151. if expand > 0:
  152. # new offset will be more than file size
  153. # expand with zero bytes
  154. self.fill(0x00, expand)
  155. return io.FileIO.seek(self, offset)
  156. def readinto (self, bytes_like : Union[bytearray, memoryview], size : int = 0):
  157. """read size amount of bytes into mutable bytes_like"""
  158. if size == 0:
  159. return io.FileIO.readinto(self, bytes_like)
  160. else:
  161. return io.FileIO.readinto(self, memoryview(bytes_like).cast('B')[:size] )
  162. def write(self, b: Union[bytes, bytearray, memoryview]):
  163. b_len = len(b)
  164. acc = 0
  165. n_count = b_len // 16384
  166. m_count = b_len % 16384
  167. if n_count > 0:
  168. for i in range(n_count):
  169. acc += io.FileIO.write(self, b[i*16384:(i+1)*16384])
  170. if m_count > 0:
  171. acc += io.FileIO.write(self, b[n_count*16384:])
  172. return acc
  173. class FormattedMemoryViewIO(io.RawIOBase, FormattedIOBase):
  174. """file-IO-like to memoryview"""
  175. def __init__(self, mv : memoryview):
  176. super().__init__()
  177. self._mv = mv
  178. self._mv_size = self._c_max = mv.nbytes
  179. self._c = 0
  180. def seek(self, cursor, whence=0):
  181. """
  182. seek to offset
  183. whence 0(default) : from begin , offset >= 0
  184. 1 : from current , offset any
  185. 2 : from end , offset any
  186. returns cursor after seek
  187. """
  188. # memoryview is not expandable, thus just clip the cursor
  189. if whence == 0:
  190. self._c = min( max(cursor,0), self._mv_size)
  191. self._c_max = max(self._c, self._c_max)
  192. elif whence == 1:
  193. self._c = min( max(self._c + cursor, 0), self._mv_size)
  194. self._c_max = max(self._c, self._c_max)
  195. elif whence == 2:
  196. self._c = min( max(self._c_max + cursor, 0), self._mv_size)
  197. self._c_max = max(self._c, self._c_max)
  198. else:
  199. raise ValueError('whence != 0,1,2')
  200. return self._c
  201. def tell(self):
  202. """returns current cursor offset"""
  203. return self._c
  204. def truncate(self, size=None):
  205. """truncate to the current cursor"""
  206. if size is not None:
  207. self._c_max = min(size, self._c_max)
  208. else:
  209. self._c_max = self._c
  210. return self._c_max
  211. def write(self, b : Union[bytes, bytearray, memoryview], size=0):
  212. if isinstance(b, memoryview):
  213. b = b.cast('B')
  214. size = b.nbytes
  215. else:
  216. size = len(b)
  217. size = min(size, self._mv_size - self._c)
  218. self._mv[self._c:self._c+size] = b[:size]
  219. self._c += size
  220. return size
  221. def read_memoryview(self, size) -> memoryview:
  222. size = min(size, self._c_max - self._c)
  223. result = self._mv[self._c:self._c+size]
  224. self._c += size
  225. return result
  226. def read(self, size) -> bytearray:
  227. """
  228. read bytearray of size
  229. """
  230. size = min(size, self._c_max - self._c)
  231. result = bytearray(size)
  232. memoryview(result)[:] = self._mv[self._c:self._c+size]
  233. self._c += size
  234. return result
  235. def readinto (self, bytes_like_or_io : Union[bytearray, memoryview, io.IOBase], size):
  236. """read size amount of bytes into mutable bytes_like or io"""
  237. if isinstance(bytes_like_or_io, io.IOBase):
  238. bytes_like_or_io.write( self._mv[self._c:self._c+size] )
  239. else:
  240. memoryview(bytes_like_or_io).cast('B')[:size] = self._mv[self._c:self._c+size]
  241. self._c += size
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...