Skip to content

Commit 0b6556e

Browse files
committed
Allow arbitrary types of map keys
Of particular interest are maps that have numbers or enums as keys. Closes #74.
1 parent ad29f8f commit 0b6556e

File tree

3 files changed

+52
-2
lines changed

3 files changed

+52
-2
lines changed

src/de.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -215,7 +215,7 @@ impl<'de> de::MapAccess<'de> for MapAccess {
215215
K: de::DeserializeSeed<'de>,
216216
{
217217
if let Some(&(ref key_s, _)) = self.elements.front() {
218-
let key_de = StrDeserializer(key_s);
218+
let key_de = Value::new(None, key_s as &str);
219219
let key = de::DeserializeSeed::deserialize(seed, key_de)?;
220220

221221
Ok(Some(key))

tests/Settings.toml

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ code = 53
99
boolean_s_parse = "fals"
1010

1111
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
12+
quarks = ["up", "down", "strange", "charm", "bottom", "top"]
1213

1314
[diodes]
1415
green = "off"
@@ -40,3 +41,13 @@ rating = 4.5
4041

4142
[place.creator]
4243
name = "John Smith"
44+
45+
[proton]
46+
up = 2
47+
down = 1
48+
49+
[divisors]
50+
1 = 1
51+
2 = 2
52+
4 = 3
53+
5 = 2

tests/get.rs

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ extern crate serde_derive;
99

1010
use config::*;
1111
use float_cmp::ApproxEqUlps;
12-
use std::collections::HashMap;
12+
use std::collections::{HashMap, HashSet};
1313

1414
#[derive(Debug, Deserialize)]
1515
struct Place {
@@ -225,3 +225,42 @@ fn test_enum() {
225225
assert_eq!(s.diodes["blue"], Diode::Blinking(300, 700));
226226
assert_eq!(s.diodes["white"], Diode::Pattern{name: "christmas".into(), inifinite: true,});
227227
}
228+
229+
#[test]
230+
fn test_enum_key() {
231+
#[derive(Debug, Deserialize, PartialEq, Eq, Hash)]
232+
enum Quark {
233+
Up,
234+
Down,
235+
Strange,
236+
Charm,
237+
Bottom,
238+
Top,
239+
}
240+
241+
#[derive(Debug, Deserialize)]
242+
struct Settings {
243+
proton: HashMap<Quark, usize>,
244+
// Just to make sure that set keys work too.
245+
quarks: HashSet<Quark>,
246+
}
247+
248+
let c = make();
249+
let s: Settings = c.try_into().unwrap();
250+
251+
assert_eq!(s.proton[&Quark::Up], 2);
252+
assert_eq!(s.quarks.len(), 6);
253+
}
254+
255+
#[test]
256+
fn test_int_key() {
257+
#[derive(Debug, Deserialize, PartialEq)]
258+
struct Settings {
259+
divisors: HashMap<u32, u32>,
260+
}
261+
262+
let c = make();
263+
let s: Settings = c.try_into().unwrap();
264+
assert_eq!(s.divisors[&4], 3);
265+
assert_eq!(s.divisors.len(), 4);
266+
}

0 commit comments

Comments
 (0)