summaryrefslogtreecommitdiff
path: root/AK/Ptr32.h
blob: 9c7880123cc8f56d38b9d7a0927d39090474f597 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/*
 * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
 * Copyright (c) 2021, Leon Albrecht <leon2002.la@gmail.com>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#pragma once

#include <AK/Assertions.h>
#include <AK/Types.h>

namespace AK {

template<typename T>
class Ptr32 {
public:
    constexpr Ptr32() = default;
    Ptr32(T* const ptr)
        : m_ptr((u32) reinterpret_cast<FlatPtr>(ptr))
    {
        VERIFY((reinterpret_cast<FlatPtr>(ptr) & 0xFFFFFFFFULL) == static_cast<FlatPtr>(m_ptr));
    }
    T& operator*() { return *static_cast<T*>(*this); }
    T const& operator*() const { return *static_cast<T const*>(*this); }

    T* operator->() { return *this; }
    T const* operator->() const { return *this; }

    operator T*() { return reinterpret_cast<T*>(static_cast<FlatPtr>(m_ptr)); }
    operator T const*() const { return reinterpret_cast<T const*>(static_cast<FlatPtr>(m_ptr)); }

    T& operator[](size_t index) { return static_cast<T*>(*this)[index]; }
    T const& operator[](size_t index) const { return static_cast<T const*>(*this)[index]; }

    constexpr explicit operator bool() { return m_ptr; }
    template<typename U>
    constexpr bool operator==(Ptr32<U> other) { return m_ptr == other.m_ptr; }

    constexpr Ptr32<T> operator+(u32 other) const
    {
        Ptr32<T> ptr {};
        ptr.m_ptr = m_ptr + other;
        return ptr;
    }
    constexpr Ptr32<T> operator-(u32 other) const
    {
        Ptr32<T> ptr {};
        ptr.m_ptr = m_ptr - other;
        return ptr;
    }

private:
    u32 m_ptr { 0 };
};

}

using AK::Ptr32;