Skip to content

Commit b898cda

Browse files
committed
serde example
1 parent d7464ff commit b898cda

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

Cargo.toml

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,3 +21,10 @@ failure = "0.1"
2121
version = "1.0"
2222
features = ["derive"]
2323
optional = true
24+
25+
[dev-dependencies]
26+
serde_json = "1.0"
27+
28+
[[example]]
29+
name = "svd2json"
30+
required-features = ["serde"]

examples/svd2json.rs

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
use serde_json as json;
2+
use svd_parser as svd;
3+
4+
use json::Value;
5+
use std::env::args;
6+
use std::fs::File;
7+
use std::io::{Read, Write};
8+
9+
fn main() {
10+
// Collect command-line arguments.
11+
let argv: Vec<String> = args().collect();
12+
// Expect exactly one argument, with the name of the SVD file.
13+
// (Arg #0 is this program's name, Arg #1 is the actual argument)
14+
if argv.len() != 2 {
15+
println!("Usage: (svd2json) file.svd");
16+
return;
17+
}
18+
let svd_fn: String = argv[1].clone();
19+
20+
// Open the XML-formatted SVD file and read it into a String.
21+
let svd_xml = &mut String::new();
22+
File::open(&svd_fn)
23+
.expect("Failed to open SVD input file")
24+
.read_to_string(svd_xml)
25+
.expect("Failed to read SVD input file to a String");
26+
27+
// Use the 'svd_parser' crate to parse the file.
28+
let device = svd::parse(svd_xml).expect("Failed to parse the SVD file into Rust structs");
29+
30+
// Convert the parsed data into JSON format.
31+
let v: Value = json::to_value(device).expect("Failed to parse Rust structs into JSON format");
32+
33+
// Write the JSON-formatted device description to a file.
34+
let json_fn: String = svd_fn + ".json";
35+
File::create(json_fn)
36+
.expect("Failed to open JSON output file")
37+
.write_all(json::to_string_pretty(&v).unwrap().as_bytes())
38+
.expect("Failed to write to JSON output file");
39+
}

0 commit comments

Comments
 (0)