On Thursday, 22 October 2015 at 16:15:23 UTC, Shriramana Sharma wrote:
I wanted a D equivalent to: http://doc.qt.io/qt-5/qdatastream.html https://docs.python.org/3/library/pickle.html

and saw that one is under construction: http://wiki.dlang.org/Review/std.serialization

But till it's finalized, I'd just like to have a quick but reliable way to store real and int data types into a binary data file and read therefrom. Is there such a solution? The size of the data is fixed, but especially since I have real values, I'd like to not write to limited fixed decimal text format.

If your only interested in POD data something like this should do the trick.

module pod_encoding;
import std.traits;
import std.stdio;

void encode(T)(string s, T[] t)
   if(!hasIndirections!T && (is(T == struct) || isNumeric!T))
{
   File(s, "wb").rawWrite(t);
}

T[] decode(T)(string s)
   if(!hasIndirections!T && (is(T == struct) || isNumeric!T))
{
  File f = File(s, "rb");
assert(f.size % T.sizeof == 0, "File does not contain array of " ~ T.stringof ~ ".");
  auto size = f.size / U.sizeof;
  auto data = new T[size];
  data      = f.rawRead(data);
  return data;
}

Reply via email to