diff options
author | Araq <rumpf_a@web.de> | 2011-10-22 11:08:52 +0200 |
---|---|---|
committer | Araq <rumpf_a@web.de> | 2011-10-22 11:08:52 +0200 |
commit | 235bd1c47402a62db097a0bae7d63224b46d02d8 (patch) | |
tree | 4cf5b3808c785cb7487de8b80cb503fd2b5cbd54 /lib | |
parent | ded7f6a6d56eaeeee0e9788a0637012e53981475 (diff) | |
download | Nim-235bd1c47402a62db097a0bae7d63224b46d02d8.tar.gz |
preparations for proper memmap'ed files
Diffstat (limited to 'lib')
-rw-r--r-- | lib/pure/memfiles.nim | 51 |
1 files changed, 51 insertions, 0 deletions
diff --git a/lib/pure/memfiles.nim b/lib/pure/memfiles.nim new file mode 100644 index 000000000..dd95d8d24 --- /dev/null +++ b/lib/pure/memfiles.nim @@ -0,0 +1,51 @@ +# +# +# Nimrod's Runtime Library +# (c) Copyright 2011 Andreas Rumpf +# +# See the file "copying.txt", included in this +# distribution, for details about the copyright. +# + +## This module provides support for `memory mapped files`:idx: +## (Posix's `mmap`:idx:) on the different operating systems. +## XXX Currently it is implemented with Nimrod's +## basic IO facilities and does not use any platform specific code! +## Oh and currently only ``fmRead`` is supported... + +type + TMemFile* = object {.pure.} + file: TFile + buffer: pointer + fileLen: int + +proc open*(f: var TMemFile, filename: string, mode: TFileMode = fmRead): bool = + ## open a memory mapped file `f`. Returns true for success. + assert mode == fmRead + result = open(f.file, filename, mode) + + var len = getFileSize(f.file) + if len < high(int): + f.fileLen = int(len) + f.buffer = alloc(f.fileLen) + if readBuffer(f.file, f.buffer, f.fileLen) != f.fileLen: + raise newException(EIO, "error while reading from file") + else: + raise newException(EIO, "file too big to fit in memory") + +proc close*(f: var TMemFile) = + ## closes the memory mapped file `f`. All changes are written back to the + ## file system, if `f` was opened with write access. + dealloc(f.buffer) + close(f.file) + +proc mem*(f: var TMemFile): pointer {.inline.} = + ## retrives a pointer to the memory mapped file `f`. The pointer can be + ## used directly to change the contents of the file, if `f` was opened + ## with write access. + result = f.buffer + +proc size*(f: var TMemFile): int {.inline.} = + ## retrives the size of the memory mapped file `f`. + result = f.fileLen + |