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

#include "mmap.h"

bool
Mmap(unsigned char **buf, size_t *len, const char *path)
{
    int fd = open(path, O_RDONLY | O_CLOEXEC); // NOLINT(hicpp-signed-bitwise)
    if (fd == -1) {
        fprintf(stderr, "open: %s\n", strerror(errno));
        return false;
    }
    struct stat sb;
    memset(&sb, 0, sizeof(struct stat));
    if (fstat(fd, &sb) != 0) {
        fprintf(stderr, "fstat: %s\n", strerror(errno));
        return false;
    }
    (*len) = (size_t)sb.st_size;
    errno = 0;
    (*buf) = mmap(NULL, *len, PROT_READ, MAP_SHARED, fd, 0);
    if ((*buf) == MAP_FAILED) { // NOLINT(performance-no-int-to-ptr)
        fprintf(stderr, "mmap: %s\n", strerror(errno));
    }
    close(fd);
    return (*buf) != MAP_FAILED; // NOLINT(performance-no-int-to-ptr)
}
