MappedFile.h 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2023, kleines Filmröllchen <filmroellchen@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #pragma once
  8. #include <AK/ByteBuffer.h>
  9. #include <AK/Error.h>
  10. #include <AK/MemoryStream.h>
  11. #include <AK/Noncopyable.h>
  12. #include <AK/NonnullOwnPtr.h>
  13. #include <AK/RefCounted.h>
  14. #include <LibCore/Forward.h>
  15. namespace Core {
  16. class MappedFile : public FixedMemoryStream {
  17. AK_MAKE_NONCOPYABLE(MappedFile);
  18. AK_MAKE_NONMOVABLE(MappedFile);
  19. public:
  20. static ErrorOr<NonnullOwnPtr<MappedFile>> map(StringView path, Mode mode = Mode::ReadOnly);
  21. static ErrorOr<NonnullOwnPtr<MappedFile>> map_from_file(NonnullOwnPtr<Core::File>, StringView path);
  22. static ErrorOr<NonnullOwnPtr<MappedFile>> map_from_fd_and_close(int fd, StringView path, Mode mode = Mode::ReadOnly);
  23. virtual ~MappedFile();
  24. // Non-stream APIs for using MappedFile as a simple POSIX API wrapper.
  25. void* data() { return m_data; }
  26. void const* data() const { return m_data; }
  27. ReadonlyBytes bytes() const { return { m_data, m_size }; }
  28. private:
  29. explicit MappedFile(void*, size_t, Mode);
  30. void* m_data { nullptr };
  31. size_t m_size { 0 };
  32. };
  33. class SharedMappedFile : public RefCounted<SharedMappedFile> {
  34. public:
  35. explicit SharedMappedFile(NonnullOwnPtr<MappedFile> file)
  36. : m_file(move(file))
  37. {
  38. }
  39. MappedFile const& operator->() const { return *m_file; }
  40. MappedFile& operator->() { return *m_file; }
  41. private:
  42. NonnullOwnPtr<MappedFile> m_file;
  43. };
  44. }