universe@15: /* universe@15: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. universe@15: * Copyright 2023 Mike Becker. All rights reserved. universe@15: * universe@15: * Redistribution and use in source and binary forms, with or without universe@15: * modification, are permitted provided that the following conditions are met: universe@15: * universe@15: * 1. Redistributions of source code must retain the above copyright universe@15: * notice, this list of conditions and the following disclaimer. universe@15: * universe@15: * 2. Redistributions in binary form must reproduce the above copyright universe@15: * notice, this list of conditions and the following disclaimer in the universe@15: * documentation and/or other materials provided with the distribution. universe@15: * universe@15: * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" universe@15: * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE universe@15: * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE universe@15: * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE universe@15: * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR universe@15: * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF universe@15: * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS universe@15: * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN universe@15: * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) universe@15: * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE universe@15: * POSSIBILITY OF SUCH DAMAGE. universe@15: */ universe@15: universe@15: #include "ascension/files.h" universe@15: #include "ascension/error.h" universe@15: universe@15: #include universe@15: #include universe@15: #include universe@15: #include universe@15: universe@15: asc_file asc_file_mmap_rdonly(char const *filename) { universe@15: int fd = open(filename, O_RDONLY); universe@15: if (fd < 0) { universe@15: asc_dprintf("Failed to open file %s", filename); universe@15: return (cxstring) {NULL, 0}; universe@15: } universe@15: universe@15: struct stat statbuf; universe@15: int err = fstat(fd, &statbuf); universe@15: if (err < 0) { universe@15: close(fd); universe@15: asc_dprintf("Failed to stat file %s", filename); universe@15: return (cxstring) {NULL, 0}; universe@15: } universe@15: universe@15: char const *data = mmap(NULL, statbuf.st_size, PROT_READ, MAP_SHARED, fd, 0); universe@15: if (data == MAP_FAILED) { universe@15: close(fd); universe@15: asc_dprintf("Failed to map file %s into memory", filename); universe@15: return (cxstring) {NULL, 0}; universe@15: } universe@15: close(fd); universe@15: universe@15: return cx_strn(data, statbuf.st_size); universe@15: } universe@15: universe@15: void asc_file_unmap(asc_file file) { universe@15: munmap((void *) file.ptr, file.length); universe@15: }