diff --git a/lean/Makefile b/lean/Makefile index 2ab6ad0..d09401b 100644 --- a/lean/Makefile +++ b/lean/Makefile @@ -4,8 +4,8 @@ test: gcc -c src/*.c -Iinclude -Wall -pedantic --std=gnu11 - g++ -c src/*.cpp -Iinclude -Wall -pedantic --std=gnu++11 - gcc -o $@ *.o + g++ -c src/*.cpp -Iinclude -Wall -pedantic --std=gnu++20 + g++ -o $@ *.o ./$@ clean: rm -f test diff --git a/lean/include/map.h b/lean/include/map.h index 7574cf2..87534a1 100644 --- a/lean/include/map.h +++ b/lean/include/map.h @@ -18,8 +18,52 @@ typedef struct mmap { int open_and_map(const char* file, mmap_t* restrict ptr); int unmap_and_close(mmap_t map); -#ifdef _cplusplus +typedef void* (*map_cb)(mmap_t map); +void* map_and_then(const char* file, map_cb callback); + +#ifdef __cplusplus +} +#include +#include +namespace mm { + struct mmap { + inline static mmap_t create_raw(const char* file) + { + mmap_t map; + if (!open_and_map(file, &map)) panic("Failed to map file"); + return map; + } + + inline mmap(mmap_t raw) :inner(raw){} + inline mmap(const char* file) + : inner(create_raw(file)) {} + + inline mmap(mmap&& move) : inner(move.inner) + { + auto other = const_cast(&move.inner); + other->ptr = nullptr; + } + inline mmap(const mmap& copt) = delete; + + inline ~mmap() + { + if (inner.ptr) { + ::unmap_and_close(inner); + } + } + + inline const std::uint8_t* as_ptr() const { return (const std::uint8_t*)inner.ptr; } + inline std::uint8_t* as_ptr() { return (std::uint8_t*)inner.ptr; } + + inline std::size_t size() const { return inner.len; } + + inline int as_fd() const { return inner.fd; } + inline const mmap_t& as_raw() const { return inner; } + private: + const mmap_t inner; + }; } + #undef restrict #endif diff --git a/lean/src/main.c b/lean/src/main.c index 3197400..330c412 100644 --- a/lean/src/main.c +++ b/lean/src/main.c @@ -7,6 +7,7 @@ #include #include #include +#include _Static_assert(sizeof(float)==sizeof(uint32_t), "float is not 32 bits"); @@ -21,6 +22,14 @@ static void unshuffle_file(const char* filename) panic("unimplemented"); }*/ +static void* map_callback(mmap_t map) +{ + printf("fd %d mapped (sz %lu) (ptr %p)\n", map.fd, map.len, map.ptr); + + + return NULL; +} + static void do_test() { char* string = "Hello world.. how are you?????"; @@ -45,7 +54,10 @@ static void do_test() int main(int argc, char** argv) { - do_test(); + do_test(); + if( argv[1] ) { + map_and_then(argv[1], &map_callback); + } return 0; } diff --git a/lean/src/map_callback.cpp b/lean/src/map_callback.cpp new file mode 100644 index 0000000..8ea87b8 --- /dev/null +++ b/lean/src/map_callback.cpp @@ -0,0 +1,11 @@ + +#include +#include +#include + + +extern "C" void* map_and_then(const char* file, map_cb callback) +{ + mm::mmap map(file); + return callback(map.as_raw()); +}