summaryrefslogtreecommitdiff
path: root/AK/BufferStream.h
blob: 0b8ad76f15c07846d9f47283636252200f4b1677 (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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#pragma once

#include <AK/AKString.h>
#include <AK/ByteBuffer.h>

namespace AK {

class BufferStream {
public:
    explicit BufferStream(ByteBuffer& buffer)
        : m_buffer(buffer)
    {
    }

    void operator<<(u8 value)
    {
        m_buffer[m_offset++] = value & 0xffu;
    }

    void operator<<(char value)
    {
        m_buffer[m_offset++] = (u8)value;
    }

    void operator<<(u16 value)
    {
        m_buffer[m_offset++] = value & 0xffu;
        m_buffer[m_offset++] = (u8)(value >> 8) & 0xffu;
    }

    void operator<<(u32 value)
    {
        m_buffer[m_offset++] = value & 0xffu;
        m_buffer[m_offset++] = (u8)(value >> 8) & 0xffu;
        m_buffer[m_offset++] = (u8)(value >> 16) & 0xffu;
        m_buffer[m_offset++] = (u8)(value >> 24) & 0xffu;
    }

    void operator<<(const StringView& value)
    {
        for (ssize_t i = 0; i < value.length(); ++i)
            m_buffer[m_offset++] = value[i];
    }

    void operator<<(const ByteBuffer& value)
    {
        for (ssize_t i = 0; i < value.size(); ++i)
            m_buffer[m_offset++] = value[i];
    }

    bool at_end() const
    {
        return m_offset == m_buffer.size();
    }

    void fill_to_end(u8 ch)
    {
        while (!at_end())
            m_buffer[m_offset++] = ch;
    }

    ssize_t offset() const { return m_offset; }

    void snip()
    {
        m_buffer.trim(m_offset);
    }

private:
    ByteBuffer& m_buffer;
    ssize_t m_offset { 0 };
};

}

using AK::BufferStream;