blob: 9742e253ad3e1e8f3b90a5cd1a4ad1aa98d412f1 [file] [log] [blame]
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001//===- EndianStream.h - Stream ops with endian specific data ----*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines utilities for operating on streams that have endian
11// specific data.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_SUPPORT_ENDIANSTREAM_H
16#define LLVM_SUPPORT_ENDIANSTREAM_H
17
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/Support/Endian.h"
20#include "llvm/Support/raw_ostream.h"
21
22namespace llvm {
23namespace support {
24
25namespace endian {
Andrew Scullcdfcccc2018-10-05 20:58:37 +010026
27template <typename value_type>
28inline void write(raw_ostream &os, value_type value, endianness endian) {
29 value = byte_swap<value_type>(value, endian);
30 os.write((const char *)&value, sizeof(value_type));
31}
32
33template <>
34inline void write<float>(raw_ostream &os, float value, endianness endian) {
35 write(os, FloatToBits(value), endian);
36}
37
38template <>
39inline void write<double>(raw_ostream &os, double value,
40 endianness endian) {
41 write(os, DoubleToBits(value), endian);
42}
43
44template <typename value_type>
45inline void write(raw_ostream &os, ArrayRef<value_type> vals,
46 endianness endian) {
47 for (value_type v : vals)
48 write(os, v, endian);
49}
50
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010051/// Adapter to write values to a stream in a particular byte order.
Andrew Scullcdfcccc2018-10-05 20:58:37 +010052struct Writer {
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010053 raw_ostream &OS;
Andrew Scullcdfcccc2018-10-05 20:58:37 +010054 endianness Endian;
55 Writer(raw_ostream &OS, endianness Endian) : OS(OS), Endian(Endian) {}
56 template <typename value_type> void write(ArrayRef<value_type> Val) {
57 endian::write(OS, Val, Endian);
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010058 }
59 template <typename value_type> void write(value_type Val) {
Andrew Scullcdfcccc2018-10-05 20:58:37 +010060 endian::write(OS, Val, Endian);
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010061 }
62};
63
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010064} // end namespace endian
65
66} // end namespace support
67} // end namespace llvm
68
69#endif