Range.h 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/Types.h>
  8. #include <Kernel/VirtualAddress.h>
  9. namespace UserspaceEmulator {
  10. class Range {
  11. friend class RangeAllocator;
  12. public:
  13. Range() = delete;
  14. Range(VirtualAddress base, size_t size)
  15. : m_base(base)
  16. , m_size(size)
  17. {
  18. }
  19. VirtualAddress base() const { return m_base; }
  20. size_t size() const { return m_size; }
  21. bool is_valid() const { return !m_base.is_null(); }
  22. bool contains(VirtualAddress vaddr) const { return vaddr >= base() && vaddr < end(); }
  23. VirtualAddress end() const { return m_base.offset(m_size); }
  24. bool operator==(const Range& other) const
  25. {
  26. return m_base == other.m_base && m_size == other.m_size;
  27. }
  28. bool contains(VirtualAddress base, size_t size) const
  29. {
  30. if (base.offset(size) < base)
  31. return false;
  32. return base >= m_base && base.offset(size) <= end();
  33. }
  34. bool contains(const Range& other) const
  35. {
  36. return contains(other.base(), other.size());
  37. }
  38. Vector<Range, 2> carve(const Range&) const;
  39. Range split_at(VirtualAddress address)
  40. {
  41. VERIFY(address.is_page_aligned());
  42. VERIFY(m_base < address);
  43. size_t new_size = (address - m_base).get();
  44. VERIFY(new_size < m_size);
  45. size_t other_size = m_size - new_size;
  46. m_size = new_size;
  47. return { address, other_size };
  48. }
  49. private:
  50. VirtualAddress m_base;
  51. size_t m_size { 0 };
  52. };
  53. }
  54. namespace AK {
  55. template<>
  56. struct Traits<UserspaceEmulator::Range> : public GenericTraits<UserspaceEmulator::Range> {
  57. static constexpr bool is_trivial() { return true; }
  58. };
  59. }