benc2json.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /* vim: set expandtab ts=4 sw=4: */
  2. /*
  3. * You may redistribute this program and/or modify it under the terms of
  4. * the GNU General Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. *
  7. * This program is distributed in the hope that it will be useful,
  8. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. * GNU General Public License for more details.
  11. *
  12. * You should have received a copy of the GNU General Public License
  13. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. #define string_strcmp
  16. #include "benc/Dict.h"
  17. #include "benc/serialization/BencSerializer.h"
  18. #include "benc/serialization/json/JsonBencSerializer.h"
  19. #include "benc/serialization/standard/StandardBencSerializer.h"
  20. #include "memory/MallocAllocator.h"
  21. #include "io/Reader.h"
  22. #include "io/FileReader.h"
  23. #include "io/Writer.h"
  24. #include "io/FileWriter.h"
  25. #include "util/platform/libc/string.h"
  26. #include <unistd.h>
  27. int main(int argc, char** argv)
  28. {
  29. if (isatty(STDIN_FILENO)) {
  30. printf("Usage: %s < input.benc > output.json\n", argv[0]);
  31. printf("Or: %s -r < input.json > output.benc\n", argv[0]);
  32. exit(0);
  33. }
  34. struct Allocator* allocator = MallocAllocator_new(1<<20);
  35. const struct BencSerializer* parser = StandardBencSerializer_get();
  36. const struct BencSerializer* serializer = JsonBencSerializer_get();
  37. if (argc > 1 && !strcmp(argv[1], "-r")) {
  38. const struct BencSerializer* p = parser;
  39. parser = serializer;
  40. serializer = p;
  41. }
  42. struct Reader* stdinReader = FileReader_new(stdin, allocator);
  43. Dict config;
  44. if (parser->parseDictionary(stdinReader, allocator, &config)) {
  45. fprintf(stderr, "Failed to parse configuration.\n");
  46. return -1;
  47. }
  48. struct Writer* stdoutWriter = FileWriter_new(stdout, allocator);
  49. serializer->serializeDictionary(stdoutWriter, &config);
  50. printf("\n");
  51. Allocator_free(allocator);
  52. }