jbeder / yaml-cpp

A YAML parser and emitter in C++
MIT License
4.91k stars 1.77k forks source link

`uint8_t` not emit as an integer using YAML::Emitter #1245

Open LudoBike opened 7 months ago

LudoBike commented 7 months ago

Bug description

With yaml-cpp version 0.8.0, when I use YAML::Emitter to emit a uint8_t in a yaml document, the result is different from other integer types. It seems that it is emitted in a quoted hexadecimal representation.

A side effect of this is that a BadConversion exception is thrown when you try to convert a uint8_t emitted with YAML::Emitter.

Might be link with #1081

Reproduction

Test code

#include <yaml-cpp/yaml.h>
#include <iostream>
#include <cstdint>

template<typename Int>
void test(Int integer)
{
  YAML::Emitter out;
  out << integer;
  std::cout << out.c_str() << std::endl;
}

int main()
{
  // Comparison with other interger types
  int8_t int8 {1};
  int16_t int16 {1};
  int32_t int32 {1};
  int64_t int64 {1};

  uint8_t uint8 {16};
  uint16_t uint16 {1};
  uint32_t uint32 {1};
  uint64_t uint64 {1};

  test(int8);
  test(int16);
  test(int32);
  test(int64);
  test(uint8);
  test(uint16);
  test(uint32);
  test(uint64);

  // BadConversion exception
  YAML::Emitter out;
  out << uint8;
  try
  {
    auto test = YAML::Load(out.c_str()).as<uint8_t>();
  }
  catch (const YAML::BadConversion &e)
  {
    std::cout << e.what() << std::endl;
  }

  return 0;
}

Result

With yaml-cpp version 0.8.0

1
1
1
1
"\x10"
1
1
1
yaml-cpp: error at line 1, column 1: bad conversion

Workaround

Do a static cast to another integer type before emitting:

  YAML::Emitter out;
  out << static_cast<unsigned int>(uint8);