+#include <limits>
#include <msp/core/maputils.h>
#include "binarywriter.h"
+#include "binfloat.h"
+#include "output.h"
#include "statement.h"
using namespace std;
namespace Msp {
namespace DataFile {
-BinaryWriter::BinaryWriter(IO::Base &o):
+BinaryWriter::BinaryWriter(Output &o):
WriterMode(o),
- next_kwd_id(3),
- next_str_id(1)
+ next_kwd_id(1),
+ next_str_id(1),
+ float_precision(32)
{
- dict[DictEntry("__kwd", "iss")] = 1;
- dict[DictEntry("__str", "is")] = 2;
+ dict[StatementKey("__kwd", "iss")] = -1;
+ dict[StatementKey("__str", "is")] = -2;
+ dict[StatementKey("__flt", "i")] = -3;
+}
+
+void BinaryWriter::set_float_precision(unsigned fp)
+{
+ if(fp<16 || fp>64 || fp%8)
+ throw invalid_argument("BinaryWriter::set_float_precision");
+ float_precision = fp;
+ Statement fst;
+ fst.keyword = "__flt";
+ fst.args.push_back(float_precision);
+ write_(fst);
}
void BinaryWriter::write(const Statement &st)
void BinaryWriter::write_(const Statement &st)
{
- unsigned id = get_item(dict, DictEntry(st.keyword, st.get_signature()));
+ int id = get_item(dict, StatementKey(st.keyword, st.get_signature()));
write_int(id);
for(Statement::Arguments::const_iterator j = st.args.begin(); j!=st.args.end(); ++j)
void BinaryWriter::collect_keywords(const Statement &st)
{
- DictEntry de(st.keyword, st.get_signature());
+ StatementKey key(st.keyword, st.get_signature());
- if(!dict.count(de))
+ if(!dict.count(key))
{
Statement kst;
kst.keyword = "__kwd";
kst.args.push_back(next_kwd_id);
- kst.args.push_back(de.keyword);
- kst.args.push_back(de.args);
+ kst.args.push_back(key.keyword);
+ kst.args.push_back(key.signature);
write_(kst);
- dict[de] = next_kwd_id++;
+ dict[key] = next_kwd_id++;
}
- for(ValueArray::const_iterator i = st.args.begin(); i!=st.args.end(); ++i)
+ for(vector<Value>::const_iterator i = st.args.begin(); i!=st.args.end(); ++i)
{
char sig = i->get_signature();
string str;
else
{
write_int(s.size());
- out.write(s.data(), s.size());
+ out.write(s);
}
}
void BinaryWriter::write_float(FloatType::Store f)
{
- union
+ BinFloat bf;
+
+ if(numeric_limits<FloatType::Store>::is_iec559)
+ bf = BinFloat::explode_iec559(f);
+ else
{
- float v;
- char d[sizeof(float)];
- };
-
- v = f;
-#if BYTE_ORDER == LITTLE_ENDIAN
- for(unsigned i = sizeof(float); i--;)
- out.put(d[i]);
-#else
- for(unsigned i = 0; i<sizeof(float); ++i)
- out.put(d[i]);
-#endif
+ /* The structure of the float is unknown, so we must use arithmetic to
+ reduce it to components. */
+ bf.sign = f<0;
+ bf.exponent = 0;
+ bf.mantissa = 0;
+
+ if(f<0)
+ f = -f;
+ if(!(f+f>f))
+ bf.infinity = true;
+ else if(f!=0)
+ {
+ for(; f<1; f*=2)
+ --bf.exponent;
+ for(; f>=2; f/=2)
+ ++bf.exponent;
+ for(unsigned i=0; i<64; ++i)
+ {
+ bf.mantissa <<= 1;
+ if(f>=1)
+ {
+ bf.mantissa |= 1;
+ f -= 1;
+ }
+ f *= 2;
+ }
+ }
+ }
+
+ UInt64 encoded = bf.compose(float_precision);
+ for(unsigned i=float_precision/8; i--; )
+ out.put((encoded>>(i*8))&0xFF);
}
void BinaryWriter::write_symbol(const SymbolType::Store &s)