blob: 87898038d2162c4c3f54e4c556b13dbec03aa871 [file] [log] [blame]
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001//===- EndianStream.h - Stream ops with endian specific data ----*- C++ -*-===//
2//
Andrew Walbran16937d02019-10-22 13:54:20 +01003// 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
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01006//
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/Support/Endian.h"
19#include "llvm/Support/raw_ostream.h"
20
21namespace llvm {
22namespace support {
23
24namespace endian {
Andrew Scullcdfcccc2018-10-05 20:58:37 +010025
26template <typename value_type>
27inline void write(raw_ostream &os, value_type value, endianness endian) {
28 value = byte_swap<value_type>(value, endian);
29 os.write((const char *)&value, sizeof(value_type));
30}
31
32template <>
33inline void write<float>(raw_ostream &os, float value, endianness endian) {
34 write(os, FloatToBits(value), endian);
35}
36
37template <>
38inline void write<double>(raw_ostream &os, double value,
39 endianness endian) {
40 write(os, DoubleToBits(value), endian);
41}
42
43template <typename value_type>
44inline void write(raw_ostream &os, ArrayRef<value_type> vals,
45 endianness endian) {
46 for (value_type v : vals)
47 write(os, v, endian);
48}
49
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010050/// Adapter to write values to a stream in a particular byte order.
Andrew Scullcdfcccc2018-10-05 20:58:37 +010051struct Writer {
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010052 raw_ostream &OS;
Andrew Scullcdfcccc2018-10-05 20:58:37 +010053 endianness Endian;
54 Writer(raw_ostream &OS, endianness Endian) : OS(OS), Endian(Endian) {}
55 template <typename value_type> void write(ArrayRef<value_type> Val) {
56 endian::write(OS, Val, Endian);
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010057 }
58 template <typename value_type> void write(value_type Val) {
Andrew Scullcdfcccc2018-10-05 20:58:37 +010059 endian::write(OS, Val, Endian);
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010060 }
61};
62
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010063} // end namespace endian
64
65} // end namespace support
66} // end namespace llvm
67
68#endif