Skip to content

Instantly share code, notes, and snippets.

@hexfusion
Created October 16, 2023 22:48
Show Gist options
  • Save hexfusion/a05d725044e36e758576588b0fe000c9 to your computer and use it in GitHub Desktop.
Save hexfusion/a05d725044e36e758576588b0fe000c9 to your computer and use it in GitHub Desktop.
extern crate serde;
extern crate serde_yaml;
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize, PartialEq)]
struct Config {
max_memory_pages: u32,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
struct Step<'a> {
task: &'a str,
description: &'a str,
#[serde(default)]
request: Option<Request<'a>>,
#[serde(default)]
require: Option<Require>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
struct Request<'a> {
method: &'a str,
params: Vec<Param<'a>>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
struct Param<'a> {
name: &'a str,
#[serde(rename = "type")]
param_type: &'a str,
value: &'a str,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
struct Require {
result: ResultCondition,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
struct ResultCondition {
operator: String,
operand: String,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
struct Simulation<'a> {
name: &'a str,
description: &'a str,
caller_key: &'a str,
config: Config,
steps: Vec<Step<'a>>,
}
fn parse_yaml<'a>(yaml_content: &'a str) -> Result<Simulation<'a>, Box<dyn std::error::Error>> {
let workflow: Simulation<'a> = serde_yaml::from_str(yaml_content)?;
Ok(workflow)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_yaml() {
let yaml_content = "
name: token program
description: Deploy and execute token program
caller_key: alice_key
steps:
- task: key
description: create alice key
request:
method: create
params:
- name: key name
type: string
value: alice_key
- task: key
description: create bob key
request:
method: create
params:
- name: key name
type: string
value: bob_key
";
let expected = Simulation {
name: "token program",
description: "Deploy and execute token program",
caller_key: "alice_key",
config: Config {
max_memory_pages: 18,
},
steps: vec![
Step {
task: "key",
description: "create alice key",
request: Some(Request {
method: "create",
params: vec![Param {
name: "key name",
param_type: "string",
value: "alice_key",
}],
}),
require: None,
},
Step {
task: "key",
description: "create bob key",
request: Some(Request {
method: "create",
params: vec![Param {
name: "key name",
param_type: "string",
value: "bob_key",
}],
}),
require: None,
},
],
};
assert_eq!(parse_yaml(yaml_content).unwrap(), expected);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment