// Written by retoor@molodetz.nl

// This code provides a mechanism to initialize and manage file-backed memory using memory mapping and file operations for storing large
// data sets temporarily in a file system.

// The code uses `fcntl.h`, `stdbool.h`, `stdio.h`, `stdlib.h`, `string.h`, `sys/mman.h`, and `unistd.h` for file handling, memory
// management, and basic input/output operations.

// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

#include <fcntl.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <unistd.h>

typedef struct rfm_t {
    char path[4096];
    void *data;
    size_t size;
    long ptr;
    FILE *f;
    int fd;
} rfm_t;

rfm_t rfm;
bool initialized = false;

void rfm_destroy(rfm_t *r) {
    if (munmap(r->data, r->size) == -1) {
        perror("munmap");
        exit(EXIT_FAILURE);
    }
    close(r->fd);
}

void *falloc(size_t s) {
    rfm_t *rr = &rfm;
    char *data = (char *)rr->data + rfm.ptr;
    rfm.ptr += s;
    return data;
}

void *finit(char *path, size_t size) {
    if (!initialized) {
        initialized = true;
        memset(&rfm, 0, sizeof(rfm_t));
        rfm.size = size;

        if (path) {
            strcpy(rfm.path, path);
            rfm.fd = open(path, O_RDWR);
        } else {
            rfm.f = tmpfile();
            rfm.fd = fileno(rfm.f);
        }

        rfm.data = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, rfm.fd, 0);
    }
}

int main() {
    finit("tast.dat", 1024 * 1024 * 100);
    char *data = (char *)falloc(10);
    strcpy(data, "ab");
    char *data2 = (char *)falloc(30);
    strcpy(data2, "ff\n");
    printf("%s\n", data);
    return 0;
}