| 254 | |
| 255 | |
| 256 | class _Unframer: |
| 257 | |
| 258 | def __init__(self, file_read, file_readline, file_tell=None): |
| 259 | self.file_read = file_read |
| 260 | self.file_readline = file_readline |
| 261 | self.current_frame = None |
| 262 | |
| 263 | def readinto(self, buf): |
| 264 | if self.current_frame: |
| 265 | n = self.current_frame.readinto(buf) |
| 266 | if n == 0 and len(buf) != 0: |
| 267 | self.current_frame = None |
| 268 | n = len(buf) |
| 269 | buf[:] = self.file_read(n) |
| 270 | return n |
| 271 | if n < len(buf): |
| 272 | raise UnpicklingError( |
| 273 | "pickle exhausted before end of frame") |
| 274 | return n |
| 275 | else: |
| 276 | n = len(buf) |
| 277 | buf[:] = self.file_read(n) |
| 278 | return n |
| 279 | |
| 280 | def read(self, n): |
| 281 | if self.current_frame: |
| 282 | data = self.current_frame.read(n) |
| 283 | if not data and n != 0: |
| 284 | self.current_frame = None |
| 285 | return self.file_read(n) |
| 286 | if len(data) < n: |
| 287 | raise UnpicklingError( |
| 288 | "pickle exhausted before end of frame") |
| 289 | return data |
| 290 | else: |
| 291 | return self.file_read(n) |
| 292 | |
| 293 | def readline(self): |
| 294 | if self.current_frame: |
| 295 | data = self.current_frame.readline() |
| 296 | if not data: |
| 297 | self.current_frame = None |
| 298 | return self.file_readline() |
| 299 | if data[-1] != b'\n'[0]: |
| 300 | raise UnpicklingError( |
| 301 | "pickle exhausted before end of frame") |
| 302 | return data |
| 303 | else: |
| 304 | return self.file_readline() |
| 305 | |
| 306 | def load_frame(self, frame_size): |
| 307 | if self.current_frame and self.current_frame.read() != b'': |
| 308 | raise UnpicklingError( |
| 309 | "beginning of a new frame before end of current frame") |
| 310 | self.current_frame = io.BytesIO(self.file_read(frame_size)) |
| 311 | |
| 312 | |
| 313 | # Tools used for pickling. |