frontend-utils: Add TableExt trait

This moves the logic previously found in BookmarkWriter's `with_underlying_table`
into a common trait to be reused by other writers.
This commit is contained in:
sleepycatcoding 2024-04-04 19:31:22 +03:00 committed by Nathan Adams
parent e4c798fdd4
commit 9f71206fcf
5 changed files with 28 additions and 16 deletions

1
Cargo.lock generated
View File

@ -4286,6 +4286,7 @@ name = "ruffle_frontend_utils"
version = "0.1.0"
dependencies = [
"toml_edit 0.22.9",
"tracing",
"url",
]

View File

@ -3,8 +3,9 @@ use crate::preferences::storage::StorageBackend;
use crate::preferences::SavedGlobalPreferences;
use ruffle_frontend_utils::bookmarks::{Bookmark, Bookmarks};
use ruffle_frontend_utils::parse::DocumentHolder;
use ruffle_frontend_utils::write::TableExt;
use ruffle_render_wgpu::clap::{GraphicsBackend, PowerPreference};
use toml_edit::{array, value, ArrayOfTables, DocumentMut, Table};
use toml_edit::{value, ArrayOfTables, Table};
use unic_langid::LanguageIdentifier;
pub struct PreferencesWriter<'a>(&'a mut DocumentHolder<SavedGlobalPreferences>);
@ -83,22 +84,8 @@ impl<'a> BookmarksWriter<'a> {
}
fn with_underlying_table(&mut self, fun: impl FnOnce(&mut Bookmarks, &mut ArrayOfTables)) {
fn find_table(toml_document: &mut DocumentMut) -> &mut ArrayOfTables {
if toml_document.contains_array_of_tables("bookmark") {
return toml_document["bookmark"]
.as_array_of_tables_mut()
.expect("type was just verified");
}
tracing::warn!("missing or invalid bookmark array, recreating..");
toml_document.insert("bookmark", array());
toml_document["bookmark"]
.as_array_of_tables_mut()
.expect("type was just created")
}
self.0.edit(|values, toml_document| {
let table = find_table(toml_document);
let table = toml_document.get_or_create_array_of_tables("bookmark");
fun(values, table)
})
}

View File

@ -13,3 +13,4 @@ workspace = true
[dependencies]
toml_edit = { version = "0.22.9", features = ["parse"] }
url = { workspace = true }
tracing = { workspace = true }

View File

@ -1,2 +1,3 @@
pub mod bookmarks;
pub mod parse;
pub mod write;

View File

@ -0,0 +1,22 @@
use toml_edit::{array, ArrayOfTables, Table};
pub trait TableExt {
/// Gets an existing array of tables, or creates a new one if it does not exist or type is different.
fn get_or_create_array_of_tables(&mut self, key: &str) -> &mut ArrayOfTables;
}
impl TableExt for Table {
fn get_or_create_array_of_tables(&mut self, key: &str) -> &mut ArrayOfTables {
if self.contains_array_of_tables(key) {
return self[key]
.as_array_of_tables_mut()
.expect("type was just verified");
}
tracing::warn!("missing or invalid '{key}' array, recreating..");
self.insert(key, array());
self[key]
.as_array_of_tables_mut()
.expect("type was just created")
}
}