GCB: GreyCat Binary serialization

GreyCat provides data serialization to and from a file, in a binary format. This can be useful for exchanging information between a GreyCat backend and a web frontend, or an external program (with the GreyCat SDK).

One caveat is that the parties exchanging GCB files must belong to the same project (must share type information).

GcbWriter and GcbReader are available through the io module.

Writing to a GCB file

Serializing data is straightforward with the GcbWriter type.

use io;

fn main() {
  var writer = GcbWriter::new("test.gcb");
  writer.write([42, "hello world!", 37.5]);
}

The alternative GcbWriter::new_append() is similar but appends to the file if it exists.

Reading a GCB file

Deserializing from the binary data file is similar.

use io;

fn main() {
  var reader = GcbReader::new("test.gcb");
  var v = reader.read();
}

GcbReader supports additional methods (which are often found in other IO types).

use io;

fn main() {
  var w = GcbWriter::new("test.gcb");
  w.write(12);
  w.write("twelve");
  w = null;  // closes the writer, saves to disk (needed here because we read in same 'fn')

  var r = GcbReader::new("test.gcb");
  var v : any?;
  var p : int;
  while (r.available() > 0) {
    v = r.read();
    p = r.get_pos();
    println("at ${p}, found: ${v}");
  }
}

Displays:

at 2, found: 12
at 5, found: twelve