| 1 |
@system unittest |
| 2 |
{ |
| 3 |
import std.mmfile; |
| 4 |
|
| 5 |
import std.file; |
| 6 |
std.file.write(deleteme, "hello"); // deleteme is a temporary filename |
| 7 |
scope(exit) remove(deleteme); |
| 8 |
|
| 9 |
// Use a scope class so the file will be closed at the end of this function |
| 10 |
scope mmfile = new MmFile(deleteme); |
| 11 |
|
| 12 |
assert(mmfile.length == "hello".length); |
| 13 |
|
| 14 |
// Access file contents with the slice operator |
| 15 |
// This is typed as `void[]`, so cast to `char[]` or `ubyte[]` to use it |
| 16 |
const data = cast(const(char)[]) mmfile[]; |
| 17 |
|
| 18 |
// At this point, the file content may not have been read yet. |
| 19 |
// In that case, the following memory access will intentionally |
| 20 |
// trigger a page fault, causing the kernel to load the file contents |
| 21 |
assert(data[0 .. 5] == "hello"); |
| 22 |
} |
| 23 |
|
| 24 |
@system unittest |
| 25 |
{ |
| 26 |
import std.mmfile; |
| 27 |
|
| 28 |
import std.file; |
| 29 |
scope(exit) remove(deleteme); |
| 30 |
|
| 31 |
scope mmfile = new MmFile(deleteme, MmFile.Mode.readWriteNew, 5, null); |
| 32 |
assert(mmfile.length == 5); |
| 33 |
|
| 34 |
auto data = cast(ubyte[]) mmfile[]; |
| 35 |
|
| 36 |
// This write to memory will be reflected in the file contents |
| 37 |
data[] = '\n'; |
| 38 |
|
| 39 |
mmfile.flush(); |
| 40 |
|
| 41 |
assert(std.file.read(deleteme) == "\n\n\n\n\n"); |
| 42 |
} |
| 43 |
|