Skip to content

Commit c65058a

Browse files
committed
impl ToLua and FromLua for HashSet and BTreeSet
1 parent 93d63ce commit c65058a

File tree

1 file changed

+51
-1
lines changed

1 file changed

+51
-1
lines changed

src/conversion.rs

Lines changed: 51 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use std::collections::{BTreeMap, HashMap};
1+
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
22
use std::ffi::{CStr, CString};
33
use std::hash::{BuildHasher, Hash};
44
use std::string::String as StdString;
@@ -481,6 +481,56 @@ impl<'lua, K: Ord + FromLua<'lua>, V: FromLua<'lua>> FromLua<'lua> for BTreeMap<
481481
}
482482
}
483483

484+
impl<'lua, T: Eq + Hash + ToLua<'lua>, S: BuildHasher> ToLua<'lua> for HashSet<T, S> {
485+
fn to_lua(self, lua: &'lua Lua) -> Result<Value<'lua>> {
486+
Ok(Value::Table(lua.create_table_from(
487+
self.into_iter().map(|val| (val, true)),
488+
)?))
489+
}
490+
}
491+
492+
impl<'lua, T: Eq + Hash + FromLua<'lua>, S: BuildHasher + Default> FromLua<'lua> for HashSet<T, S> {
493+
fn from_lua(value: Value<'lua>, _: &'lua Lua) -> Result<Self> {
494+
if let Value::Table(table) = value {
495+
table
496+
.pairs::<T, Value<'lua>>()
497+
.map(|res| res.map(|(k, _)| k))
498+
.collect()
499+
} else {
500+
Err(Error::FromLuaConversionError {
501+
from: value.type_name(),
502+
to: "HashSet",
503+
message: Some("expected table".to_string()),
504+
})
505+
}
506+
}
507+
}
508+
509+
impl<'lua, T: Ord + ToLua<'lua>> ToLua<'lua> for BTreeSet<T> {
510+
fn to_lua(self, lua: &'lua Lua) -> Result<Value<'lua>> {
511+
Ok(Value::Table(lua.create_table_from(
512+
self.into_iter().map(|val| (val, true)),
513+
)?))
514+
}
515+
}
516+
517+
impl<'lua, T: Ord + FromLua<'lua>> FromLua<'lua> for BTreeSet<T> {
518+
fn from_lua(value: Value<'lua>, _: &'lua Lua) -> Result<Self> {
519+
if let Value::Table(table) = value {
520+
table
521+
.pairs::<T, Value<'lua>>()
522+
.map(|res| res.map(|(k, _)| k))
523+
.collect()
524+
} else {
525+
Err(Error::FromLuaConversionError {
526+
from: value.type_name(),
527+
to: "BTreeSet",
528+
message: Some("expected table".to_string()),
529+
})
530+
}
531+
}
532+
}
533+
484534
impl<'lua, T: ToLua<'lua>> ToLua<'lua> for Option<T> {
485535
fn to_lua(self, lua: &'lua Lua) -> Result<Value<'lua>> {
486536
match self {

0 commit comments

Comments
 (0)