From 82a572bda127405f1bd2e4068e31be7c61915306 Mon Sep 17 00:00:00 2001 From: ENGO150 Date: Sat, 1 Feb 2025 16:04:04 +0100 Subject: [PATCH] created why2_toml_write_preserve rust fn same as why2_toml_write but does not remove comments --- include/chat/config.h | 1 + src/chat/config/Cargo.toml | 1 + src/chat/config/src/lib.rs | 42 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 44 insertions(+) diff --git a/include/chat/config.h b/include/chat/config.h index a38abfb..f021052 100644 --- a/include/chat/config.h +++ b/include/chat/config.h @@ -40,6 +40,7 @@ void why2_chat_init_authority(void); //CREATE WHY2_CHAT_AUTHORITY_DIR char *why2_toml_read(const char* path, const char* key); //READ key FROM path TOML FILE void why2_toml_write(const char *path, const char *key, const char *value); //WRITE value AS key INTO path TOML FILE +void why2_toml_write_preserve(const char *path, const char *key, const char *value); //WRITE value AS key INTO path TOML FILE WITHOUT REMOVING COMMENTS why2_bool why2_toml_contains(const char *path, const char *key); //CHECK IF path CONTAINS key why2_bool why2_toml_equals(const char *path, const char *key, const char *value); //CHECK IF key IN path IS EQUAL TO value void why2_toml_read_free(char* s); //DEALLOCATE THE READ VALUE diff --git a/src/chat/config/Cargo.toml b/src/chat/config/Cargo.toml index 30c69cc..0a36273 100644 --- a/src/chat/config/Cargo.toml +++ b/src/chat/config/Cargo.toml @@ -25,3 +25,4 @@ crate-type = ["cdylib"] [dependencies] toml = "*" +toml_edit = "*" \ No newline at end of file diff --git a/src/chat/config/src/lib.rs b/src/chat/config/src/lib.rs index 1fb379f..a2369f7 100644 --- a/src/chat/config/src/lib.rs +++ b/src/chat/config/src/lib.rs @@ -126,6 +126,48 @@ pub extern "C" fn why2_toml_write(path: *const c_char, key: *const c_char, value } } +#[no_mangle] +pub extern "C" fn why2_toml_write_preserve(path: *const c_char, key: *const c_char, value: *const c_char) +{ + //CONVERT C STRINGS TO RUST STRINGS + let path_r = unsafe { CStr::from_ptr(path).to_string_lossy().into_owned() }; + let key_r = unsafe { CStr::from_ptr(key).to_string_lossy().into_owned() }; + let value_r = unsafe { CStr::from_ptr(value).to_string_lossy().into_owned() }; + + //READ FILE + let file_raw = match read_to_string(&path_r) + { + Ok(raw) => raw, + Err(e) => + { + eprintln!("Could not read TOML config '{}': {}", path_r, e); + return; + } + }; + + //PARSE TO A toml_edit Document + let mut doc: toml_edit::Document = match file_raw.parse() + { + Ok(doc) => doc, + Err(e) => + { + eprintln!("Could not parse TOML config '{}': {}", path_r, e); + return; + } + }; + + doc[&key_r] = toml_edit::value(value_r); + + //CONVERT DOCUMENT TO STRING + let updated_data = doc.to_string(); + + //WRITE + if let Err(e) = write(&path_r, updated_data) + { + eprintln!("Could not write to TOML config '{}': {}", path_r, e); + } +} + #[no_mangle] pub extern "C" fn why2_toml_contains(path: *const c_char, key: *const c_char) -> bool {