Files
Nim/tests/stdlib/tmemfiles2.nim
c-blake d59441340d Fixes incorrect fd==0 test on Unix; Conserves handles by default. (#5512)
* Fix 2 problems.  First, 0 is a valid fd on Unix (easily gotten if user first
closes all fds and then starts using memfiles).  Use -1 instead for an invalid
fd.  Second, it is best practice to conserve open fds on Unix and file handles
on Windows.  These handles are not needed unless the user wants to remap the
memory with ``mapMem`` (or a hypothetical future ``proc resize``).  Adding a
new bool param ``allowRemap=false`` to ``memfiles.open`` solves this cleanly
in a "mostly" backward compatible way.  This is only "mostly" because the
default ``false`` case does not keep unneeded resources allocated, but that
most sensible default means that any ``mapMem`` callers need to fix all their
open calls to have allowRemap=true, as this PR also does for tmemfiles2.nim.
* Include backwards compatibility note.
2017-03-12 20:45:10 +01:00

40 lines
953 B
Nim

discard """
file: "tmemfiles2.nim"
disabled: true
output: '''Full read size: 20
Half read size: 10 Data: Hello'''
"""
# doesn't work on windows. fmReadWrite doesn't create a file.
import memfiles, os
var
mm, mm_full, mm_half: MemFile
fn = "test.mmap"
p: pointer
if fileExists(fn): removeFile(fn)
# Create a new file, data all zeros
mm = memfiles.open(fn, mode = fmReadWrite, newFileSize = 20)
mm.close()
# read, change
mm_full = memfiles.open(fn, mode = fmWrite, mappedSize = -1, allowRemap = true)
echo "Full read size: ",mm_full.size
p = mm_full.mapMem(fmReadWrite, 20, 0)
var p2 = cast[cstring](p)
p2[0] = 'H'
p2[1] = 'e'
p2[2] = 'l'
p2[3] = 'l'
p2[4] = 'o'
p2[5] = '\0'
mm_full.unmapMem(p, 20)
mm_full.close()
# read half, and verify data change
mm_half = memfiles.open(fn, mode = fmRead, mappedSize = 10)
echo "Half read size: ",mm_half.size, " Data: ", cast[cstring](mm_half.mem)
mm_half.close()
if fileExists(fn): removeFile(fn)