Note that there are some explanatory texts on larger screens.

plurals
  1. POTiny serializer
    text
    copied!<p>I have a family of classes that contain only variables of the following types: std::string, int, double. I should be able to serialize/deserialize objects of these classes to/from C string (null terminated). I don't want to use some 3rdparty serializer and do not want to write full-featured serializer by myself. I will serialize/deserialize only once in my code.</p> <p>So, how to write very very tiny and yet elegant serializer and do it pretty fast?</p> <p>UPDATE</p> <p>I've written and tested my own. Maybe it will be useful for someone. If you notice some bugs or have some suggestions how to make it better, let me know. Here it is:</p> <pre><code> typedef std::ostringstream ostr; typedef std::istringstream istr; const char delimiter = '\n'; const int doublePrecision = 15; void Save(ostr&amp; os, int x) { os &lt;&lt; x &lt;&lt; delimiter; } void Save(ostr&amp; os, double x) { os.precision(doublePrecision); os &lt;&lt; x &lt;&lt; delimiter; } void Save(ostr&amp; os, const std::string&amp; x) { os &lt;&lt; x &lt;&lt; delimiter; } void Load(istr&amp; is, int&amp; x) { is &gt;&gt; x; is.rdbuf()-&gt;sbumpc(); // get rid of delimiter } void Load(istr&amp; is, double&amp; x) { is &gt;&gt; x; is.rdbuf()-&gt;sbumpc(); // get rid of delimiter } void Load(istr&amp; is, std::string&amp; x) { getline(is, x, delimiter); } </code></pre> <p>Test:</p> <pre><code> std::string a = "Test string 1 2 and 2.33"; std::string b = "45"; double c = 45.7; int d = 58; double e = 1.0/2048; std::ostringstream os; Save(os, a); Save(os, b); Save(os, c); Save(os, d); Save(os, e); std::string serialized = os.str(); std::string aa; std::string bb; double cc = 0.0; int dd = 0; double ee = 0.0; std::istringstream is(serialized); Load(is, aa); Load(is, bb); Load(is, cc); Load(is, dd); Load(is, ee); ASSERT(a == aa); ASSERT(b == bb); ASSERT(c == cc); ASSERT(d == dd); ASSERT(e == ee); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload