memfiles.nim 21 KB

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