← Back to AILP Home

Binary I/O

Nitpick provides dedicated utilities for efficiently loading and manipulating binary data. While text files are usually processed via File.read or File_read_line, binary files require raw buffer management.

Reading Binary Files

To read a binary file directly into memory, use readBinary. This function returns an opaque handle (typed as an int8-> pointer) that manages the underlying buffer.

// Read a binary file, returns an opaque handle
int8->:handle = readBinary("data.bin");

// Get the length of the binary content
int64:size = binarySize(handle);

// Get the raw memory pointer to the buffer
int64:ptr = binaryPtr(handle);

// Read a byte from the buffer (assuming a mem_read utility exists)
// int32:byte = mem_read(ptr, 0);

// Free the handle when done to prevent memory leaks
int64:freed = binaryFree(handle);

Writing Binary Files

To write binary data to a file, use writeBinary. This takes the file path, the raw memory pointer, and the size in bytes.

// Write `size` bytes from `ptr` into "output.bin"
int64:w = writeBinary("output.bin", ptr, size);

Buffer Management

When working with binary I/O, you often need to manage raw memory. Since readBinary allocates its own buffer, you must always release it with binaryFree(handle).

If you are constructing your own binary data to pass to writeBinary, you would typically: 1. Allocate memory using allocate(size) or similar. 2. Populate the memory using pointer offsets (mem_write(ptr, offset, value)). 3. Write to disk with writeBinary(path, ptr, size).

Examples

Read a ROM File (Chip-8 Pattern)

A common pattern for emulators is loading a ROM file into a specific memory region.

func:load_rom = int64(string:path) {
    int8->:h = readBinary(path);
    int64:size = binarySize(h);
    int64:ptr = binaryPtr(h);

    // Copy the ROM data into emulator memory at offset 0x200
    // (Assuming a mem_copy implementation)
    // mem_copy(EMU_MEM_PTR + 0x200, ptr, size);

    _ = binaryFree(h);
    return size;
};

Copy a Binary File

func:copy_binary = void(string:src, string:dest) {
    int8->:h = readBinary(src);
    int64:size = binarySize(h);
    int64:ptr = binaryPtr(h);

    int64:w = writeBinary(dest, ptr, size);

    _ = binaryFree(h);
};