summaryrefslogtreecommitdiffstatshomepage
path: root/include/winapi/buffer.hpp
blob: fa087260f59b0ac2bf0640f2a16543973fa5941b (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
78
79
80
81
82
83
84
85
86
// Copyright (c) 2020 Egor Tensin <egor@tensin.name>
// This file is part of the "winapi-common" project.
// For details, see https://github.com/egor-tensin/winapi-common
// Distributed under the MIT License.

#pragma once

#include <cstddef>
#include <cstring>
#include <format>
#include <initializer_list>
#include <stdexcept>
#include <string>
#include <string_view>
#include <utility>
#include <vector>

namespace winapi {

/**
 * @brief Binary data container.
 *
 * This class wraps a blob of binary data.
 */
class Buffer : public std::vector<unsigned char> {
public:
    using Parent = std::vector<unsigned char>;

    Buffer() = default;

    /** Construct a buffer from an explicit list of byte values. */
    Buffer(std::initializer_list<unsigned char> lst) : Parent{lst} {}

    /** Construct a buffer from an instance of `std::vector<unsigned char>`. */
    explicit Buffer(Parent&& src) : Parent{std::move(src)} {}

    /** Construct a buffer from a string view. */
    template <typename CharT>
    explicit Buffer(std::basic_string_view<CharT> src) {
        set(src);
    }

    /** Construct a buffer from a memory region. */
    Buffer(const void* src, std::size_t nb) {
        set(src, nb);
    }

    /** Replace the buffer's contents with the data from a string view. */
    template <typename CharT>
    void set(std::basic_string_view<CharT> src) {
        set(src.data(), src.length() * sizeof(std::basic_string_view<CharT>::char_type));
    }

    /** Replace the buffer's contents with the data from a memory region. */
    void set(const void* src, std::size_t nb) {
        resize(nb);
        std::memcpy(data(), src, nb);
    }

    /** Interpret the buffer's contents as a `std::string`. */
    std::string as_utf8() const {
        const auto c_str = reinterpret_cast<const char*>(data());
        const auto nb = size();
        const auto nch = nb;
        return {c_str, nch};
    }

    /** Interpret the buffer's contents as a `std::wstring`. */
    std::wstring as_utf16() const {
        const auto c_str = reinterpret_cast<const wchar_t*>(data());
        const auto nb = size();
        if (nb % 2 != 0)
            throw std::runtime_error{std::format("Buffer size invalid at {} bytes", nb)};
        const auto nch = nb / 2;
        return {c_str, nch};
    }

    /** Append another buffer to the end of this one. */
    void add(const Buffer& src) {
        const auto nb = size();
        resize(nb + src.size());
        std::memcpy(data() + nb, src.data(), src.size());
    }
};

} // namespace winapi