EndianStream.h 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- EndianStream.h - Stream ops with endian specific data ----*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This file defines utilities for operating on streams that have endian
  15. // specific data.
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #ifndef LLVM_SUPPORT_ENDIANSTREAM_H
  19. #define LLVM_SUPPORT_ENDIANSTREAM_H
  20. #include "llvm/ADT/ArrayRef.h"
  21. #include "llvm/Support/Endian.h"
  22. #include "llvm/Support/MathExtras.h"
  23. #include "llvm/Support/raw_ostream.h"
  24. namespace llvm {
  25. namespace support {
  26. namespace endian {
  27. template <typename value_type>
  28. inline 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. template <>
  33. inline void write<float>(raw_ostream &os, float value, endianness endian) {
  34. write(os, FloatToBits(value), endian);
  35. }
  36. template <>
  37. inline void write<double>(raw_ostream &os, double value,
  38. endianness endian) {
  39. write(os, DoubleToBits(value), endian);
  40. }
  41. template <typename value_type>
  42. inline void write(raw_ostream &os, ArrayRef<value_type> vals,
  43. endianness endian) {
  44. for (value_type v : vals)
  45. write(os, v, endian);
  46. }
  47. /// Adapter to write values to a stream in a particular byte order.
  48. struct Writer {
  49. raw_ostream &OS;
  50. endianness Endian;
  51. Writer(raw_ostream &OS, endianness Endian) : OS(OS), Endian(Endian) {}
  52. template <typename value_type> void write(ArrayRef<value_type> Val) {
  53. endian::write(OS, Val, Endian);
  54. }
  55. template <typename value_type> void write(value_type Val) {
  56. endian::write(OS, Val, Endian);
  57. }
  58. };
  59. } // end namespace endian
  60. } // end namespace support
  61. } // end namespace llvm
  62. #endif
  63. #ifdef __GNUC__
  64. #pragma GCC diagnostic pop
  65. #endif