Skip to content

Commit

Permalink
Add JSON_SaveFile.
Browse files Browse the repository at this point in the history
  • Loading branch information
TommyB123 committed Feb 9, 2021
1 parent 174f6ee commit 2e56809
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 0 deletions.
1 change: 1 addition & 0 deletions json.inc
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ enum JSON_NODE {
// JSON_Parse decodes JSON and stores the root node into `output`.
native JSON_Parse(const string[], &Node:output);
native JSON_ParseFile(const path[], &Node:output);
native JSON_SaveFile(const path[], Node:input);

// JSON_Stringify encodes a JSON node into `buf`.
native JSON_Stringify(Node:node, buf[], len = sizeof(buf));
Expand Down
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ initialize_plugin!(
natives: [
Plugin::json_parse,
Plugin::json_parse_file,
Plugin::json_save_file,
Plugin::json_stringify,
Plugin::json_node_type,
Plugin::json_object,
Expand Down
30 changes: 30 additions & 0 deletions src/plugin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,36 @@ impl Plugin {
Ok(0)
}

#[native(name = "JSON_SaveFile")]
pub fn json_save_file(&mut self, _: &Amx, path: AmxString, node: i32) -> AmxResult<i32> {
let v: &serde_json::Value = match self.json_nodes.get(node) {
Some(v) => v,
None => return Ok(1),
};
let mut file = match File::create(path.to_string()) {
Ok(file) => file,
Err(e) => {
error!("{}", e);
return Ok(1);
}
};
let string = match serde_json::to_string(&v) {
Ok(v) => v,
Err(e) => {
error!("{}", e);
return Ok(1);
}
};
match file.write_all(string.as_bytes()) {
Ok(file) => file,
Err(e) => {
error!("{}", e);
return Ok(1);
}
};
Ok(0)
}

#[native(name = "JSON_Stringify")]
pub fn json_stringify(
&mut self,
Expand Down

0 comments on commit 2e56809

Please sign in to comment.