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