Pass a unique_ptr<MemoryBuffer> to the constructors in the Binary hierarchy.
[oota-llvm.git] / lib / Object / YAML.cpp
1 //===- YAML.cpp - YAMLIO utilities for object files -----------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines utility classes for handling the YAML representation of
11 // object files.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/Object/YAML.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/Support/raw_ostream.h"
18 #include <cctype>
19
20 using namespace llvm;
21 using namespace object::yaml;
22
23 void yaml::ScalarTraits<object::yaml::BinaryRef>::output(
24     const object::yaml::BinaryRef &Val, void *, llvm::raw_ostream &Out) {
25   Val.writeAsHex(Out);
26 }
27
28 StringRef yaml::ScalarTraits<object::yaml::BinaryRef>::input(
29     StringRef Scalar, void *, object::yaml::BinaryRef &Val) {
30   if (Scalar.size() % 2 != 0)
31     return "BinaryRef hex string must contain an even number of nybbles.";
32   // TODO: Can we improve YAMLIO to permit a more accurate diagnostic here?
33   // (e.g. a caret pointing to the offending character).
34   for (unsigned I = 0, N = Scalar.size(); I != N; ++I)
35     if (!isxdigit(Scalar[I]))
36       return "BinaryRef hex string must contain only hex digits.";
37   Val = object::yaml::BinaryRef(Scalar);
38   return StringRef();
39 }
40
41 void BinaryRef::writeAsBinary(raw_ostream &OS) const {
42   if (!DataIsHexString) {
43     OS.write((const char *)Data.data(), Data.size());
44     return;
45   }
46   for (unsigned I = 0, N = Data.size(); I != N; I += 2) {
47     uint8_t Byte;
48     StringRef((const char *)&Data[I],  2).getAsInteger(16, Byte);
49     OS.write(Byte);
50   }
51 }
52
53 void BinaryRef::writeAsHex(raw_ostream &OS) const {
54   if (binary_size() == 0)
55     return;
56   if (DataIsHexString) {
57     OS.write((const char *)Data.data(), Data.size());
58     return;
59   }
60   for (ArrayRef<uint8_t>::iterator I = Data.begin(), E = Data.end(); I != E;
61        ++I) {
62     uint8_t Byte = *I;
63     OS << hexdigit(Byte >> 4);
64     OS << hexdigit(Byte & 0xf);
65   }
66 }