1 //===- EndianStream.h - Stream ops with endian specific data ----*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines utilities for operating on streams that have endian
10 // specific data.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_SUPPORT_ENDIANSTREAM_H
15 #define LLVM_SUPPORT_ENDIANSTREAM_H
16 
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/Support/Endian.h"
20 #include "llvm/Support/MathExtras.h"
21 #include "llvm/Support/raw_ostream.h"
22 
23 namespace llvm {
24 namespace support {
25 
26 namespace endian {
27 
28 template <typename value_type>
29 inline void write(raw_ostream &os, value_type value, endianness endian) {
30   value = byte_swap<value_type>(value, endian);
31   os.write((const char *)&value, sizeof(value_type));
32 }
33 
34 template <>
35 inline void write<float>(raw_ostream &os, float value, endianness endian) {
36   write(os, llvm::bit_cast<uint32_t>(value), endian);
37 }
38 
39 template <>
40 inline void write<double>(raw_ostream &os, double value,
41                           endianness endian) {
42   write(os, llvm::bit_cast<uint64_t>(value), endian);
43 }
44 
45 template <typename value_type>
46 inline void write(raw_ostream &os, ArrayRef<value_type> vals,
47                   endianness endian) {
48   for (value_type v : vals)
49     write(os, v, endian);
50 }
51 
52 template <typename value_type>
53 inline void write(SmallVectorImpl<char> &Out, value_type V, endianness E) {
54   V = byte_swap<value_type>(V, E);
55   Out.append((const char *)&V, (const char *)&V + sizeof(value_type));
56 }
57 
58 /// Adapter to write values to a stream in a particular byte order.
59 struct Writer {
60   raw_ostream &OS;
61   endianness Endian;
62   Writer(raw_ostream &OS, endianness Endian) : OS(OS), Endian(Endian) {}
63   template <typename value_type> void write(ArrayRef<value_type> Val) {
64     endian::write(OS, Val, Endian);
65   }
66   template <typename value_type> void write(value_type Val) {
67     endian::write(OS, Val, Endian);
68   }
69 };
70 
71 } // end namespace endian
72 
73 } // end namespace support
74 } // end namespace llvm
75 
76 #endif
77