transcode.cc 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // Copyright 2019 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include <fstream>
  5. #include <iostream>
  6. #include <sstream>
  7. #include <string>
  8. #include "json.h"
  9. namespace crdtp {
  10. namespace {
  11. int Transcode(const std::string& cmd,
  12. const std::string& input_file_name,
  13. const std::string& output_file_name) {
  14. std::ifstream input_file(input_file_name, std::ios::binary);
  15. if (!input_file.is_open()) {
  16. std::cerr << "failed to open " << input_file_name << "\n";
  17. return 1;
  18. }
  19. std::string in;
  20. while (input_file) {
  21. std::string buffer(1024, '\0');
  22. input_file.read(&buffer.front(), buffer.size());
  23. in += buffer.substr(0, input_file.gcount());
  24. }
  25. Status status;
  26. std::vector<uint8_t> out;
  27. if (cmd == "--json-to-cbor") {
  28. status = json::ConvertJSONToCBOR(SpanFrom(in), &out);
  29. } else if (cmd == "--cbor-to-json") {
  30. status = json::ConvertCBORToJSON(SpanFrom(in), &out);
  31. } else {
  32. std::cerr << "unknown command " << cmd << "\n";
  33. return 1;
  34. }
  35. if (!status.ok()) {
  36. std::cerr << "transcoding error: " << status.ToASCIIString() << "\n";
  37. return 1;
  38. }
  39. std::ofstream output_file(output_file_name, std::ios::binary);
  40. if (!output_file.is_open()) {
  41. std::cerr << "failed to open " << output_file_name << "\n";
  42. return 1;
  43. }
  44. output_file.write(reinterpret_cast<const char*>(out.data()), out.size());
  45. return 0;
  46. }
  47. } // namespace
  48. } // namespace crdtp
  49. int main(int argc, char** argv) {
  50. if (argc == 4)
  51. return ::crdtp::Transcode(argv[1], argv[2], argv[3]);
  52. std::cerr << "usage: " << argv[0]
  53. << " --json-to-cbor <input-file> <output-file>\n"
  54. << " or " << argv[0]
  55. << " --cbor-to-json <input-file> <output-file>\n";
  56. return 1;
  57. }