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

feat: impl From<[(K, V); N]> for Map and Value #938

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 6 additions & 0 deletions build.rs
Expand Up @@ -32,6 +32,12 @@ fn main() {
println!("cargo:rustc-cfg=no_btreemap_remove_entry");
}

// Const generics
// https://blog.rust-lang.org/2021/03/25/Rust-1.51.0.html#const-generics-mvp
if minor < 51 {
println!("cargo:rustc-cfg=no_const_generics");
}

// BTreeMap::retain
// https://blog.rust-lang.org/2021/06/17/Rust-1.53.0.html#stabilized-apis
if minor < 53 {
Expand Down
9 changes: 9 additions & 0 deletions src/map.rs
Expand Up @@ -430,6 +430,15 @@ impl<'de> de::Deserialize<'de> for Map<String, Value> {
}
}

#[cfg(not(no_const_generics))]
impl<const N: usize> From<[(String, Value); N]> for Map<String, Value> {
fn from(arr: [(String, Value); N]) -> Self {
// FromIterator::from_iter cannot be used before Rust 1.53
#[allow(deprecated)]
core::array::IntoIter::new(arr).collect()
}
}

impl FromIterator<(String, Value)> for Map<String, Value> {
fn from_iter<T>(iter: T) -> Self
where
Expand Down
19 changes: 19 additions & 0 deletions src/value/from.rs
Expand Up @@ -233,6 +233,25 @@ impl<T: Into<Value>> FromIterator<T> for Value {
}
}

#[cfg(not(no_const_generics))]
impl<K: Into<String>, V: Into<Value>, const N: usize> From<[(K, V); N]> for Value {
/// Convert a list of map entry tuples to `Value`
///
/// # Examples
///
/// ```
/// use serde_json::Value;
///
/// let v = [("lorem", 40), ("ipsum", 2)];
/// let x: Value = v.into();
/// ```
fn from(arr: [(K, V); N]) -> Self {
// FromIterator::from_iter cannot be used before Rust 1.53
#[allow(deprecated)]
core::array::IntoIter::new(arr).collect()
}
}

impl<K: Into<String>, V: Into<Value>> FromIterator<(K, V)> for Value {
/// Convert an iteratable type to a `Value`
///
Expand Down