]> git.tdb.fi Git - libs/datafile.git/blobdiff - source/textwriter.cpp
Use custom encoding for floats in binary format
[libs/datafile.git] / source / textwriter.cpp
index 890c4172162ea17631d8bc69fad7be8ce3a28788..65f4870ea6e466816ee25d9dd40dbc550d00faa8 100644 (file)
@@ -1,10 +1,3 @@
-/* $Id$
-
-This file is part of libmspdatafile
-Copyright © 2006  Mikko Rasa, Mikkosoft Productions
-Distributed under the LGPL
-*/
-
 #include <msp/io/print.h>
 #include <msp/strings/utils.h>
 #include "statement.h"
@@ -16,9 +9,15 @@ namespace Msp {
 namespace DataFile {
 
 TextWriter::TextWriter(IO::Base &o):
-       WriterMode(o)
+       WriterMode(o),
+       float_format("%#.7g")
 { }
 
+void TextWriter::set_float_precision(unsigned fp)
+{
+       float_format = format("%%#.%dg", fp/4-1);
+}
+
 void TextWriter::write(const Statement &st)
 {
        write_(st, 0);
@@ -29,20 +28,30 @@ void TextWriter::write_(const Statement &st, unsigned level)
        string indent(level, '\t');
 
        IO::print(out, "%s%s", indent, st.keyword);
-       for(ValueArray::const_iterator i=st.args.begin(); i!=st.args.end(); ++i)
+       for(ValueArray::const_iterator i = st.args.begin(); i!=st.args.end(); ++i)
        {
                out.put(' ');
-               if(i->get_type()==STRING)
-                       IO::print(out, "\"%s\"", c_escape(i->get_raw(), false));
-               else if(i->get_type()==BOOLEAN)
-                       out.write(i->get<bool>() ? "true" : "false");
-               else
-                       out.write(i->get_raw());
+               if(i->get_signature()==StringType::signature)
+                       IO::print(out, "\"%s\"", c_escape(i->get<StringType::Store>(), false));
+               else if(i->get_signature()==BoolType::signature)
+                       out.write(i->get<BoolType::Store>() ? "true" : "false");
+               else if(i->get_signature()==IntType::signature)
+                       out.write(lexical_cast(i->get<IntType::Store>()));
+               else if(i->get_signature()==FloatType::signature)
+                       out.write(format(float_format, i->get<FloatType::Store>()));
+               else if(i->get_signature()==SymbolType::signature)
+               {
+                       string name = i->get<SymbolType::Store>().name;
+                       if(isdigit(name[0]))
+                               out.write("\\"+name);
+                       else
+                               out.write(name);
+               }
        }
        if(!st.sub.empty())
        {
                IO::print(out, "\n%s{\n", indent);
-               for(list<Statement>::const_iterator i=st.sub.begin(); i!=st.sub.end(); ++i)
+               for(list<Statement>::const_iterator i = st.sub.begin(); i!=st.sub.end(); ++i)
                        write_(*i, level+1);
                IO::print(out, "%s}", indent);
        }