Skip to content

Commit fbd7d14

Browse files
committed
feat(array): add support for BTreeMap ArrayKey
Refs: extphprs#535
1 parent 6c83ceb commit fbd7d14

File tree

2 files changed

+43
-11
lines changed

2 files changed

+43
-11
lines changed

src/types/array/array_key.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ use std::str::FromStr;
33
use std::{convert::TryFrom, fmt::Display};
44

55
/// Represents the key of a PHP array, which can be either a long or a string.
6-
#[derive(Debug, Clone, PartialEq)]
6+
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
77
pub enum ArrayKey<'a> {
88
/// A numerical key.
99
/// In Zend API it's represented by `u64` (`zend_ulong`), so the value needs

src/types/array/conversions/btree_map.rs

Lines changed: 42 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -18,22 +18,42 @@ where
1818
type Error = Error;
1919

2020
fn try_from(value: &'a ZendHashTable) -> Result<Self> {
21-
let mut hm = Self::new();
21+
let mut map = Self::new();
2222

2323
for (key, val) in value {
24-
hm.insert(
24+
map.insert(
2525
key.try_into()?,
2626
V::from_zval(val).ok_or_else(|| Error::ZvalConversion(val.get_type()))?,
2727
);
2828
}
2929

30-
Ok(hm)
30+
Ok(map)
3131
}
3232
}
3333

34-
impl<K, V> TryFrom<BTreeMap<K, V>> for ZBox<ZendHashTable>
34+
impl<'a, V> TryFrom<&'a ZendHashTable> for BTreeMap<ArrayKey<'a>, V>
3535
where
36-
K: AsRef<str>,
36+
V: FromZval<'a>,
37+
{
38+
type Error = Error;
39+
40+
fn try_from(value: &'a ZendHashTable) -> Result<Self> {
41+
let mut map = Self::new();
42+
43+
for (key, val) in value {
44+
map.insert(
45+
key,
46+
V::from_zval(val).ok_or_else(|| Error::ZvalConversion(val.get_type()))?,
47+
);
48+
}
49+
50+
Ok(map)
51+
}
52+
}
53+
54+
impl<'a, K, V> TryFrom<BTreeMap<K, V>> for ZBox<ZendHashTable>
55+
where
56+
K: Into<ArrayKey<'a>>,
3757
V: IntoZval,
3858
{
3959
type Error = Error;
@@ -44,16 +64,16 @@ where
4464
);
4565

4666
for (k, v) in value {
47-
ht.insert(k.as_ref(), v)?;
67+
ht.insert(k, v)?;
4868
}
4969

5070
Ok(ht)
5171
}
5272
}
5373

54-
impl<K, V> IntoZval for BTreeMap<K, V>
74+
impl<'a, K, V> IntoZval for BTreeMap<K, V>
5575
where
56-
K: AsRef<str>,
76+
K: Into<ArrayKey<'a>>,
5777
V: IntoZval,
5878
{
5979
const TYPE: DataType = DataType::Array;
@@ -66,9 +86,21 @@ where
6686
}
6787
}
6888

69-
impl<'a, T> FromZval<'a> for BTreeMap<String, T>
89+
impl<'a, K, V> FromZval<'a> for BTreeMap<K, V>
7090
where
71-
T: FromZval<'a>,
91+
K: TryFrom<ArrayKey<'a>, Error = Error> + Ord,
92+
V: FromZval<'a>,
93+
{
94+
const TYPE: DataType = DataType::Array;
95+
96+
fn from_zval(zval: &'a Zval) -> Option<Self> {
97+
zval.array().and_then(|arr| arr.try_into().ok())
98+
}
99+
}
100+
101+
impl<'a, V> FromZval<'a> for BTreeMap<ArrayKey<'a>, V>
102+
where
103+
V: FromZval<'a>,
72104
{
73105
const TYPE: DataType = DataType::Array;
74106

0 commit comments

Comments
 (0)