memfiles.nim 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2015 Nim Contributors
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## :Authors: Zahary Karadjov, Andreas Rumpf
  10. ##
  11. ## This module provides support for `memory mapped files`:idx:
  12. ## (Posix's `mmap`:idx:) on the different operating systems.
  13. ##
  14. ## It also provides some fast iterators over lines in text files (or
  15. ## other "line-like", variable length, delimited records).
  16. when defined(windows):
  17. import std/winlean
  18. when defined(nimPreviewSlimSystem):
  19. import std/widestrs
  20. elif defined(posix):
  21. import std/posix
  22. else:
  23. {.error: "the memfiles module is not supported on your operating system!".}
  24. import std/streams
  25. import std/oserrors
  26. when defined(nimPreviewSlimSystem):
  27. import std/[syncio, assertions]
  28. proc newEIO(msg: string): ref IOError =
  29. new(result)
  30. result.msg = msg
  31. proc setFileSize(fh: FileHandle, newFileSize = -1, oldSize = -1): OSErrorCode =
  32. ## Set the size of open file pointed to by `fh` to `newFileSize` if != -1,
  33. ## allocating | freeing space from the file system. This routine returns the
  34. ## last OSErrorCode found rather than raising to support old rollback/clean-up
  35. ## code style. [ Should maybe move to std/osfiles. ]
  36. if newFileSize < 0 or newFileSize == oldSize:
  37. return
  38. when defined(windows):
  39. var sizeHigh = int32(newFileSize shr 32)
  40. let sizeLow = int32(newFileSize and 0xffffffff)
  41. let status = setFilePointer(fh, sizeLow, addr(sizeHigh), FILE_BEGIN)
  42. let lastErr = osLastError()
  43. if (status == INVALID_SET_FILE_POINTER and lastErr.int32 != NO_ERROR) or
  44. setEndOfFile(fh) == 0:
  45. result = lastErr
  46. else:
  47. if newFileSize > oldSize: # grow the file
  48. var e: cint # posix_fallocate truncates up when needed.
  49. when declared(posix_fallocate):
  50. while (e = posix_fallocate(fh, 0, newFileSize); e == EINTR):
  51. discard
  52. if e in [EINVAL, EOPNOTSUPP] and ftruncate(fh, newFileSize) == -1:
  53. result = osLastError() # fallback arguable; Most portable BUT allows SEGV
  54. elif e != 0:
  55. result = osLastError()
  56. else: # shrink the file
  57. if ftruncate(fh.cint, newFileSize) == -1:
  58. result = osLastError()
  59. type
  60. MemFile* = object ## represents a memory mapped file
  61. mem*: pointer ## a pointer to the memory mapped file. The pointer
  62. ## can be used directly to change the contents of the
  63. ## file, if it was opened with write access.
  64. size*: int ## size of the memory mapped file
  65. when defined(windows):
  66. fHandle*: Handle ## **Caution**: Windows specific public field to allow
  67. ## even more low level trickery.
  68. mapHandle*: Handle ## **Caution**: Windows specific public field.
  69. wasOpened*: bool ## **Caution**: Windows specific public field.
  70. else:
  71. handle*: cint ## **Caution**: Posix specific public field.
  72. flags: cint ## **Caution**: Platform specific private field.
  73. proc mapMem*(m: var MemFile, mode: FileMode = fmRead,
  74. mappedSize = -1, offset = 0, mapFlags = cint(-1)): pointer =
  75. ## returns a pointer to a mapped portion of MemFile `m`
  76. ##
  77. ## `mappedSize` of `-1` maps to the whole file, and
  78. ## `offset` must be multiples of the PAGE SIZE of your OS
  79. if mode == fmAppend:
  80. raise newEIO("The append mode is not supported.")
  81. var readonly = mode == fmRead
  82. when defined(windows):
  83. result = mapViewOfFileEx(
  84. m.mapHandle,
  85. if readonly: FILE_MAP_READ else: FILE_MAP_READ or FILE_MAP_WRITE,
  86. int32(offset shr 32),
  87. int32(offset and 0xffffffff),
  88. WinSizeT(if mappedSize == -1: 0 else: mappedSize),
  89. nil)
  90. if result == nil:
  91. raiseOSError(osLastError())
  92. else:
  93. assert mappedSize > 0
  94. m.flags = if mapFlags == cint(-1): MAP_SHARED else: mapFlags
  95. #Ensure exactly one of MAP_PRIVATE cr MAP_SHARED is set
  96. if int(m.flags and MAP_PRIVATE) == 0:
  97. m.flags = m.flags or MAP_SHARED
  98. result = mmap(
  99. nil,
  100. mappedSize,
  101. if readonly: PROT_READ else: PROT_READ or PROT_WRITE,
  102. m.flags,
  103. m.handle, offset)
  104. if result == cast[pointer](MAP_FAILED):
  105. raiseOSError(osLastError())
  106. proc unmapMem*(f: var MemFile, p: pointer, size: int) =
  107. ## unmaps the memory region `(p, <p+size)` of the mapped file `f`.
  108. ## All changes are written back to the file system, if `f` was opened
  109. ## with write access.
  110. ##
  111. ## `size` must be of exactly the size that was requested
  112. ## via `mapMem`.
  113. when defined(windows):
  114. if unmapViewOfFile(p) == 0: raiseOSError(osLastError())
  115. else:
  116. if munmap(p, size) != 0: raiseOSError(osLastError())
  117. proc open*(filename: string, mode: FileMode = fmRead,
  118. mappedSize = -1, offset = 0, newFileSize = -1,
  119. allowRemap = false, mapFlags = cint(-1)): MemFile =
  120. ## opens a memory mapped file. If this fails, `OSError` is raised.
  121. ##
  122. ## `newFileSize` can only be set if the file does not exist and is opened
  123. ## with write access (e.g., with fmReadWrite).
  124. ##
  125. ##`mappedSize` and `offset`
  126. ## can be used to map only a slice of the file.
  127. ##
  128. ## `offset` must be multiples of the PAGE SIZE of your OS
  129. ## (usually 4K or 8K but is unique to your OS)
  130. ##
  131. ## `allowRemap` only needs to be true if you want to call `mapMem` on
  132. ## the resulting MemFile; else file handles are not kept open.
  133. ##
  134. ## `mapFlags` allows callers to override default choices for memory mapping
  135. ## flags with a bitwise mask of a variety of likely platform-specific flags
  136. ## which may be ignored or even cause `open` to fail if misspecified.
  137. ##
  138. ## Example:
  139. ##
  140. ## ```nim
  141. ## var
  142. ## mm, mm_full, mm_half: MemFile
  143. ##
  144. ## mm = memfiles.open("/tmp/test.mmap", mode = fmWrite, newFileSize = 1024) # Create a new file
  145. ## mm.close()
  146. ##
  147. ## # Read the whole file, would fail if newFileSize was set
  148. ## mm_full = memfiles.open("/tmp/test.mmap", mode = fmReadWrite, mappedSize = -1)
  149. ##
  150. ## # Read the first 512 bytes
  151. ## mm_half = memfiles.open("/tmp/test.mmap", mode = fmReadWrite, mappedSize = 512)
  152. ## ```
  153. # The file can be resized only when write mode is used:
  154. if mode == fmAppend:
  155. raise newEIO("The append mode is not supported.")
  156. assert newFileSize == -1 or mode != fmRead
  157. var readonly = mode == fmRead
  158. template rollback =
  159. result.mem = nil
  160. result.size = 0
  161. when defined(windows):
  162. let desiredAccess = GENERIC_READ
  163. let shareMode = FILE_SHARE_READ
  164. let flags = FILE_FLAG_RANDOM_ACCESS
  165. template fail(errCode: OSErrorCode, msg: untyped) =
  166. rollback()
  167. if result.fHandle != 0: discard closeHandle(result.fHandle)
  168. if result.mapHandle != 0: discard closeHandle(result.mapHandle)
  169. raiseOSError(errCode)
  170. # return false
  171. #raise newException(IOError, msg)
  172. template callCreateFile(winApiProc, filename): untyped =
  173. winApiProc(
  174. filename,
  175. # GENERIC_ALL != (GENERIC_READ or GENERIC_WRITE)
  176. if readonly: desiredAccess else: desiredAccess or GENERIC_WRITE,
  177. if readonly: shareMode else: shareMode or FILE_SHARE_WRITE,
  178. nil,
  179. if newFileSize != -1: CREATE_ALWAYS else: OPEN_EXISTING,
  180. if readonly: FILE_ATTRIBUTE_READONLY or flags
  181. else: FILE_ATTRIBUTE_NORMAL or flags,
  182. 0)
  183. result.fHandle = callCreateFile(createFileW, newWideCString(filename))
  184. if result.fHandle == INVALID_HANDLE_VALUE:
  185. fail(osLastError(), "error opening file")
  186. if (let e = setFileSize(result.fHandle.FileHandle, newFileSize);
  187. e != 0.OSErrorCode): fail(e, "error setting file size")
  188. # since the strings are always 'nil', we simply always call
  189. # CreateFileMappingW which should be slightly faster anyway:
  190. result.mapHandle = createFileMappingW(
  191. result.fHandle, nil,
  192. if readonly: PAGE_READONLY else: PAGE_READWRITE,
  193. 0, 0, nil)
  194. if result.mapHandle == 0:
  195. fail(osLastError(), "error creating mapping")
  196. result.mem = mapViewOfFileEx(
  197. result.mapHandle,
  198. if readonly: FILE_MAP_READ else: FILE_MAP_READ or FILE_MAP_WRITE,
  199. int32(offset shr 32),
  200. int32(offset and 0xffffffff),
  201. if mappedSize == -1: 0 else: mappedSize,
  202. nil)
  203. if result.mem == nil:
  204. fail(osLastError(), "error mapping view")
  205. var hi, low: int32
  206. low = getFileSize(result.fHandle, addr(hi))
  207. if low == INVALID_FILE_SIZE:
  208. fail(osLastError(), "error getting file size")
  209. else:
  210. var fileSize = (int64(hi) shl 32) or int64(uint32(low))
  211. if mappedSize != -1: result.size = min(fileSize, mappedSize).int
  212. else: result.size = fileSize.int
  213. result.wasOpened = true
  214. if not allowRemap and result.fHandle != INVALID_HANDLE_VALUE:
  215. if closeHandle(result.fHandle) != 0:
  216. result.fHandle = INVALID_HANDLE_VALUE
  217. else:
  218. template fail(errCode: OSErrorCode, msg: string) =
  219. rollback()
  220. if result.handle != -1: discard close(result.handle)
  221. raiseOSError(errCode)
  222. var flags = (if readonly: O_RDONLY else: O_RDWR) or O_CLOEXEC
  223. if newFileSize != -1:
  224. flags = flags or O_CREAT or O_TRUNC
  225. var permissionsMode = S_IRUSR or S_IWUSR
  226. result.handle = open(filename, flags, permissionsMode)
  227. if result.handle != -1:
  228. if (let e = setFileSize(result.handle.FileHandle, newFileSize);
  229. e != 0.OSErrorCode): fail(e, "error setting file size")
  230. else:
  231. result.handle = open(filename, flags)
  232. if result.handle == -1:
  233. fail(osLastError(), "error opening file")
  234. if mappedSize != -1: #XXX Logic here differs from `when windows` branch ..
  235. result.size = mappedSize #.. which always fstats&Uses min(mappedSize, st).
  236. else: # if newFileSize!=-1: result.size=newFileSize # if trust setFileSize
  237. var stat: Stat #^^.. BUT some FSes (eg. Linux HugeTLBfs) round to 2MiB.
  238. if fstat(result.handle, stat) != -1:
  239. result.size = stat.st_size.int # int may be 32-bit-unsafe for 2..<4 GiB
  240. else:
  241. fail(osLastError(), "error getting file size")
  242. result.flags = if mapFlags == cint(-1): MAP_SHARED else: mapFlags
  243. # Ensure exactly one of MAP_PRIVATE cr MAP_SHARED is set
  244. if int(result.flags and MAP_PRIVATE) == 0:
  245. result.flags = result.flags or MAP_SHARED
  246. let pr = if readonly: PROT_READ else: PROT_READ or PROT_WRITE
  247. result.mem = mmap(nil, result.size, pr, result.flags, result.handle, offset)
  248. if result.mem == cast[pointer](MAP_FAILED):
  249. fail(osLastError(), "file mapping failed")
  250. if not allowRemap and result.handle != -1:
  251. if close(result.handle) == 0:
  252. result.handle = -1
  253. proc flush*(f: var MemFile; attempts: Natural = 3) =
  254. ## Flushes `f`'s buffer for the number of attempts equal to `attempts`.
  255. ## If were errors an exception `OSError` will be raised.
  256. var res = false
  257. var lastErr: OSErrorCode
  258. when defined(windows):
  259. for i in 1..attempts:
  260. res = flushViewOfFile(f.mem, 0) != 0
  261. if res:
  262. break
  263. lastErr = osLastError()
  264. if lastErr != ERROR_LOCK_VIOLATION.OSErrorCode:
  265. raiseOSError(lastErr)
  266. else:
  267. for i in 1..attempts:
  268. res = msync(f.mem, f.size, MS_SYNC or MS_INVALIDATE) == 0
  269. if res:
  270. break
  271. lastErr = osLastError()
  272. if lastErr != EBUSY.OSErrorCode:
  273. raiseOSError(lastErr, "error flushing mapping")
  274. proc resize*(f: var MemFile, newFileSize: int) {.raises: [IOError, OSError].} =
  275. ## Resize & re-map the file underlying an `allowRemap MemFile`. If the OS/FS
  276. ## supports it, file space is reserved to ensure room for new virtual pages.
  277. ## Caller should wait often enough for `flush` to finish to limit use of
  278. ## system RAM for write buffering, perhaps just prior to this call.
  279. ## **Note**: this assumes the entire file is mapped read-write at offset 0.
  280. ## Also, the value of `.mem` will probably change.
  281. if newFileSize < 1: # Q: include system/bitmasks & use PageSize ?
  282. raise newException(IOError, "Cannot resize MemFile to < 1 byte")
  283. when defined(windows):
  284. if not f.wasOpened:
  285. raise newException(IOError, "Cannot resize unopened MemFile")
  286. if f.fHandle == INVALID_HANDLE_VALUE:
  287. raise newException(IOError,
  288. "Cannot resize MemFile opened with allowRemap=false")
  289. if unmapViewOfFile(f.mem) == 0 or closeHandle(f.mapHandle) == 0: # Un-do map
  290. raiseOSError(osLastError())
  291. if newFileSize != f.size: # Seek to size & `setEndOfFile` => allocated.
  292. if (let e = setFileSize(f.fHandle.FileHandle, newFileSize);
  293. e != 0.OSErrorCode): raiseOSError(e)
  294. f.mapHandle = createFileMappingW(f.fHandle, nil, PAGE_READWRITE, 0,0,nil)
  295. if f.mapHandle == 0: # Re-do map
  296. raiseOSError(osLastError())
  297. if (let m = mapViewOfFileEx(f.mapHandle, FILE_MAP_READ or FILE_MAP_WRITE,
  298. 0, 0, WinSizeT(newFileSize), nil); m != nil):
  299. f.mem = m
  300. f.size = newFileSize
  301. else:
  302. raiseOSError(osLastError())
  303. elif defined(posix):
  304. if f.handle == -1:
  305. raise newException(IOError,
  306. "Cannot resize MemFile opened with allowRemap=false")
  307. if newFileSize != f.size:
  308. if (let e = setFileSize(f.handle.FileHandle, newFileSize, f.size);
  309. e != 0.OSErrorCode): raiseOSError(e)
  310. when defined(linux): #Maybe NetBSD, too?
  311. # On Linux this can be over 100 times faster than a munmap,mmap cycle.
  312. proc mremap(old: pointer; oldSize, newSize: csize_t; flags: cint):
  313. pointer {.importc: "mremap", header: "<sys/mman.h>".}
  314. let newAddr = mremap(f.mem, csize_t(f.size), csize_t(newFileSize), 1.cint)
  315. if newAddr == cast[pointer](MAP_FAILED):
  316. raiseOSError(osLastError())
  317. else:
  318. if munmap(f.mem, f.size) != 0:
  319. raiseOSError(osLastError())
  320. let newAddr = mmap(nil, newFileSize, PROT_READ or PROT_WRITE,
  321. f.flags, f.handle, 0)
  322. if newAddr == cast[pointer](MAP_FAILED):
  323. raiseOSError(osLastError())
  324. f.mem = newAddr
  325. f.size = newFileSize
  326. proc close*(f: var MemFile) =
  327. ## closes the memory mapped file `f`. All changes are written back to the
  328. ## file system, if `f` was opened with write access.
  329. var error = false
  330. var lastErr: OSErrorCode
  331. when defined(windows):
  332. if f.wasOpened:
  333. error = unmapViewOfFile(f.mem) == 0
  334. if not error:
  335. error = closeHandle(f.mapHandle) == 0
  336. if not error and f.fHandle != INVALID_HANDLE_VALUE:
  337. discard closeHandle(f.fHandle)
  338. f.fHandle = INVALID_HANDLE_VALUE
  339. if error:
  340. lastErr = osLastError()
  341. else:
  342. error = munmap(f.mem, f.size) != 0
  343. lastErr = osLastError()
  344. if f.handle != -1:
  345. error = (close(f.handle) != 0) or error
  346. f.size = 0
  347. f.mem = nil
  348. when defined(windows):
  349. f.fHandle = 0
  350. f.mapHandle = 0
  351. f.wasOpened = false
  352. else:
  353. f.handle = -1
  354. if error: raiseOSError(lastErr)
  355. type MemSlice* = object ## represent slice of a MemFile for iteration over delimited lines/records
  356. data*: pointer
  357. size*: int
  358. proc `==`*(x, y: MemSlice): bool =
  359. ## Compare a pair of MemSlice for strict equality.
  360. result = (x.size == y.size and equalMem(x.data, y.data, x.size))
  361. proc `$`*(ms: MemSlice): string {.inline.} =
  362. ## Return a Nim string built from a MemSlice.
  363. result.setLen(ms.size)
  364. copyMem(result.cstring, ms.data, ms.size)
  365. iterator memSlices*(mfile: MemFile, delim = '\l', eat = '\r'): MemSlice {.inline.} =
  366. ## Iterates over \[optional `eat`] `delim`-delimited slices in MemFile `mfile`.
  367. ##
  368. ## Default parameters parse lines ending in either Unix(\\l) or Windows(\\r\\l)
  369. ## style on on a line-by-line basis. I.e., not every line needs the same ending.
  370. ## Unlike readLine(File) & lines(File), archaic MacOS9 \\r-delimited lines
  371. ## are not supported as a third option for each line. Such archaic MacOS9
  372. ## files can be handled by passing delim='\\r', eat='\\0', though.
  373. ##
  374. ## Delimiters are not part of the returned slice. A final, unterminated line
  375. ## or record is returned just like any other.
  376. ##
  377. ## Non-default delimiters can be passed to allow iteration over other sorts
  378. ## of "line-like" variable length records. Pass eat='\\0' to be strictly
  379. ## `delim`-delimited. (Eating an optional prefix equal to '\\0' is not
  380. ## supported.)
  381. ##
  382. ## This zero copy, memchr-limited interface is probably the fastest way to
  383. ## iterate over line-like records in a file. However, returned (data,size)
  384. ## objects are not Nim strings, bounds checked Nim arrays, or even terminated
  385. ## C strings. So, care is required to access the data (e.g., think C mem*
  386. ## functions, not str* functions).
  387. ##
  388. ## Example:
  389. ## ```nim
  390. ## var count = 0
  391. ## for slice in memSlices(memfiles.open("foo")):
  392. ## if slice.size > 0 and cast[cstring](slice.data)[0] != '#':
  393. ## inc(count)
  394. ## echo count
  395. ## ```
  396. proc c_memchr(cstr: pointer, c: char, n: csize_t): pointer {.
  397. importc: "memchr", header: "<string.h>".}
  398. proc `-!`(p, q: pointer): int {.inline.} = return cast[int](p) -% cast[int](q)
  399. var ms: MemSlice
  400. var ending: pointer
  401. ms.data = mfile.mem
  402. var remaining = mfile.size
  403. while remaining > 0:
  404. ending = c_memchr(ms.data, delim, csize_t(remaining))
  405. if ending == nil: # unterminated final slice
  406. ms.size = remaining # Weird case..check eat?
  407. yield ms
  408. break
  409. ms.size = ending -! ms.data # delim is NOT included
  410. if eat != '\0' and ms.size > 0 and cast[cstring](ms.data)[ms.size - 1] == eat:
  411. dec(ms.size) # trim pre-delim char
  412. yield ms
  413. ms.data = cast[pointer](cast[int](ending) +% 1) # skip delim
  414. remaining = mfile.size - (ms.data -! mfile.mem)
  415. iterator lines*(mfile: MemFile, buf: var string, delim = '\l',
  416. eat = '\r'): string {.inline.} =
  417. ## Replace contents of passed buffer with each new line, like
  418. ## `readLine(File) <syncio.html#readLine,File,string>`_.
  419. ## `delim`, `eat`, and delimiting logic is exactly as for `memSlices
  420. ## <#memSlices.i,MemFile,char,char>`_, but Nim strings are returned.
  421. ##
  422. ## Example:
  423. ## ```nim
  424. ## var buffer: string = ""
  425. ## for line in lines(memfiles.open("foo"), buffer):
  426. ## echo line
  427. ## ```
  428. for ms in memSlices(mfile, delim, eat):
  429. setLen(buf, ms.size)
  430. if ms.size > 0:
  431. copyMem(addr buf[0], ms.data, ms.size)
  432. yield buf
  433. iterator lines*(mfile: MemFile, delim = '\l', eat = '\r'): string {.inline.} =
  434. ## Return each line in a file as a Nim string, like
  435. ## `lines(File) <syncio.html#lines.i,File>`_.
  436. ## `delim`, `eat`, and delimiting logic is exactly as for `memSlices
  437. ## <#memSlices.i,MemFile,char,char>`_, but Nim strings are returned.
  438. ##
  439. ## Example:
  440. ## ```nim
  441. ## for line in lines(memfiles.open("foo")):
  442. ## echo line
  443. ## ```
  444. var buf = newStringOfCap(80)
  445. for line in lines(mfile, buf, delim, eat):
  446. yield buf
  447. type
  448. MemMapFileStream* = ref MemMapFileStreamObj ## a stream that encapsulates a `MemFile`
  449. MemMapFileStreamObj* = object of Stream
  450. mf: MemFile
  451. mode: FileMode
  452. pos: ByteAddress
  453. proc mmsClose(s: Stream) =
  454. MemMapFileStream(s).pos = -1
  455. close(MemMapFileStream(s).mf)
  456. proc mmsFlush(s: Stream) = flush(MemMapFileStream(s).mf)
  457. proc mmsAtEnd(s: Stream): bool = (MemMapFileStream(s).pos >= MemMapFileStream(s).mf.size) or
  458. (MemMapFileStream(s).pos < 0)
  459. proc mmsSetPosition(s: Stream, pos: int) =
  460. if pos > MemMapFileStream(s).mf.size or pos < 0:
  461. raise newEIO("cannot set pos in stream")
  462. MemMapFileStream(s).pos = pos
  463. proc mmsGetPosition(s: Stream): int = MemMapFileStream(s).pos
  464. proc mmsPeekData(s: Stream, buffer: pointer, bufLen: int): int =
  465. let startAddress = cast[int](MemMapFileStream(s).mf.mem)
  466. let p = cast[int](MemMapFileStream(s).pos)
  467. let l = min(bufLen, MemMapFileStream(s).mf.size - p)
  468. moveMem(buffer, cast[pointer](startAddress + p), l)
  469. result = l
  470. proc mmsReadData(s: Stream, buffer: pointer, bufLen: int): int =
  471. result = mmsPeekData(s, buffer, bufLen)
  472. inc(MemMapFileStream(s).pos, result)
  473. proc mmsWriteData(s: Stream, buffer: pointer, bufLen: int) =
  474. if MemMapFileStream(s).mode == fmRead:
  475. raise newEIO("cannot write to read-only stream")
  476. let size = MemMapFileStream(s).mf.size
  477. if MemMapFileStream(s).pos + bufLen > size:
  478. raise newEIO("cannot write to stream")
  479. let p = cast[int](MemMapFileStream(s).mf.mem) +
  480. cast[int](MemMapFileStream(s).pos)
  481. moveMem(cast[pointer](p), buffer, bufLen)
  482. inc(MemMapFileStream(s).pos, bufLen)
  483. proc newMemMapFileStream*(filename: string, mode: FileMode = fmRead,
  484. fileSize: int = -1): MemMapFileStream =
  485. ## creates a new stream from the file named `filename` with the mode `mode`.
  486. ## Raises ## `OSError` if the file cannot be opened. See the `system
  487. ## <system.html>`_ module for a list of available FileMode enums.
  488. ## `fileSize` can only be set if the file does not exist and is opened
  489. ## with write access (e.g., with fmReadWrite).
  490. var mf: MemFile = open(filename, mode, newFileSize = fileSize)
  491. new(result)
  492. result.mode = mode
  493. result.mf = mf
  494. result.closeImpl = mmsClose
  495. result.atEndImpl = mmsAtEnd
  496. result.setPositionImpl = mmsSetPosition
  497. result.getPositionImpl = mmsGetPosition
  498. result.readDataImpl = mmsReadData
  499. result.peekDataImpl = mmsPeekData
  500. result.writeDataImpl = mmsWriteData
  501. result.flushImpl = mmsFlush