2 * Copyright (C) 2016 Thomas Voss <thomas.voss.bochum@gmail.com>
3 * Simon Fels <morphis@gravedo.de>
5 * This program is free software: you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 3, as published
7 * by the Free Software Foundation.
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranties of
11 * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
12 * PURPOSE. See the GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License along
15 * with this program. If not, see <http://www.gnu.org/licenses/>.
19 #include "anbox/common/binary_writer.h"
24 #include <boost/endian/buffers.hpp>
25 #include <boost/endian/conversion.hpp>
28 bool is_little_endian() {
29 static const std::uint32_t v = 1;
30 return (*reinterpret_cast<const std::uint8_t*>(&v) == 1);
37 BinaryWriter::BinaryWriter(std::vector<std::uint8_t>::iterator begin,
38 std::vector<std::uint8_t>::iterator end) :
39 begin_{begin}, current_{begin}, end_{end},
40 byte_order_{is_little_endian() ? Order::Little : Order::Big} {}
42 void BinaryWriter::set_byte_order(Order order) {
46 void BinaryWriter::write_uint16(std::uint16_t value) {
47 if (current_ + sizeof(value) > end_)
48 throw std::out_of_range{"Write buffer exhausted"};
50 std::uint16_t v = value;
51 switch (byte_order_) {
53 v = boost::endian::native_to_big(value);
56 v = boost::endian::native_to_little(value);
62 memcpy(&(*current_), &v, sizeof(std::uint16_t));
63 current_ += sizeof(v);
66 void BinaryWriter::write_uint32(std::uint32_t value) {
67 if (current_ + sizeof(value) > end_)
68 throw std::out_of_range{"Write buffer exhausted"};
70 std::uint32_t v = value;
71 switch (byte_order_) {
73 v = boost::endian::native_to_big(value);
76 v = boost::endian::native_to_little(value);
81 memcpy(&(*current_), &v, sizeof(std::uint32_t));
82 current_ += sizeof(v);
85 void BinaryWriter::write_string(const char *s, std::size_t size) {
86 if (current_ + size > end_)
87 throw std::out_of_range{"Write buffer exhausted"};
89 memcpy(&(*current_), s, size);
93 void BinaryWriter::write_string_with_size(const std::string &str) {
94 write_string_with_size(str.c_str(), str.length());
97 void BinaryWriter::write_string_with_size(const char *s, std::size_t size) {
99 write_string(s, size);
102 std::size_t BinaryWriter::bytes_written() const {
103 return current_ - begin_;
105 } // namespace common