mapping callback

lean
Avril 4 years ago
parent b64ab59240
commit 57b01b78f3
Signed by: flanchan
GPG Key ID: 284488987C31F630

@ -4,8 +4,8 @@
test: test:
gcc -c src/*.c -Iinclude -Wall -pedantic --std=gnu11 gcc -c src/*.c -Iinclude -Wall -pedantic --std=gnu11
g++ -c src/*.cpp -Iinclude -Wall -pedantic --std=gnu++11 g++ -c src/*.cpp -Iinclude -Wall -pedantic --std=gnu++20
gcc -o $@ *.o g++ -o $@ *.o
./$@ ./$@
clean: clean:
rm -f test rm -f test

@ -18,8 +18,52 @@ typedef struct mmap {
int open_and_map(const char* file, mmap_t* restrict ptr); int open_and_map(const char* file, mmap_t* restrict ptr);
int unmap_and_close(mmap_t map); 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 <panic.h>
#include <cstdint>
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<mmap_t*>(&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 #undef restrict
#endif #endif

@ -7,6 +7,7 @@
#include <shuffle3.h> #include <shuffle3.h>
#include <panic.h> #include <panic.h>
#include <reinterpret.h> #include <reinterpret.h>
#include <map.h>
_Static_assert(sizeof(float)==sizeof(uint32_t), "float is not 32 bits"); _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"); 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() static void do_test()
{ {
char* string = "Hello world.. how are you?????"; char* string = "Hello world.. how are you?????";
@ -45,7 +54,10 @@ static void do_test()
int main(int argc, char** argv) int main(int argc, char** argv)
{ {
do_test(); do_test();
if( argv[1] ) {
map_and_then(argv[1], &map_callback);
}
return 0; return 0;
} }

@ -0,0 +1,11 @@
#include <shuffle3.h>
#include <reinterpret.hpp>
#include <map.h>
extern "C" void* map_and_then(const char* file, map_cb callback)
{
mm::mmap map(file);
return callback(map.as_raw());
}
Loading…
Cancel
Save