Skip to content

Commit

Permalink
Added ostream hex support for DynamicArrayOf
Browse files Browse the repository at this point in the history
  • Loading branch information
arBmind committed May 29, 2024
1 parent 651cdd0 commit 7b96f6b
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 1 deletion.
27 changes: 27 additions & 0 deletions src/array19.lib/array19/DynamicArrayOf.AsHex.ostream.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
#pragma once
#include "DynamicArrayOf.h"

#include <iomanip>
#include <ostream>

namespace array19 {

template<class T> struct AsHex {
const DynamicArrayOf<T>& a;

template<class Chr, class Traits>
friend auto operator<<(std::basic_ostream<Chr, Traits>& out, AsHex<T>&& a) -> decltype(out)& {
out << "[";
bool first = true;
for (auto& v : a.a) {
if (first)
first = false;
else
out << ", ";
out << std::setfill('0') << std::setw(sizeof(T) * 2) << std::hex << std::internal << +v;
}
return out << std::dec << "]";
}
};

} // namespace array19
21 changes: 20 additions & 1 deletion src/array19.lib/array19/DynamicArrayOf.test.cpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#include "DynamicArrayOf.h"

#include "Array.h"
#include "DynamicArrayOf.AsHex.ostream.h"
#include "DynamicArrayOf.equals.h"
#include "DynamicArrayOf.ostream.h"
#include "SliceOf.carray.h"
Expand Down Expand Up @@ -151,7 +152,7 @@ struct Vec3 {
bool operator==(const Vec3&) const = default;

[[maybe_unused]] friend auto operator<<(std::ostream& o, const Vec3& v) -> std::ostream& {
return o << "x:" << v.x << ", y:" << v.y << ", z:" << v.z;
return o << "{x:" << v.x << ", y:" << v.y << ", z:" << v.z << '}';
}
};

Expand All @@ -165,6 +166,24 @@ TEST(DynamicArrayOf, EmplaceStruct) {
EXPECT_EQ(v, v2);
}

TEST(DynamicArrayOf, Ostream) {
auto s = std::stringstream{};
s << DynamicArrayOf{10, 11, 16};
EXPECT_EQ(s.str(), "[10, 11, 16]");
}

TEST(DynamicArrayOf, OstreamStruct) {
auto s = std::stringstream{};
s << DynamicArrayOf{Vec3{1.1, 2.2, 3.3}, Vec3{10, 11, 16}};
EXPECT_EQ(s.str(), "[{x:1.1, y:2.2, z:3.3}, {x:10, y:11, z:16}]");
}

TEST(DynamicArrayOf, OstreamAsHex) {
auto s = std::stringstream{};
s << AsHex{DynamicArrayOf<uint8_t>{uint8_t{10}, uint8_t{11}, uint8_t{16}}};
EXPECT_EQ(s.str(), "[0a, 0b, 10]");
}

namespace {

struct Recorder {
Expand Down
1 change: 1 addition & 0 deletions src/array19.lib/array19/array19.qbs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ Product {
"AllocatedArrayUtils.h",
"Array.h",
"Array.ostream.h",
"DynamicArrayOf.AsHex.ostream.h",
"DynamicArrayOf.equals.h",
"DynamicArrayOf.h",
"DynamicArrayOf.ostream.h",
Expand Down

0 comments on commit 7b96f6b

Please sign in to comment.