aboutsummaryrefslogtreecommitdiff
path: root/thirdparty/tourist/foundation/src/ref.cpp
blob: feda5b0dd045e9073774c1217cec2d04565ef1c0 (plain) (blame)
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
60
61
62
63
64
65
66
67
68
69
#include <foundation/buffer.h>

#include "slab.h"

//------------------------------------------------------------------------------
Pointer::Pointer(Slab* slab, const uint8* ptr)
: _ptr(uintptr(ptr))
, _pinned(0)
{
    uintptr bias = (uintptr(ptr) - uintptr(slab)) / alignof(Slab);
    _slab_offset = bias;
}

//------------------------------------------------------------------------------
Pointer::Pointer(Pointer&& rhs)
{
    *this = std::move(rhs);
}

//------------------------------------------------------------------------------
Pointer::~Pointer()
{
    if (_pinned)
        get_slab()->dec_ref();
}

//------------------------------------------------------------------------------
void Pointer::operator = (Pointer&& rhs)
{
    std::swap(_value, rhs._value);
}

//------------------------------------------------------------------------------
bool Pointer::is_valid() const
{
    return _ptr != 0;
}

//------------------------------------------------------------------------------
void Pointer::pin()
{
    if (!_pinned)
        get_slab()->inc_ref();
    _pinned = 1;
}

//------------------------------------------------------------------------------
const uint8* Pointer::get() const
{
    return (uint8*)_ptr;
}

//------------------------------------------------------------------------------
Slab* Pointer::get_slab() const
{
    uintptr bias = _slab_offset * alignof(Slab);
    bias += uintptr(_ptr) & (alignof(Slab) - 1);
    return (Slab*)(_ptr - bias);
}



//------------------------------------------------------------------------------
BufferRef::BufferRef(Slab* slab, const uint8* ptr)
: Pointer(slab, ptr)
{
    pin();
}