winapi_common
buffer.hpp
1 // Copyright (c) 2020 Egor Tensin <Egor.Tensin@gmail.com>
2 // This file is part of the "winapi-common" project.
3 // For details, see https://github.com/egor-tensin/winapi-common.
4 // Distributed under the MIT License.
5 
6 #pragma once
7 
8 #include <cstddef>
9 #include <cstring>
10 #include <initializer_list>
11 #include <sstream>
12 #include <stdexcept>
13 #include <string>
14 #include <utility>
15 #include <vector>
16 
17 namespace winapi {
18 
24 class Buffer : public std::vector<unsigned char> {
25 public:
26  typedef std::vector<unsigned char> Parent;
27 
28  Buffer() = default;
29 
31  Buffer(std::initializer_list<unsigned char> lst) : Parent{lst} {}
32 
34  explicit Buffer(Parent&& src) : Parent{std::move(src)} {}
35 
37  template <typename CharT>
38  explicit Buffer(const std::basic_string<CharT>& src) {
39  set(src);
40  }
41 
43  Buffer(const void* src, std::size_t nb) { set(src, nb); }
44 
46  template <typename CharT>
47  void set(const std::basic_string<CharT>& src) {
48  set(src.c_str(), src.length() * sizeof(std::basic_string<CharT>::char_type));
49  }
50 
52  void set(const void* src, std::size_t nb) {
53  resize(nb);
54  std::memcpy(data(), src, nb);
55  }
56 
58  std::string as_utf8() const {
59  const auto c_str = reinterpret_cast<const char*>(data());
60  const auto nb = size();
61  const auto nch = nb;
62  return {c_str, nch};
63  }
64 
66  std::wstring as_utf16() const {
67  const auto c_str = reinterpret_cast<const wchar_t*>(data());
68  const auto nb = size();
69  if (nb % 2 != 0) {
70  std::ostringstream oss;
71  oss << "Buffer size invalid at " << nb << " bytes";
72  throw std::runtime_error{oss.str()};
73  }
74  const auto nch = nb / 2;
75  return {c_str, nch};
76  }
77 
79  void add(const Buffer& src) {
80  const auto nb = size();
81  resize(nb + src.size());
82  std::memcpy(data() + nb, src.data(), src.size());
83  }
84 };
85 
86 } // namespace winapi
Binary data container.
Definition: buffer.hpp:24
void set(const std::basic_string< CharT > &src)
Definition: buffer.hpp:47
void add(const Buffer &src)
Definition: buffer.hpp:79
Buffer(Parent &&src)
Definition: buffer.hpp:34
Buffer(const std::basic_string< CharT > &src)
Definition: buffer.hpp:38
void set(const void *src, std::size_t nb)
Definition: buffer.hpp:52
Buffer(const void *src, std::size_t nb)
Definition: buffer.hpp:43
Buffer(std::initializer_list< unsigned char > lst)
Definition: buffer.hpp:31
std::wstring as_utf16() const
Definition: buffer.hpp:66
std::string as_utf8() const
Definition: buffer.hpp:58