aboutsummaryrefslogtreecommitdiff
path: root/thirdparty/tourist/foundation/src/stream.cpp
blob: 97d4cb39507ba29fdd29fed937d177749bffffb2 (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
70
71
72
73
74
75
76
77
#include <foundation/buffer.h>

#include "slab.h"

#include <stdexcept>

//------------------------------------------------------------------------------
BufferStream::BufferStream(Slab* slab, const uint8* ptr, uint32 size)
: _ptr(ptr)
, _slab_offset(uint32(uintptr(ptr) - uintptr(slab)))
, _end(size)
{
}

//------------------------------------------------------------------------------
Slab* BufferStream::get_slab() const
{
    return (Slab*)(_ptr - _slab_offset);
}

//------------------------------------------------------------------------------
bool BufferStream::has_data() const
{
    return (_cursor < _end);
}

//------------------------------------------------------------------------------
uint32 BufferStream::get_consumed() const
{
    return _cursor;
}

//------------------------------------------------------------------------------
uint32 BufferStream::get_remaining() const
{
    return uint32(ptrdiff_t(_end - _cursor));
}

//------------------------------------------------------------------------------
const uint8* BufferStream::read(uint32 size)
{
    if (size > _end - _cursor)
        throw std::runtime_error("BufferStream: read past end of buffer");
    const uint8* ret = (uint8*)_ptr + _cursor;
    _cursor += size;
    return ret;
}

//------------------------------------------------------------------------------
Buffer BufferStream::read_buf(uint32 size)
{
    const uint8* ptr = read(size);

    Buffer buffer;
    buffer._slab = get_slab();
    buffer._offset = uint32(uintptr(ptr) - uintptr(buffer._slab));
    buffer._size = size;
    return buffer;
}

//------------------------------------------------------------------------------
Pointer BufferStream::read_ptr(uint32 size)
{
    const uint8* ret = read(size);
    Slab* slab = get_slab();
    return Pointer(slab, ret);
}

//------------------------------------------------------------------------------
template <>  int8  BufferStream::read< int8>()  { return *( int8 *)read(sizeof( int8)); }
template <>  int16 BufferStream::read< int16>() { return *( int16*)read(sizeof( int16)); }
template <>  int32 BufferStream::read< int32>() { return *( int32*)read(sizeof( int32)); }
template <>  int64 BufferStream::read< int64>() { return *( int64*)read(sizeof( int64)); }
template <> uint8  BufferStream::read<uint8>()  { return *(uint8 *)read(sizeof(uint8)); }
template <> uint16 BufferStream::read<uint16>() { return *(uint16*)read(sizeof(uint16)); }
template <> uint32 BufferStream::read<uint32>() { return *(uint32*)read(sizeof(uint32)); }
template <> uint64 BufferStream::read<uint64>() { return *(uint64*)read(sizeof(uint64)); }