MappedFile.cpp 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. #include "MappedFile.h"
  2. #include <sys/mman.h>
  3. #include <sys/stat.h>
  4. #include <fcntl.h>
  5. #include <cstdio>
  6. namespace AK {
  7. MappedFile::MappedFile(String&& file_name)
  8. : m_file_name(std::move(file_name))
  9. {
  10. m_file_length = 1024;
  11. m_fd = open(m_file_name.characters(), O_RDONLY);
  12. if (m_fd != -1) {
  13. struct stat st;
  14. fstat(m_fd, &st);
  15. m_file_length = st.st_size;
  16. m_map = mmap(nullptr, m_file_length, PROT_READ, MAP_SHARED, m_fd, 0);
  17. if (m_map == MAP_FAILED)
  18. perror("");
  19. }
  20. printf("MappedFile{%s} := { m_fd=%d, m_file_length=%zu, m_map=%p }\n", m_file_name.characters(), m_fd, m_file_length, m_map);
  21. }
  22. MappedFile::~MappedFile()
  23. {
  24. if (m_map != (void*)-1) {
  25. ASSERT(m_fd != -1);
  26. munmap(m_map, m_file_length);
  27. }
  28. }
  29. MappedFile::MappedFile(MappedFile&& other)
  30. : m_file_name(std::move(other.m_file_name))
  31. , m_file_length(other.m_file_length)
  32. , m_fd(other.m_fd)
  33. , m_map(other.m_map)
  34. {
  35. other.m_file_length = 0;
  36. other.m_fd = -1;
  37. other.m_map = (void*)-1;
  38. }
  39. }