Skip to content

Add conversion for BTreeMap #138

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

Merged
merged 1 commit into from
Feb 23, 2025
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
62 changes: 62 additions & 0 deletions src/r_hash.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! Types and functions for working with Ruby’s Hash class.

use std::{
collections::BTreeMap,
collections::HashMap,
convert::Infallible,
fmt,
Expand Down Expand Up @@ -804,6 +805,46 @@ impl RHash {
Ok(map)
}

/// Return `self` converted to a Rust [`BTreeMap`].
///
/// This will only convert to a map of 'owned' Rust native types. The types
/// representing Ruby objects can not be stored in a heap-allocated
/// datastructure like a [`BTreeMap`] as they are hidden from the mark phase
/// of Ruby's garbage collector, and thus may be prematurely garbage
/// collected in the following sweep phase.
///
/// Errors if the conversion of any key or value fails.
///
/// # Examples
///
/// ```
/// use std::collections::BTreeMap;
///
/// use magnus::{Error, RHash, Ruby};
///
/// fn example(ruby: &Ruby) -> Result<(), Error> {
/// let r_hash: RHash = ruby.eval(r#"{"answer" => 42}"#)?;
/// let mut hash_map = BTreeMap::new();
/// hash_map.insert(String::from("answer"), 42);
/// assert_eq!(r_hash.to_btree_map()?, hash_map);
///
/// Ok(())
/// }
/// # Ruby::init(example).unwrap()
/// ```
pub fn to_btree_map<K, V>(self) -> Result<BTreeMap<K, V>, Error>
where
K: TryConvertOwned + Eq + Hash + Ord,
V: TryConvertOwned,
{
let mut map = BTreeMap::new();
self.foreach(|key, value| {
map.insert(key, value);
Ok(ForEach::Continue)
})?;
Ok(map)
}

/// Convert `self` to a Rust vector of key/value pairs.
///
/// This will only convert to a map of 'owned' Rust native types. The types
Expand Down Expand Up @@ -940,6 +981,27 @@ where
{
}

impl<K, V> IntoValue for BTreeMap<K, V>
where
K: IntoValueFromNative,
V: IntoValueFromNative,
{
fn into_value_with(self, handle: &Ruby) -> Value {
let hash = handle.hash_new();
for (k, v) in self {
let _ = hash.aset(k, v);
}
hash.into_value_with(handle)
}
}

unsafe impl<K, V> IntoValueFromNative for BTreeMap<K, V>
where
K: IntoValueFromNative,
V: IntoValueFromNative,
{
}

#[cfg(feature = "old-api")]
impl<K, V> FromIterator<(K, V)> for RHash
where
Expand Down
18 changes: 18 additions & 0 deletions src/try_convert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,24 @@ where
{
}

impl<K, V> TryConvert for std::collections::BTreeMap<K, V>
where
K: TryConvertOwned + Eq + std::hash::Hash + Ord,
V: TryConvertOwned,
{
#[inline]
fn try_convert(val: Value) -> Result<Self, Error> {
debug_assert_value!(val);
RHash::try_convert(val)?.to_btree_map()
}
}
unsafe impl<K, V> TryConvertOwned for std::collections::BTreeMap<K, V>
where
K: TryConvertOwned + Eq + std::hash::Hash + Ord,
V: TryConvertOwned,
{
}

#[cfg(unix)]
impl TryConvert for PathBuf {
fn try_convert(val: Value) -> Result<Self, Error> {
Expand Down
23 changes: 21 additions & 2 deletions tests/hash.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::collections::HashMap;
use std::collections::{BTreeMap, HashMap};

#[test]
fn it_converts_hash_map() {
fn it_converts_maps() {
let ruby = unsafe { magnus::embed::init() };

let map: HashMap<String, u8> = ruby
Expand All @@ -22,4 +22,23 @@ fn it_converts_hash_map() {
r#"map == {"test" => [0, 0.5], "example" => [1, 3.75]}"#,
map
);

let map: BTreeMap<String, u8> = ruby
.eval(r#"{"foo" => 1, "bar" => 2, "baz" => 3}"#)
.unwrap();

let mut expected = BTreeMap::new();
expected.insert("foo".to_owned(), 1);
expected.insert("bar".to_owned(), 2);
expected.insert("baz".to_owned(), 3);
assert_eq!(expected, map);

let mut map = BTreeMap::new();
map.insert("test", (0, 0.5));
map.insert("example", (1, 3.75));
magnus::rb_assert!(
ruby,
r#"map == {"test" => [0, 0.5], "example" => [1, 3.75]}"#,
map
);
}
Loading