(subtype, filename, dtype=uint8, mode='r+', offset=0,
shape=None, order='C')
| 207 | __array_priority__ = -100.0 |
| 208 | |
| 209 | def __new__(subtype, filename, dtype=uint8, mode='r+', offset=0, |
| 210 | shape=None, order='C'): |
| 211 | # Import here to minimize 'import numpy' overhead |
| 212 | import mmap |
| 213 | import os.path |
| 214 | try: |
| 215 | mode = mode_equivalents[mode] |
| 216 | except KeyError as e: |
| 217 | if mode not in valid_filemodes: |
| 218 | raise ValueError( |
| 219 | "mode must be one of {!r} (got {!r})" |
| 220 | .format(valid_filemodes + list(mode_equivalents.keys()), mode) |
| 221 | ) from None |
| 222 | |
| 223 | if mode == 'w+' and shape is None: |
| 224 | raise ValueError("shape must be given if mode == 'w+'") |
| 225 | |
| 226 | if hasattr(filename, 'read'): |
| 227 | f_ctx = nullcontext(filename) |
| 228 | else: |
| 229 | f_ctx = open(os_fspath(filename), ('r' if mode == 'c' else mode)+'b') |
| 230 | |
| 231 | with f_ctx as fid: |
| 232 | fid.seek(0, 2) |
| 233 | flen = fid.tell() |
| 234 | descr = dtypedescr(dtype) |
| 235 | _dbytes = descr.itemsize |
| 236 | |
| 237 | if shape is None: |
| 238 | bytes = flen - offset |
| 239 | if bytes % _dbytes: |
| 240 | raise ValueError("Size of available data is not a " |
| 241 | "multiple of the data-type size.") |
| 242 | size = bytes // _dbytes |
| 243 | shape = (size,) |
| 244 | else: |
| 245 | if not isinstance(shape, tuple): |
| 246 | shape = (shape,) |
| 247 | size = np.intp(1) # avoid default choice of np.int_, which might overflow |
| 248 | for k in shape: |
| 249 | size *= k |
| 250 | |
| 251 | bytes = int(offset + size*_dbytes) |
| 252 | |
| 253 | if mode in ('w+', 'r+') and flen < bytes: |
| 254 | fid.seek(bytes - 1, 0) |
| 255 | fid.write(b'\0') |
| 256 | fid.flush() |
| 257 | |
| 258 | if mode == 'c': |
| 259 | acc = mmap.ACCESS_COPY |
| 260 | elif mode == 'r': |
| 261 | acc = mmap.ACCESS_READ |
| 262 | else: |
| 263 | acc = mmap.ACCESS_WRITE |
| 264 | |
| 265 | start = offset - offset % mmap.ALLOCATIONGRANULARITY |
| 266 | bytes -= start |
no test coverage detected