memfiles.nim 21 KB

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