Skip to content

Instantly share code, notes, and snippets.

@dongyuwei
Last active May 15, 2019 09:22
Show Gist options
  • Save dongyuwei/21fd7c4e843beae7f70224dd10a4085d to your computer and use it in GitHub Desktop.
Save dongyuwei/21fd7c4e843beae7f70224dd10a4085d to your computer and use it in GitHub Desktop.
flatbuffer for english dictionary

flatbuffer Scheme: dictionary.fbs

table Word {
  frequency:long;
  ipa:string;
  translation:[string];
}


table Dictionary {
    keys:[string];
    values:[Word];
}

root_type Dictionary;

json data: dictionary.json

{
  "keys": ["downbeat"],
  "values": [
    {
      "frequency": 236548,
      "translation": [
        "n. 下拍(乐队指挥向下的手势);停滞",
        "adj. 忧郁的;悲观的;不强烈的"
      ],
      "ipa": "daʊnˈbit"
    }
  ]
}

generate js code and binary data from scheme and json text:

cd flatbuffers/samples && ../Debug/flatc --js dictionary.fbs --binary dictionary.json

@dongyuwei
Copy link
Author

deserialize binary file and get the dictionary data :samplebinary2.js

var assert = require("assert");
var flatbuffers = require("../js/flatbuffers").flatbuffers;
var { Dictionary, Word } = require("./dictionary_generated.js");
var fs = require("fs");

function main() {
  var data = new Uint8Array(fs.readFileSync("./dictionary.bin"));
  var buf = new flatbuffers.ByteBuffer(data);

  var dict = Dictionary.getRootAsDictionary(buf);
  console.log("dict.keysLength", dict.keysLength());
  var word = dict.values(0);
  console.log(
    "word",
    word.ipa(),
    word.translationLength(),
    word.translation(0),
    word.translation(1)
  );

  console.log("dict.valuesLength", dict.valuesLength());
  console.log("The FlatBuffer was successfully created and verified!");
}

main();

@dongyuwei
Copy link
Author

flatc -b myschema.fbs mydata.json
This will generate the binary file mydata_wire.bin which can be loaded as before.
https://github.com/google/flatbuffers/blob/master/docs/source/CppUsage.md

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment