YAML.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. //===- YAML.cpp - YAMLIO utilities for object files -----------------------===//
  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 utility classes for handling the YAML representation of
  10. // object files.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/ObjectYAML/YAML.h"
  14. #include "llvm/ADT/StringExtras.h"
  15. #include "llvm/Support/raw_ostream.h"
  16. #include <cctype>
  17. #include <cstdint>
  18. using namespace llvm;
  19. void yaml::ScalarTraits<yaml::BinaryRef>::output(
  20. const yaml::BinaryRef &Val, void *, raw_ostream &Out) {
  21. Val.writeAsHex(Out);
  22. }
  23. StringRef yaml::ScalarTraits<yaml::BinaryRef>::input(StringRef Scalar, void *,
  24. yaml::BinaryRef &Val) {
  25. if (Scalar.size() % 2 != 0)
  26. return "BinaryRef hex string must contain an even number of nybbles.";
  27. // TODO: Can we improve YAMLIO to permit a more accurate diagnostic here?
  28. // (e.g. a caret pointing to the offending character).
  29. if (!llvm::all_of(Scalar, llvm::isHexDigit))
  30. return "BinaryRef hex string must contain only hex digits.";
  31. Val = yaml::BinaryRef(Scalar);
  32. return {};
  33. }
  34. void yaml::BinaryRef::writeAsBinary(raw_ostream &OS, uint64_t N) const {
  35. if (!DataIsHexString) {
  36. OS.write((const char *)Data.data(), std::min<uint64_t>(N, Data.size()));
  37. return;
  38. }
  39. for (uint64_t I = 0, E = std::min<uint64_t>(N, Data.size() / 2); I != E;
  40. ++I) {
  41. uint8_t Byte = llvm::hexDigitValue(Data[I * 2]);
  42. Byte <<= 4;
  43. Byte |= llvm::hexDigitValue(Data[I * 2 + 1]);
  44. OS.write(Byte);
  45. }
  46. }
  47. void yaml::BinaryRef::writeAsHex(raw_ostream &OS) const {
  48. if (binary_size() == 0)
  49. return;
  50. if (DataIsHexString) {
  51. OS.write((const char *)Data.data(), Data.size());
  52. return;
  53. }
  54. for (uint8_t Byte : Data)
  55. OS << hexdigit(Byte >> 4) << hexdigit(Byte & 0xf);
  56. }