# memory_region.ffi

> A module of memory-region's API.

POSIX, for the two backings that need it.

Kept apart from the regions themselves so that a reader of `region.mojo` sees
what a region *is* rather than which integer `O_CREAT` happens to be on this
platform.

## Functions

### `o_creat`

```mojo
def o_creat() -> Int
```

`O_CREAT`, which is not the same number on both platforms.

macOS has 0x0200 and Linux 0x40. Getting it wrong does not fail loudly —
it opens with some other flag set — so it is spelled out here rather than
inherited from a header nobody reads.

### `o_trunc`

```mojo
def o_trunc() -> Int
```

`O_TRUNC`: 0x0400 on macOS, 0x200 on Linux.

### `cstr`

```mojo
def cstr(s: String) -> List[UInt8]
```

A NUL-terminated copy, owned by the caller across the FFI call.

### `open_file`

```mojo
def open_file(path: String, flags: Int, mode: Int = Int(384)) -> Int
```

`open(2)`, as an fd.

`open` is variadic in C — `int open(const char *, int, ...)` — and a
variadic call has a different ABI from a fixed one on arm64, so the
fixed-argument count has to be declared or the mode lands in the wrong
place. It fails at LLVM lowering rather than at the call, so the error
does not point here.

### `close_fd`

```mojo
def close_fd(fd: Int)
```

### `file_size`

```mojo
def file_size(path: String) -> Int
```

The size of the file at `path`, from the standard library's `stat`.

This used to be `lseek(fd, 0, SEEK_END)` through `external_call`. The
standard library declares `lseek` too, for `FileHandle.seek`, with
different argument types, and one program can't hold two declarations of
one C function: any binary that used both failed to compile with
"existing function with conflicting signature".

### `truncate`

```mojo
def truncate(fd: Int, size: Int) -> Bool
```

### `map_file`

```mojo
def map_file(fd: Int, size: Int, writable: Bool) -> Int
```

`mmap(..., MAP_SHARED)`; 0 when the kernel refused.

### `unmap`

```mojo
def unmap(addr: Int, size: Int)
```

## Aliases

### `PROT_READ`

```mojo
comptime PROT_READ = Int(1)
```

### `PROT_WRITE`

```mojo
comptime PROT_WRITE = Int(2)
```

### `MAP_SHARED`

```mojo
comptime MAP_SHARED = Int(1)
```

### `MAP_FAILED`

```mojo
comptime MAP_FAILED = Int(-1)
```

### `O_RDONLY`

```mojo
comptime O_RDONLY = Int(0)
```

### `O_RDWR`

```mojo
comptime O_RDWR = Int(2)
```
