[Patch] Add array support to EndianStream.

Rafael EspĂ­ndola via llvm-commits llvm-commits at lists.llvm.org
Fri Jan 22 09:32:01 PST 2016


First, thanks for EndianStream. I am using it in an experiment in lld
and it is awesome :-)

It is just missing support for arrays, which the attached patch adds.
Let me know what you think.

Cheers,
Rafael
-------------- next part --------------
diff --git a/include/llvm/Support/EndianStream.h b/include/llvm/Support/EndianStream.h
index d44a9b3..0e7274a 100644
--- a/include/llvm/Support/EndianStream.h
+++ b/include/llvm/Support/EndianStream.h
@@ -26,6 +26,13 @@ namespace endian {
 template <endianness endian> struct Writer {
   raw_ostream &OS;
   Writer(raw_ostream &OS) : OS(OS) {}
+  template <typename value_type, std::size_t N>
+  void write(const value_type (&Vals)[N]) {
+    for (value_type V : Vals) {
+      value_type Swaped = byte_swap<value_type, endian>(V);
+      OS.write((const char *)&Swaped, sizeof(value_type));
+    }
+  }
   template <typename value_type> void write(value_type Val) {
     Val = byte_swap<value_type, endian>(Val);
     OS.write((const char *)&Val, sizeof(value_type));
diff --git a/unittests/Support/EndianStreamTest.cpp b/unittests/Support/EndianStreamTest.cpp
index 6a69be5..ecfc02c 100644
--- a/unittests/Support/EndianStreamTest.cpp
+++ b/unittests/Support/EndianStreamTest.cpp
@@ -153,5 +153,21 @@ TEST(EndianStream, WriteDoubleBE) {
   EXPECT_EQ(static_cast<uint8_t>(data[7]), 0x20);
 }
 
+TEST(EndianStream, WriteVectorLE) {
+  SmallString<16> Data;
+
+  {
+    raw_svector_ostream OS(Data);
+    endian::Writer<little> LE(OS);
+    // FIXME: can we drop the typedef?
+    typedef uint16_t VT[];
+    LE.write(VT{0x1234, 0x5678});
+  }
+
+  EXPECT_EQ(static_cast<uint8_t>(Data[0]), 0x34);
+  EXPECT_EQ(static_cast<uint8_t>(Data[1]), 0x12);
+  EXPECT_EQ(static_cast<uint8_t>(Data[2]), 0x78);
+  EXPECT_EQ(static_cast<uint8_t>(Data[3]), 0x56);
+}
 
 } // end anon namespace


More information about the llvm-commits mailing list