use std::path::Path;
use crate::error::{IrError, Result};
use crate::ir::MoonIr;
pub const MOON_IR_FILENAME: &str = "contract.mpir";
pub const SUPPORTED_SCHEMA_VERSION: u32 = 3;
pub const MIN_SCHEMA_VERSION: u32 = 1;
pub fn from_cbor_slice(bytes: &[u8]) -> Result<MoonIr> {
let ir = crate::cbor_fast::decode_runtime_ir_slice(bytes)?;
check_schema_version(&ir)?;
Ok(ir)
}
#[must_use]
pub fn to_cbor_vec(ir: &MoonIr) -> Vec<u8> {
crate::cbor_fast::encode_runtime_ir_vec(ir)
}
pub fn write_cbor(ir: &MoonIr, out: &mut Vec<u8>) {
crate::cbor_fast::encode_runtime_ir_into(ir, out);
}
pub fn from_path(path: impl AsRef<Path>) -> Result<MoonIr> {
let bytes = std::fs::read(path.as_ref())?;
from_cbor_slice(&bytes)
}
fn check_schema_version(ir: &MoonIr) -> Result<()> {
if (MIN_SCHEMA_VERSION..=SUPPORTED_SCHEMA_VERSION).contains(&ir.schema_version) {
Ok(())
} else {
Err(IrError::UnsupportedSchemaVersion {
actual: ir.schema_version,
supported: SUPPORTED_SCHEMA_VERSION,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
fn ir_with_version(v: u32) -> MoonIr {
let mut ir: MoonIr = serde_json::from_str(
r#"{"schema-version":1,"compiler-version":"x","language-version":"x",
"runtime-version":"x","constructor":{"arguments":[],"initial-state":
{"kind":"null"},"init-ops":[],"register-operations":[],
"body":{"stmt":"seq","items":[]}}}"#,
)
.expect("fixture parses");
ir.schema_version = v;
ir
}
#[test]
fn accepts_every_released_schema_version() {
for v in MIN_SCHEMA_VERSION..=SUPPORTED_SCHEMA_VERSION {
assert!(
check_schema_version(&ir_with_version(v)).is_ok(),
"schema {v} must stay readable"
);
}
}
#[test]
fn rejects_a_newer_schema_than_this_build_knows() {
let err = check_schema_version(&ir_with_version(SUPPORTED_SCHEMA_VERSION + 1));
assert!(err.is_err(), "a future schema must not be read as if known");
}
}