C++11 library providing functionality common to all adapters.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

53 lines
1.7 KiB

  1. // This file is under GNU General Public License 3.0
  2. // see LICENSE.txt
  3. #ifndef LIBPEPADAPTER_STD_UTILS_HXX
  4. #define LIBPEPADAPTER_STD_UTILS_HXX
  5. #include <sstream>
  6. #include <fstream>
  7. #include <iterator>
  8. namespace pEp {
  9. namespace Utils {
  10. template<typename T>
  11. std::string to_string(const std::vector<T>& v)
  12. {
  13. std::stringstream ss;
  14. for (const T& elem : v) {
  15. ss << elem << std::endl;
  16. }
  17. return ss.str();
  18. }
  19. template<typename T>
  20. std::vector<T> file_read_bin(const std::string &filename)
  21. {
  22. std::vector<T> ret{};
  23. if (pEp::Utils::path_exists(filename)) {
  24. std::ifstream ifs(filename, std::ios_base::binary);
  25. ifs.unsetf(std::ios_base::skipws);
  26. if (ifs.bad()) {
  27. throw std::runtime_error("failed to read file: '" + filename + "'");
  28. }
  29. ret = { std::istream_iterator<T>(ifs), std::istream_iterator<T>() };
  30. } else {
  31. throw std::runtime_error("File does not exist: '" + filename + "'");
  32. }
  33. return ret;
  34. }
  35. template<typename T>
  36. void file_write_bin(const std::string &filename, std::vector<T> &data)
  37. {
  38. std::fstream f(filename, std::ios_base::out | std::ios_base::binary | std::ios_base::trunc);
  39. f.write(data.data(), static_cast<std::streamsize>(data.size()));
  40. if (f.bad()) {
  41. throw std::runtime_error("failed to write file: '" + filename + "'");
  42. }
  43. }
  44. } // namespace Utils
  45. } // namespace pEp
  46. #endif // LIBPEPADAPTER_STD_UTILS_HXX