Skip to content
This repository was archived by the owner on Aug 15, 2021. It is now read-only.

Commit ef08d90

Browse files
committed
Add blanket From conversions for Value containers
Serde uses a blanket impl for serialization. This change fixes the From conversions to match serde's behavior. Without this, the user of serde_cbor could run into awkward bugs where values of the same type get serialized different ways; all hidden behind an innocent looking .into().
1 parent 04de01f commit ef08d90

File tree

1 file changed

+25
-4
lines changed

1 file changed

+25
-4
lines changed

src/value/mod.rs

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -125,11 +125,32 @@ impl_from!(Value::Integer, u64);
125125
// u128 omitted because not all numbers fit in CBOR serialization
126126
impl_from!(Value::Float, f32);
127127
impl_from!(Value::Float, f64);
128-
impl_from!(Value::Bytes, Vec<u8>);
129128
impl_from!(Value::Text, String);
130-
// TODO: figure out if these impls should be more generic or removed.
131-
impl_from!(Value::Array, Vec<Value>);
132-
impl_from!(Value::Map, BTreeMap<Value, Value>);
129+
130+
impl<T> From<Vec<T>> for Value
131+
where
132+
Value: From<T>,
133+
{
134+
fn from(mut value: Vec<T>) -> Self {
135+
Value::Array(value.drain(..).map(|x| Value::from(x)).collect())
136+
}
137+
}
138+
139+
impl<T, U> From<BTreeMap<T, U>> for Value
140+
where
141+
Value: From<T>,
142+
Value: From<U>,
143+
{
144+
fn from(value: BTreeMap<T, U>) -> Self {
145+
let mut map = BTreeMap::new();
146+
147+
for (key, val) in value {
148+
map.insert(Value::from(key), Value::from(val));
149+
}
150+
151+
Value::Map(map)
152+
}
153+
}
133154

134155
impl Value {
135156
fn major_type(&self) -> u8 {

0 commit comments

Comments
 (0)