aboutsummaryrefslogtreecommitdiff
path: root/sys
diff options
context:
space:
mode:
authorNicholas Noll <nbnoll@eml.cc>2020-04-25 11:39:01 -0700
committerNicholas Noll <nbnoll@eml.cc>2020-04-25 11:39:01 -0700
commit50081012e8dcf3c4ee4163526f684afa707c5a98 (patch)
treeddef4c9eabc1ac1bb39d18eef6fe70408e2cdda6 /sys
parent788ddbd8e113cd4f9694aee779c5b5dcca26e30b (diff)
feat: added memory mapped file reader
Diffstat (limited to 'sys')
-rw-r--r--sys/libn/mmap.c42
1 files changed, 42 insertions, 0 deletions
diff --git a/sys/libn/mmap.c b/sys/libn/mmap.c
new file mode 100644
index 0000000..d8b2a61
--- /dev/null
+++ b/sys/libn/mmap.c
@@ -0,0 +1,42 @@
+#include <u.h>
+#include <libn.h>
+
+#include <sys/mman.h>
+
+mmap·Reader
+mmap·open(byte *filename)
+{
+ int fd;
+ int err;
+ void *buf;
+ Stream *s;
+ io·Stat st;
+
+ s = io·open(filename, "r");
+ fd = io·fd(s);
+ err = io·stat(s, &st);
+ if (err) {
+ errorf("file stat: error code %d", err);
+ goto ERROR;
+ }
+ buf = mmap(nil, st.st_size, PROT_READ, MAP_SHARED, fd, 0);
+ if (!buf) {
+ errorf("mmap: failed");
+ goto ERROR;
+ }
+ // NOTE: posix systems require that reference kept to mmap file after fd is closed
+ io·close(s);
+ return (mmap·Reader){.len=st.st_size, .buf=buf};
+
+ERROR:
+ io·close(s);
+ return (mmap·Reader){ 0 };
+}
+
+error
+mmap·close(mmap·Reader rdr)
+{
+ munmap(rdr.buf, rdr.len);
+
+ return 0;
+}