Example 1: Write and read

  • file format 6
  • Rust SDK 1.0 preview

Needs the Rust SDK

Parse three records, write a pack in memory, open it, read the records back, and save the pack as sample.plxi.

01_write_and_read.rsrust
// Write a pack in memory, open it, and read the records back.
use plxi_sdk::{write, OpenOptions, Pack, Record};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // A record is one JSON object with a string member "k" (its kind).
    let lines = [
        r#"{"k":"rel","src":"e1","tgt":"e2","kind":"knows"}"#,
        r#"{"k":"ent","id":"e2","t":"Person"}"#,
        r#"{"k":"ent","id":"e1","t":"Person","name":"Ada","salience":0.5}"#,
    ];
    let records = lines
        .iter()
        .map(|l| Record::from_json_line(l))
        .collect::<Result<Vec<_>, _>>()?;

    // `write` returns the whole pack as bytes. No file is touched.
    let bytes = write(&records, None)?;

    // Opening verifies the pack by default (digest, header, record count).
    let pack = Pack::from_bytes(bytes, OpenOptions::default())?;
    assert_eq!(pack.record_count(), 3);
    assert!(!pack.has_appendix());

    // Records come back in the format's sort order (entities before
    // relations), spelled the way the writer emits them.
    let out: Vec<String> = pack
        .records()
        .map(|r| r.map(|rec| rec.json_line().to_string()))
        .collect::<Result<_, _>>()?;
    assert_eq!(
        out,
        [
            concat!(
                r#"{"k":"ent","v":1,"id":"e1","t":"Person","#,
                r#""name":"Ada","salience":0.5,"stub":false}"#
            ),
            r#"{"k":"ent","v":1,"id":"e2","t":"Person","stub":false}"#,
            r#"{"k":"rel","v":1,"src":"e1","tgt":"e2","kind":"knows"}"#,
        ]
    );
    for line in &out {
        println!("{line}");
    }
    println!("sha256 = {}", pack.sha256_hex());

    // Keep a copy on disk, for checking with standard tools.
    std::fs::write("sample.plxi", pack.to_bytes())?;
    println!("wrote sample.plxi, {} bytes", pack.to_bytes().len());
    Ok(())
}
Output
{"k":"ent","v":1,"id":"e1","t":"Person","name":"Ada","salience":0.5,"stub":false}
{"k":"ent","v":1,"id":"e2","t":"Person","stub":false}
{"k":"rel","v":1,"src":"e1","tgt":"e2","kind":"knows"}
sha256 = 068f161e337da4b2b0c319a3539b9c62f4b15715d0f3c4de8e1664e5ef66bb28
wrote sample.plxi, 544 bytes

Ran with cargo run --example 01_write_and_read · exit status 0

sample.plxi is the file checked on the no-SDK page. Check a pack with standard tools

Explained in: Rust quickstart

Sections