ostream_wrapper.h 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #ifndef OSTREAM_WRAPPER_H_62B23520_7C8E_11DE_8A39_0800200C9A66
  2. #define OSTREAM_WRAPPER_H_62B23520_7C8E_11DE_8A39_0800200C9A66
  3. #if defined(_MSC_VER) || \
  4. (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \
  5. (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4
  6. #pragma once
  7. #endif
  8. #include <string>
  9. #include <vector>
  10. #include "yaml-cpp/dll.h"
  11. namespace YAML {
  12. class YAML_CPP_API ostream_wrapper {
  13. public:
  14. ostream_wrapper();
  15. explicit ostream_wrapper(std::ostream& stream);
  16. ~ostream_wrapper();
  17. void write(const std::string& str);
  18. void write(const char* str, std::size_t size);
  19. void set_comment() { m_comment = true; }
  20. const char* str() const {
  21. if (m_pStream) {
  22. return 0;
  23. } else {
  24. m_buffer[m_pos] = '\0';
  25. return &m_buffer[0];
  26. }
  27. }
  28. std::size_t row() const { return m_row; }
  29. std::size_t col() const { return m_col; }
  30. std::size_t pos() const { return m_pos; }
  31. bool comment() const { return m_comment; }
  32. private:
  33. void update_pos(char ch);
  34. private:
  35. mutable std::vector<char> m_buffer;
  36. std::ostream* const m_pStream;
  37. std::size_t m_pos;
  38. std::size_t m_row, m_col;
  39. bool m_comment;
  40. };
  41. template <std::size_t N>
  42. inline ostream_wrapper& operator<<(ostream_wrapper& stream,
  43. const char(&str)[N]) {
  44. stream.write(str, N - 1);
  45. return stream;
  46. }
  47. inline ostream_wrapper& operator<<(ostream_wrapper& stream,
  48. const std::string& str) {
  49. stream.write(str);
  50. return stream;
  51. }
  52. inline ostream_wrapper& operator<<(ostream_wrapper& stream, char ch) {
  53. stream.write(&ch, 1);
  54. return stream;
  55. }
  56. }
  57. #endif // OSTREAM_WRAPPER_H_62B23520_7C8E_11DE_8A39_0800200C9A66