Is the enhancement spirit a good fit for this situation?

I have a situation where I am trying to create an HDF connection type from a stream of name-value pairs (for simplicity, we say that the value can be either a double or a string character). To be clear, numeric data is already binary - this is not a string. Names provide structural information (is this part of the array?), Is this part a nested composite type?).

I imagine creating a token vector using name information to insert tokens (for example, '[' and ']' to delimit an array, '{' and '}' to delimit nested connections), but use values ​​otherwise. It is not clear to me from the documentation if Spirit binary parsers would be a suitable choice for handling numerical values.

+4
source share
1 answer

I can’t judge if the “rest” (ie not binary data) justifies switching to a PEG parser generator.

However, to give you something to start with:

Use

  • qi::bin_float, qi::little_bin_floatorqi::big_bin_float
  • qi::bin_double, qi::little_bin_doubleorqi::big_bin_double

Here's an example program with 17 lines that exactly duplicates behavior

od -w8 -A none -t f8 -v input.dat

in my field:

#include <boost/spirit/include/qi.hpp>
#include <fstream>
#include <iomanip>

namespace qi = boost::spirit::qi;

int main() {
    using namespace std;
    // read file
    ifstream ifs("input.dat", ios::binary);
    string const input { istreambuf_iterator<char>(ifs), {} };

    // parse
    vector<double> result;
    bool ret = qi::parse(begin(input), end(input), *qi::bin_double, result);

    // print
    if (ret) for (auto v : result) 
        cout << setw(28) << setprecision(16) << right << v << "\n";
}

Live on Coliru


:

clang++ -Os -std=c++11 -Wall -pedantic main.cpp          # compile
dd if=/dev/urandom count=32 bs=1 2>/dev/null > input.dat # generate input
./a.out                                               # spirit demo
echo 'And `od` output:'                        
od -w8 -A none -t f8 -v /tmp/input.dat                  # compare to `od` 

. , , Spirit .

+1

All Articles