YAML.cpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. for (unsigned I = 0, N = Scalar.size(); I != N; ++I)
  30. if (!llvm::isHexDigit(Scalar[I]))
  31. return "BinaryRef hex string must contain only hex digits.";
  32. Val = yaml::BinaryRef(Scalar);
  33. return {};
  34. }
  35. void yaml::BinaryRef::writeAsBinary(raw_ostream &OS, uint64_t N) const {
  36. if (!DataIsHexString) {
  37. OS.write((const char *)Data.data(), std::min<uint64_t>(N, Data.size()));
  38. return;
  39. }
  40. for (uint64_t I = 0, E = std::min<uint64_t>(N, Data.size() / 2); I != E;
  41. ++I) {
  42. uint8_t Byte = llvm::hexDigitValue(Data[I * 2]);
  43. Byte <<= 4;
  44. Byte |= llvm::hexDigitValue(Data[I * 2 + 1]);
  45. OS.write(Byte);
  46. }
  47. }
  48. void yaml::BinaryRef::writeAsHex(raw_ostream &OS) const {
  49. if (binary_size() == 0)
  50. return;
  51. if (DataIsHexString) {
  52. OS.write((const char *)Data.data(), Data.size());
  53. return;
  54. }
  55. for (uint8_t Byte : Data)
  56. OS << hexdigit(Byte >> 4) << hexdigit(Byte & 0xf);
  57. }