memfiles.nim 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  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. ## ```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. ## ```
  149. # The file can be resized only when write mode is used:
  150. if mode == fmAppend:
  151. raise newEIO("The append mode is not supported.")
  152. assert newFileSize == -1 or mode != fmRead
  153. var readonly = mode == fmRead
  154. template rollback =
  155. result.mem = nil
  156. result.size = 0
  157. when defined(windows):
  158. let desiredAccess = GENERIC_READ
  159. let shareMode = FILE_SHARE_READ
  160. let flags = FILE_FLAG_RANDOM_ACCESS
  161. template fail(errCode: OSErrorCode, msg: untyped) =
  162. rollback()
  163. if result.fHandle != 0: discard closeHandle(result.fHandle)
  164. if result.mapHandle != 0: discard closeHandle(result.mapHandle)
  165. raiseOSError(errCode)
  166. # return false
  167. #raise newException(IOError, msg)
  168. template callCreateFile(winApiProc, filename): untyped =
  169. winApiProc(
  170. filename,
  171. # GENERIC_ALL != (GENERIC_READ or GENERIC_WRITE)
  172. if readonly: desiredAccess else: desiredAccess or GENERIC_WRITE,
  173. if readonly: shareMode else: shareMode or FILE_SHARE_WRITE,
  174. nil,
  175. if newFileSize != -1: CREATE_ALWAYS else: OPEN_EXISTING,
  176. if readonly: FILE_ATTRIBUTE_READONLY or flags
  177. else: FILE_ATTRIBUTE_NORMAL or flags,
  178. 0)
  179. result.fHandle = callCreateFile(createFileW, newWideCString(filename))
  180. if result.fHandle == INVALID_HANDLE_VALUE:
  181. fail(osLastError(), "error opening file")
  182. if (let e = setFileSize(result.fHandle.FileHandle, newFileSize);
  183. e != 0.OSErrorCode): fail(e, "error setting file size")
  184. # since the strings are always 'nil', we simply always call
  185. # CreateFileMappingW which should be slightly faster anyway:
  186. result.mapHandle = createFileMappingW(
  187. result.fHandle, nil,
  188. if readonly: PAGE_READONLY else: PAGE_READWRITE,
  189. 0, 0, nil)
  190. if result.mapHandle == 0:
  191. fail(osLastError(), "error creating mapping")
  192. result.mem = mapViewOfFileEx(
  193. result.mapHandle,
  194. if readonly: FILE_MAP_READ else: FILE_MAP_READ or FILE_MAP_WRITE,
  195. int32(offset shr 32),
  196. int32(offset and 0xffffffff),
  197. if mappedSize == -1: 0 else: mappedSize,
  198. nil)
  199. if result.mem == nil:
  200. fail(osLastError(), "error mapping view")
  201. var hi, low: int32
  202. low = getFileSize(result.fHandle, addr(hi))
  203. if low == INVALID_FILE_SIZE:
  204. fail(osLastError(), "error getting file size")
  205. else:
  206. var fileSize = (int64(hi) shl 32) or int64(uint32(low))
  207. if mappedSize != -1: result.size = min(fileSize, mappedSize).int
  208. else: result.size = fileSize.int
  209. result.wasOpened = true
  210. if not allowRemap and result.fHandle != INVALID_HANDLE_VALUE:
  211. if closeHandle(result.fHandle) != 0:
  212. result.fHandle = INVALID_HANDLE_VALUE
  213. else:
  214. template fail(errCode: OSErrorCode, msg: string) =
  215. rollback()
  216. if result.handle != -1: discard close(result.handle)
  217. raiseOSError(errCode)
  218. var flags = (if readonly: O_RDONLY else: O_RDWR) or O_CLOEXEC
  219. if newFileSize != -1:
  220. flags = flags or O_CREAT or O_TRUNC
  221. var permissionsMode = S_IRUSR or S_IWUSR
  222. result.handle = open(filename, flags, permissionsMode)
  223. else:
  224. result.handle = open(filename, flags)
  225. if result.handle == -1:
  226. # XXX: errno is supposed to be set here
  227. # Is there an exception that wraps it?
  228. fail(osLastError(), "error opening file")
  229. if (let e = setFileSize(result.handle.FileHandle, newFileSize);
  230. e != 0.OSErrorCode): fail(e, "error setting file size")
  231. if mappedSize != -1:
  232. result.size = mappedSize
  233. else:
  234. var stat: Stat
  235. if fstat(result.handle, stat) != -1:
  236. # XXX: Hmm, this could be unsafe
  237. # Why is mmap taking int anyway?
  238. result.size = int(stat.st_size)
  239. else:
  240. fail(osLastError(), "error getting file size")
  241. result.flags = if mapFlags == cint(-1): MAP_SHARED else: mapFlags
  242. #Ensure exactly one of MAP_PRIVATE cr MAP_SHARED is set
  243. if int(result.flags and MAP_PRIVATE) == 0:
  244. result.flags = result.flags or MAP_SHARED
  245. result.mem = mmap(
  246. nil,
  247. result.size,
  248. if readonly: PROT_READ else: PROT_READ or PROT_WRITE,
  249. result.flags,
  250. result.handle,
  251. offset)
  252. if result.mem == cast[pointer](MAP_FAILED):
  253. fail(osLastError(), "file mapping failed")
  254. if not allowRemap and result.handle != -1:
  255. if close(result.handle) == 0:
  256. result.handle = -1
  257. proc flush*(f: var MemFile; attempts: Natural = 3) =
  258. ## Flushes `f`'s buffer for the number of attempts equal to `attempts`.
  259. ## If were errors an exception `OSError` will be raised.
  260. var res = false
  261. var lastErr: OSErrorCode
  262. when defined(windows):
  263. for i in 1..attempts:
  264. res = flushViewOfFile(f.mem, 0) != 0
  265. if res:
  266. break
  267. lastErr = osLastError()
  268. if lastErr != ERROR_LOCK_VIOLATION.OSErrorCode:
  269. raiseOSError(lastErr)
  270. else:
  271. for i in 1..attempts:
  272. res = msync(f.mem, f.size, MS_SYNC or MS_INVALIDATE) == 0
  273. if res:
  274. break
  275. lastErr = osLastError()
  276. if lastErr != EBUSY.OSErrorCode:
  277. raiseOSError(lastErr, "error flushing mapping")
  278. proc resize*(f: var MemFile, newFileSize: int) {.raises: [IOError, OSError].} =
  279. ## Resize & re-map the file underlying an `allowRemap MemFile`. If the OS/FS
  280. ## supports it, file space is reserved to ensure room for new virtual pages.
  281. ## Caller should wait often enough for `flush` to finish to limit use of
  282. ## system RAM for write buffering, perhaps just prior to this call.
  283. ## **Note**: this assumes the entire file is mapped read-write at offset 0.
  284. ## Also, the value of `.mem` will probably change.
  285. if newFileSize < 1: # Q: include system/bitmasks & use PageSize ?
  286. raise newException(IOError, "Cannot resize MemFile to < 1 byte")
  287. when defined(windows):
  288. if not f.wasOpened:
  289. raise newException(IOError, "Cannot resize unopened MemFile")
  290. if f.fHandle == INVALID_HANDLE_VALUE:
  291. raise newException(IOError,
  292. "Cannot resize MemFile opened with allowRemap=false")
  293. if unmapViewOfFile(f.mem) == 0 or closeHandle(f.mapHandle) == 0: # Un-do map
  294. raiseOSError(osLastError())
  295. if newFileSize != f.size: # Seek to size & `setEndOfFile` => allocated.
  296. if (let e = setFileSize(f.fHandle.FileHandle, newFileSize);
  297. e != 0.OSErrorCode): raiseOSError(e)
  298. f.mapHandle = createFileMappingW(f.fHandle, nil, PAGE_READWRITE, 0,0,nil)
  299. if f.mapHandle == 0: # Re-do map
  300. raiseOSError(osLastError())
  301. if (let m = mapViewOfFileEx(f.mapHandle, FILE_MAP_READ or FILE_MAP_WRITE,
  302. 0, 0, WinSizeT(newFileSize), nil); m != nil):
  303. f.mem = m
  304. f.size = newFileSize
  305. else:
  306. raiseOSError(osLastError())
  307. elif defined(posix):
  308. if f.handle == -1:
  309. raise newException(IOError,
  310. "Cannot resize MemFile opened with allowRemap=false")
  311. if newFileSize != f.size:
  312. if (let e = setFileSize(f.handle.FileHandle, newFileSize);
  313. e != 0.OSErrorCode): raiseOSError(e)
  314. when defined(linux): #Maybe NetBSD, too?
  315. # On Linux this can be over 100 times faster than a munmap,mmap cycle.
  316. proc mremap(old: pointer; oldSize, newSize: csize_t; flags: cint):
  317. pointer {.importc: "mremap", header: "<sys/mman.h>".}
  318. let newAddr = mremap(f.mem, csize_t(f.size), csize_t(newFileSize), 1.cint)
  319. if newAddr == cast[pointer](MAP_FAILED):
  320. raiseOSError(osLastError())
  321. else:
  322. if munmap(f.mem, f.size) != 0:
  323. raiseOSError(osLastError())
  324. let newAddr = mmap(nil, newFileSize, PROT_READ or PROT_WRITE,
  325. f.flags, f.handle, 0)
  326. if newAddr == cast[pointer](MAP_FAILED):
  327. raiseOSError(osLastError())
  328. f.mem = newAddr
  329. f.size = newFileSize
  330. proc close*(f: var MemFile) =
  331. ## closes the memory mapped file `f`. All changes are written back to the
  332. ## file system, if `f` was opened with write access.
  333. var error = false
  334. var lastErr: OSErrorCode
  335. when defined(windows):
  336. if f.wasOpened:
  337. error = unmapViewOfFile(f.mem) == 0
  338. if not error:
  339. error = closeHandle(f.mapHandle) == 0
  340. if not error and f.fHandle != INVALID_HANDLE_VALUE:
  341. discard closeHandle(f.fHandle)
  342. f.fHandle = INVALID_HANDLE_VALUE
  343. if error:
  344. lastErr = osLastError()
  345. else:
  346. error = munmap(f.mem, f.size) != 0
  347. lastErr = osLastError()
  348. if f.handle != -1:
  349. error = (close(f.handle) != 0) or error
  350. f.size = 0
  351. f.mem = nil
  352. when defined(windows):
  353. f.fHandle = 0
  354. f.mapHandle = 0
  355. f.wasOpened = false
  356. else:
  357. f.handle = -1
  358. if error: raiseOSError(lastErr)
  359. type MemSlice* = object ## represent slice of a MemFile for iteration over delimited lines/records
  360. data*: pointer
  361. size*: int
  362. proc `==`*(x, y: MemSlice): bool =
  363. ## Compare a pair of MemSlice for strict equality.
  364. result = (x.size == y.size and equalMem(x.data, y.data, x.size))
  365. proc `$`*(ms: MemSlice): string {.inline.} =
  366. ## Return a Nim string built from a MemSlice.
  367. result.setLen(ms.size)
  368. copyMem(addr(result[0]), ms.data, ms.size)
  369. iterator memSlices*(mfile: MemFile, delim = '\l', eat = '\r'): MemSlice {.inline.} =
  370. ## Iterates over \[optional `eat`] `delim`-delimited slices in MemFile `mfile`.
  371. ##
  372. ## Default parameters parse lines ending in either Unix(\\l) or Windows(\\r\\l)
  373. ## style on on a line-by-line basis. I.e., not every line needs the same ending.
  374. ## Unlike readLine(File) & lines(File), archaic MacOS9 \\r-delimited lines
  375. ## are not supported as a third option for each line. Such archaic MacOS9
  376. ## files can be handled by passing delim='\\r', eat='\\0', though.
  377. ##
  378. ## Delimiters are not part of the returned slice. A final, unterminated line
  379. ## or record is returned just like any other.
  380. ##
  381. ## Non-default delimiters can be passed to allow iteration over other sorts
  382. ## of "line-like" variable length records. Pass eat='\\0' to be strictly
  383. ## `delim`-delimited. (Eating an optional prefix equal to '\\0' is not
  384. ## supported.)
  385. ##
  386. ## This zero copy, memchr-limited interface is probably the fastest way to
  387. ## iterate over line-like records in a file. However, returned (data,size)
  388. ## objects are not Nim strings, bounds checked Nim arrays, or even terminated
  389. ## C strings. So, care is required to access the data (e.g., think C mem*
  390. ## functions, not str* functions).
  391. ##
  392. ## Example:
  393. ## ```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. ## ```
  400. proc c_memchr(cstr: pointer, c: char, n: csize_t): pointer {.
  401. importc: "memchr", header: "<string.h>".}
  402. proc `-!`(p, q: pointer): int {.inline.} = return cast[int](p) -% cast[int](q)
  403. var ms: MemSlice
  404. var ending: pointer
  405. ms.data = mfile.mem
  406. var remaining = mfile.size
  407. while remaining > 0:
  408. ending = c_memchr(ms.data, delim, csize_t(remaining))
  409. if ending == nil: # unterminated final slice
  410. ms.size = remaining # Weird case..check eat?
  411. yield ms
  412. break
  413. ms.size = ending -! ms.data # delim is NOT included
  414. if eat != '\0' and ms.size > 0 and cast[cstring](ms.data)[ms.size - 1] == eat:
  415. dec(ms.size) # trim pre-delim char
  416. yield ms
  417. ms.data = cast[pointer](cast[int](ending) +% 1) # skip delim
  418. remaining = mfile.size - (ms.data -! mfile.mem)
  419. iterator lines*(mfile: MemFile, buf: var string, delim = '\l',
  420. eat = '\r'): string {.inline.} =
  421. ## Replace contents of passed buffer with each new line, like
  422. ## `readLine(File) <syncio.html#readLine,File,string>`_.
  423. ## `delim`, `eat`, and delimiting logic is exactly as for `memSlices
  424. ## <#memSlices.i,MemFile,char,char>`_, but Nim strings are returned.
  425. ##
  426. ## Example:
  427. ## ```nim
  428. ## var buffer: string = ""
  429. ## for line in lines(memfiles.open("foo"), buffer):
  430. ## echo line
  431. ## ```
  432. for ms in memSlices(mfile, delim, eat):
  433. setLen(buf, ms.size)
  434. if ms.size > 0:
  435. copyMem(addr buf[0], ms.data, ms.size)
  436. yield buf
  437. iterator lines*(mfile: MemFile, delim = '\l', eat = '\r'): string {.inline.} =
  438. ## Return each line in a file as a Nim string, like
  439. ## `lines(File) <syncio.html#lines.i,File>`_.
  440. ## `delim`, `eat`, and delimiting logic is exactly as for `memSlices
  441. ## <#memSlices.i,MemFile,char,char>`_, but Nim strings are returned.
  442. ##
  443. ## Example:
  444. ## ```nim
  445. ## for line in lines(memfiles.open("foo")):
  446. ## echo line
  447. ## ```
  448. var buf = newStringOfCap(80)
  449. for line in lines(mfile, buf, delim, eat):
  450. yield buf
  451. type
  452. MemMapFileStream* = ref MemMapFileStreamObj ## a stream that encapsulates a `MemFile`
  453. MemMapFileStreamObj* = object of Stream
  454. mf: MemFile
  455. mode: FileMode
  456. pos: ByteAddress
  457. proc mmsClose(s: Stream) =
  458. MemMapFileStream(s).pos = -1
  459. close(MemMapFileStream(s).mf)
  460. proc mmsFlush(s: Stream) = flush(MemMapFileStream(s).mf)
  461. proc mmsAtEnd(s: Stream): bool = (MemMapFileStream(s).pos >= MemMapFileStream(s).mf.size) or
  462. (MemMapFileStream(s).pos < 0)
  463. proc mmsSetPosition(s: Stream, pos: int) =
  464. if pos > MemMapFileStream(s).mf.size or pos < 0:
  465. raise newEIO("cannot set pos in stream")
  466. MemMapFileStream(s).pos = pos
  467. proc mmsGetPosition(s: Stream): int = MemMapFileStream(s).pos
  468. proc mmsPeekData(s: Stream, buffer: pointer, bufLen: int): int =
  469. let startAddress = cast[int](MemMapFileStream(s).mf.mem)
  470. let p = cast[int](MemMapFileStream(s).pos)
  471. let l = min(bufLen, MemMapFileStream(s).mf.size - p)
  472. moveMem(buffer, cast[pointer](startAddress + p), l)
  473. result = l
  474. proc mmsReadData(s: Stream, buffer: pointer, bufLen: int): int =
  475. result = mmsPeekData(s, buffer, bufLen)
  476. inc(MemMapFileStream(s).pos, result)
  477. proc mmsWriteData(s: Stream, buffer: pointer, bufLen: int) =
  478. if MemMapFileStream(s).mode == fmRead:
  479. raise newEIO("cannot write to read-only stream")
  480. let size = MemMapFileStream(s).mf.size
  481. if MemMapFileStream(s).pos + bufLen > size:
  482. raise newEIO("cannot write to stream")
  483. let p = cast[int](MemMapFileStream(s).mf.mem) +
  484. cast[int](MemMapFileStream(s).pos)
  485. moveMem(cast[pointer](p), buffer, bufLen)
  486. inc(MemMapFileStream(s).pos, bufLen)
  487. proc newMemMapFileStream*(filename: string, mode: FileMode = fmRead,
  488. fileSize: int = -1): MemMapFileStream =
  489. ## creates a new stream from the file named `filename` with the mode `mode`.
  490. ## Raises ## `OSError` if the file cannot be opened. See the `system
  491. ## <system.html>`_ module for a list of available FileMode enums.
  492. ## `fileSize` can only be set if the file does not exist and is opened
  493. ## with write access (e.g., with fmReadWrite).
  494. var mf: MemFile = open(filename, mode, newFileSize = fileSize)
  495. new(result)
  496. result.mode = mode
  497. result.mf = mf
  498. result.closeImpl = mmsClose
  499. result.atEndImpl = mmsAtEnd
  500. result.setPositionImpl = mmsSetPosition
  501. result.getPositionImpl = mmsGetPosition
  502. result.readDataImpl = mmsReadData
  503. result.peekDataImpl = mmsPeekData
  504. result.writeDataImpl = mmsWriteData
  505. result.flushImpl = mmsFlush