Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add {Table,TableLike}::get_mut. #106

Merged
merged 2 commits into from
Jun 4, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions src/table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,11 @@ impl Table {
self.items.get(key).map(|kv| &kv.value)
}

/// Returns an optional mutable reference to an item given the key.
pub fn get_mut<'a>(&'a mut self, key: &str) -> Option<&'a mut Item> {
self.items.get_mut(key).map(|kv| &mut kv.value)
}

/// If a table has no key/value pairs and implicit, it will not be displayed.
///
/// # Examples
Expand Down Expand Up @@ -401,6 +406,8 @@ pub trait TableLike {
}
/// Returns an optional reference to an item given the key.
fn get<'s>(&'s self, key: &str) -> Option<&'s Item>;
/// Returns an optional mutable reference to an item given the key.
fn get_mut<'s>(&'s mut self, key: &str) -> Option<&'s mut Item>;
}

impl TableLike for Table {
Expand All @@ -411,6 +418,9 @@ impl TableLike for Table {
fn get<'s>(&'s self, key: &str) -> Option<&'s Item> {
self.get(key)
}
fn get_mut<'s>(&'s mut self, key: &str) -> Option<&'s mut Item> {
self.get_mut(key)
}
}

/// Returns a formatted value.
Expand Down
3 changes: 3 additions & 0 deletions src/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,9 @@ impl TableLike for InlineTable {
fn get<'s>(&'s self, key: &str) -> Option<&'s Item> {
self.items.get(key).map(|kv| &kv.value)
}
fn get_mut<'s>(&'s mut self, key: &str) -> Option<&'s mut Item> {
self.items.get_mut(key).map(|kv| &mut kv.value)
}
}

/// Downcasting
Expand Down
2 changes: 1 addition & 1 deletion tests/test_edit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -617,7 +617,7 @@ fn test_insert_into_inline_table() {
let a = root.entry("a");
let a = as_inline_table!(a);
assert_eq!(a.len(), 2);
assert!(a.contains_key("a") && a.get("c").is_some());
assert!(a.contains_key("a") && a.get("c").is_some() && a.get_mut("c").is_some());
a.get_or_insert("b", 42);
assert_eq!(a.len(), 3);
a.fmt();
Expand Down