]> git.tdb.fi Git - libs/datafile.git/blob - tool/tool.cpp
Use custom encoding for floats in binary format
[libs/datafile.git] / tool / tool.cpp
1 #include <msp/core/getopt.h>
2 #include <msp/io/buffered.h>
3 #include <msp/io/console.h>
4 #include <msp/io/file.h>
5 #include <msp/datafile/parser.h>
6 #include <msp/datafile/statement.h>
7 #include <msp/datafile/writer.h>
8 #include "compiler.h"
9 #include "tool.h"
10
11 using namespace std;
12 using namespace Msp;
13
14 DataTool::DataTool(int argc, char **argv):
15         in_fn("-"),
16         out_fn("-"),
17         binary(false),
18         compile(false),
19         float_size(0)
20 {
21         GetOpt getopt;
22         getopt.add_option('b', "binary", binary, GetOpt::NO_ARG);
23         getopt.add_option('c', "compile", compile, GetOpt::NO_ARG);
24         getopt.add_option('f', "float-size", float_size, GetOpt::REQUIRED_ARG);
25         getopt.add_option('o', "output", out_fn, GetOpt::REQUIRED_ARG);
26         getopt(argc, argv);
27
28         const vector<string> &args = getopt.get_args();
29         if(!args.empty())
30                 in_fn = args[0];
31 }
32
33 int DataTool::main()
34 {
35         IO::Base *in;
36         if(in_fn=="-")
37                 in = &IO::cin;
38         else
39                 in = new IO::File(in_fn);
40
41         IO::Base *out;
42         if(out_fn=="-")
43                 out = &IO::cout;
44         else
45                 out = new IO::File(out_fn, IO::M_WRITE);
46
47         {
48                 IO::Buffered in_buf(*in);
49                 DataFile::Parser parser(in_buf, in_fn);
50                 IO::Buffered out_buf(*out);
51                 DataFile::Writer writer(out_buf);
52                 if(binary)
53                         writer.set_binary(true);
54                 if(float_size)
55                         writer.set_float_precision(float_size);
56
57                 if(compile)
58                 {
59                         Compiler compiler(writer);
60                         compiler.load(parser);
61                 }
62                 else
63                 {
64                         while(parser)
65                         {
66                                 DataFile::Statement st = parser.parse();
67                                 if(st.valid)
68                                 {
69                                         writer.write(st);
70                                         out_buf.flush();
71                                 }
72                         }
73                 }
74         }
75
76         if(in!=&IO::cin)
77                 delete in;
78         if(out!=&IO::cout)
79                 delete out;
80
81         return 0;
82 }