Source Edit

Authors:Zahary Karadjov, Andreas Rumpf

This module provides support for memory mapped files (Posix’s mmap) on the different operating systems.

It also provides some fast iterators over lines in text files (or other “line-like”, variable length, delimited records).

Imports

winlean, streams, oserrors

Types

  1. MemFile = object
  2. mem*: pointer ## a pointer to the memory mapped file. The pointer
  3. ## can be used directly to change the contents of the
  4. ## file, if it was opened with write access.
  5. size*: int ## size of the memory mapped file
  6. when defined(windows):
  7. fHandle*: Handle ## **Caution**: Windows specific public field to allow
  8. ## even more low level trickery.
  9. mapHandle*: Handle ## **Caution**: Windows specific public field.
  10. wasOpened*: bool ## **Caution**: Windows specific public field.
  11. else:
  12. handle*: cint ## **Caution**: Posix specific public field.
  13. ## **Caution**: Platform specific private field.

represents a memory mapped file Source Edit

  1. MemMapFileStream = ref MemMapFileStreamObj

a stream that encapsulates a MemFile Source Edit

  1. MemMapFileStreamObj = object of Stream

Source Edit

  1. MemSlice = object
  2. data*: pointer
  3. size*: int

represent slice of a MemFile for iteration over delimited lines/records Source Edit

Procs

  1. proc `$`(ms: MemSlice): string {.inline, ...raises: [], tags: [], forbids: [].}

Return a Nim string built from a MemSlice. Source Edit

  1. proc `==`(x, y: MemSlice): bool {....raises: [], tags: [], forbids: [].}

Compare a pair of MemSlice for strict equality. Source Edit

  1. proc close(f: var MemFile) {....raises: [OSError], tags: [], forbids: [].}

closes the memory mapped file f. All changes are written back to the file system, if f was opened with write access. Source Edit

  1. proc flush(f: var MemFile; attempts: Natural = 3) {....raises: [OSError], tags: [],
  2. forbids: [].}

Flushes f’s buffer for the number of attempts equal to attempts. If were errors an exception OSError will be raised. Source Edit

  1. proc mapMem(m: var MemFile; mode: FileMode = fmRead; mappedSize = -1;
  2. offset = 0; mapFlags = cint(-1)): pointer {.
  3. ...raises: [IOError, OSError], tags: [], forbids: [].}

returns a pointer to a mapped portion of MemFile m

mappedSize of -1 maps to the whole file, and offset must be multiples of the PAGE SIZE of your OS

Source Edit

  1. proc newMemMapFileStream(filename: string; mode: FileMode = fmRead;
  2. fileSize: int = -1): MemMapFileStream {.
  3. ...raises: [IOError, OSError], tags: [], forbids: [].}

creates a new stream from the file named filename with the mode mode. Raises ## OSError if the file cannot be opened. See the system module for a list of available FileMode enums. fileSize can only be set if the file does not exist and is opened with write access (e.g., with fmReadWrite). Source Edit

  1. proc open(filename: string; mode: FileMode = fmRead; mappedSize = -1;
  2. offset = 0; newFileSize = -1; allowRemap = false; mapFlags = cint(-1)): MemFile {.
  3. ...raises: [IOError, OSError], tags: [], forbids: [].}

opens a memory mapped file. If this fails, OSError is raised.

newFileSize can only be set if the file does not exist and is opened with write access (e.g., with fmReadWrite).

mappedSize and offset can be used to map only a slice of the file.

offset must be multiples of the PAGE SIZE of your OS (usually 4K or 8K but is unique to your OS)

allowRemap only needs to be true if you want to call mapMem on the resulting MemFile; else file handles are not kept open.

mapFlags allows callers to override default choices for memory mapping flags with a bitwise mask of a variety of likely platform-specific flags which may be ignored or even cause open to fail if misspecified.

Example:

  1. var
  2. mm, mm_full, mm_half: MemFile
  3. mm = memfiles.open("/tmp/test.mmap", mode = fmWrite, newFileSize = 1024) # Create a new file
  4. mm.close()
  5. # Read the whole file, would fail if newFileSize was set
  6. mm_full = memfiles.open("/tmp/test.mmap", mode = fmReadWrite, mappedSize = -1)
  7. # Read the first 512 bytes
  8. mm_half = memfiles.open("/tmp/test.mmap", mode = fmReadWrite, mappedSize = 512)

Source Edit

  1. proc resize(f: var MemFile; newFileSize: int) {....raises: [IOError, OSError],
  2. tags: [], forbids: [].}

Resize & re-map the file underlying an allowRemap MemFile. If the OS/FS supports it, file space is reserved to ensure room for new virtual pages. Caller should wait often enough for flush to finish to limit use of system RAM for write buffering, perhaps just prior to this call. Note: this assumes the entire file is mapped read-write at offset 0. Also, the value of .mem will probably change. Source Edit

  1. proc unmapMem(f: var MemFile; p: pointer; size: int) {....raises: [OSError],
  2. tags: [], forbids: [].}

unmaps the memory region (p, <p+size) of the mapped file f. All changes are written back to the file system, if f was opened with write access.

size must be of exactly the size that was requested via mapMem.

Source Edit

Iterators

  1. iterator lines(mfile: MemFile; buf: var string; delim = '\n'; eat = '\r'): string {.
  2. inline, ...raises: [], tags: [], forbids: [].}

Replace contents of passed buffer with each new line, like readLine(File). delim, eat, and delimiting logic is exactly as for memSlices, but Nim strings are returned.

Example:

  1. var buffer: string = ""
  2. for line in lines(memfiles.open("foo"), buffer):
  3. echo line

Source Edit

  1. iterator lines(mfile: MemFile; delim = '\n'; eat = '\r'): string {.inline,
  2. ...raises: [], tags: [], forbids: [].}

Return each line in a file as a Nim string, like lines(File). delim, eat, and delimiting logic is exactly as for memSlices, but Nim strings are returned.

Example:

  1. for line in lines(memfiles.open("foo")):
  2. echo line

Source Edit

  1. iterator memSlices(mfile: MemFile; delim = '\n'; eat = '\r'): MemSlice {.inline,
  2. ...raises: [], tags: [], forbids: [].}

Iterates over [optional eat] delim-delimited slices in MemFile mfile.

Default parameters parse lines ending in either Unix(\l) or Windows(\r\l) style on on a line-by-line basis. I.e., not every line needs the same ending. Unlike readLine(File) & lines(File), archaic MacOS9 \r-delimited lines are not supported as a third option for each line. Such archaic MacOS9 files can be handled by passing delim=’\r’, eat=’\0’, though.

Delimiters are not part of the returned slice. A final, unterminated line or record is returned just like any other.

Non-default delimiters can be passed to allow iteration over other sorts of “line-like” variable length records. Pass eat=’\0’ to be strictly delim-delimited. (Eating an optional prefix equal to ‘\0’ is not supported.)

This zero copy, memchr-limited interface is probably the fastest way to iterate over line-like records in a file. However, returned (data,size) objects are not Nim strings, bounds checked Nim arrays, or even terminated C strings. So, care is required to access the data (e.g., think C mem* functions, not str* functions).

Example:

  1. var count = 0
  2. for slice in memSlices(memfiles.open("foo")):
  3. if slice.size > 0 and cast[cstring](slice.data)[0] != '#':
  4. inc(count)
  5. echo count

Source Edit