Skip to content

feat(array): introducing BTreeMap conversion and refactoring HashMap conversion #535

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

Open
wants to merge 1 commit 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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 17 additions & 10 deletions src/types/array/array_key.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::{convert::TryFrom, fmt::Display};

use crate::{convert::FromZval, error::Error, flags::DataType, types::Zval};
use std::str::FromStr;
use std::{convert::TryFrom, fmt::Display};

/// Represents the key of a PHP array, which can be either a long or a string.
#[derive(Debug, Clone, PartialEq)]
Expand All @@ -17,26 +17,30 @@ pub enum ArrayKey<'a> {

impl From<String> for ArrayKey<'_> {
fn from(value: String) -> Self {
Self::String(value)
if let Ok(index) = i64::from_str(value.as_str()) {
Self::Long(index)
} else {
Self::String(value)
}
}
}

impl TryFrom<ArrayKey<'_>> for String {
type Error = Error;

fn try_from(value: ArrayKey<'_>) -> std::result::Result<Self, Self::Error> {
fn try_from(value: ArrayKey<'_>) -> Result<Self, Self::Error> {
match value {
ArrayKey::String(s) => Ok(s),
ArrayKey::Str(s) => Ok(s.to_string()),
ArrayKey::Long(_) => Err(Error::InvalidProperty),
ArrayKey::Long(l) => Ok(l.to_string()),
}
}
}

impl TryFrom<ArrayKey<'_>> for i64 {
type Error = Error;

fn try_from(value: ArrayKey<'_>) -> std::result::Result<Self, Self::Error> {
fn try_from(value: ArrayKey<'_>) -> Result<Self, Self::Error> {
match value {
ArrayKey::Long(i) => Ok(i),
ArrayKey::String(s) => s.parse::<i64>().map_err(|_| Error::InvalidProperty),
Expand Down Expand Up @@ -71,8 +75,12 @@ impl Display for ArrayKey<'_> {
}

impl<'a> From<&'a str> for ArrayKey<'a> {
fn from(key: &'a str) -> ArrayKey<'a> {
ArrayKey::Str(key)
fn from(value: &'a str) -> ArrayKey<'a> {
if let Ok(index) = i64::from_str(value) {
Self::Long(index)
} else {
ArrayKey::Str(value)
}
}
}

Expand Down Expand Up @@ -117,8 +125,7 @@ mod tests {

let key = ArrayKey::Long(42);
let result: crate::error::Result<String, _> = key.try_into();
assert!(result.is_err());
assert!(matches!(result.unwrap_err(), Error::InvalidProperty));
assert_eq!(result.unwrap(), "42".to_string());

let key = ArrayKey::String("42".to_string());
let result: crate::error::Result<String, _> = key.try_into();
Expand Down
78 changes: 78 additions & 0 deletions src/types/array/conversions/btree_map.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
use std::{collections::BTreeMap, convert::TryFrom};

use super::super::ZendHashTable;
use crate::types::ArrayKey;
use crate::{
boxed::ZBox,
convert::{FromZval, IntoZval},
error::{Error, Result},
flags::DataType,
types::Zval,
};

impl<'a, K, V> TryFrom<&'a ZendHashTable> for BTreeMap<K, V>
where
K: TryFrom<ArrayKey<'a>, Error = Error> + Ord,
V: FromZval<'a>,
{
type Error = Error;

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

for (key, val) in value {
hm.insert(
key.try_into()?,
V::from_zval(val).ok_or_else(|| Error::ZvalConversion(val.get_type()))?,
);
}

Ok(hm)
}
}

impl<K, V> TryFrom<BTreeMap<K, V>> for ZBox<ZendHashTable>
where
K: AsRef<str>,
V: IntoZval,
{
type Error = Error;

fn try_from(value: BTreeMap<K, V>) -> Result<Self> {
let mut ht = ZendHashTable::with_capacity(
value.len().try_into().map_err(|_| Error::IntegerOverflow)?,
);

for (k, v) in value {
ht.insert(k.as_ref(), v)?;
}

Ok(ht)
}
}

impl<K, V> IntoZval for BTreeMap<K, V>
where
K: AsRef<str>,
V: IntoZval,
{
const TYPE: DataType = DataType::Array;
const NULLABLE: bool = false;

fn set_zval(self, zv: &mut Zval, _: bool) -> Result<()> {
let arr = self.try_into()?;
zv.set_hashtable(arr);
Ok(())
}
}

impl<'a, T> FromZval<'a> for BTreeMap<String, T>
where
T: FromZval<'a>,
{
const TYPE: DataType = DataType::Array;

fn from_zval(zval: &'a Zval) -> Option<Self> {
zval.array().and_then(|arr| arr.try_into().ok())
}
}
35 changes: 17 additions & 18 deletions src/types/array/conversions/hash_map.rs
Original file line number Diff line number Diff line change
@@ -1,29 +1,29 @@
use std::{collections::HashMap, convert::TryFrom};

use super::super::ZendHashTable;
use crate::types::ArrayKey;
use crate::{
boxed::ZBox,
convert::{FromZval, IntoZval},
error::{Error, Result},
flags::DataType,
types::Zval,
};
use std::hash::{BuildHasher, Hash};
use std::{collections::HashMap, convert::TryFrom};

use super::super::ZendHashTable;

// TODO: Generalize hasher
#[allow(clippy::implicit_hasher)]
impl<'a, V> TryFrom<&'a ZendHashTable> for HashMap<String, V>
impl<'a, K, V, H> TryFrom<&'a ZendHashTable> for HashMap<K, V, H>
where
K: TryFrom<ArrayKey<'a>, Error = Error> + Eq + Hash,
V: FromZval<'a>,
H: BuildHasher + Default,
{
type Error = Error;

fn try_from(value: &'a ZendHashTable) -> Result<Self> {
let mut hm = HashMap::with_capacity(value.len());
let mut hm = Self::with_capacity_and_hasher(value.len(), H::default());

for (key, val) in value {
hm.insert(
key.to_string(),
key.try_into()?,
V::from_zval(val).ok_or_else(|| Error::ZvalConversion(val.get_type()))?,
);
}
Expand All @@ -32,14 +32,15 @@ where
}
}

impl<K, V> TryFrom<HashMap<K, V>> for ZBox<ZendHashTable>
impl<K, V, H> TryFrom<HashMap<K, V, H>> for ZBox<ZendHashTable>
where
K: AsRef<str>,
V: IntoZval,
H: BuildHasher,
{
type Error = Error;

fn try_from(value: HashMap<K, V>) -> Result<Self> {
fn try_from(value: HashMap<K, V, H>) -> Result<Self> {
let mut ht = ZendHashTable::with_capacity(
value.len().try_into().map_err(|_| Error::IntegerOverflow)?,
);
Expand All @@ -52,12 +53,11 @@ where
}
}

// TODO: Generalize hasher
#[allow(clippy::implicit_hasher)]
impl<K, V> IntoZval for HashMap<K, V>
impl<K, V, H> IntoZval for HashMap<K, V, H>
where
K: AsRef<str>,
V: IntoZval,
H: BuildHasher,
{
const TYPE: DataType = DataType::Array;
const NULLABLE: bool = false;
Expand All @@ -69,11 +69,10 @@ where
}
}

// TODO: Generalize hasher
#[allow(clippy::implicit_hasher)]
impl<'a, T> FromZval<'a> for HashMap<String, T>
impl<'a, V, H> FromZval<'a> for HashMap<String, V, H>
where
T: FromZval<'a>,
V: FromZval<'a>,
H: BuildHasher + Default,
{
const TYPE: DataType = DataType::Array;

Expand Down
2 changes: 2 additions & 0 deletions src/types/array/conversions/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@
//!
//! ## Supported Collections
//!
//! - `BTreeMap<K, V>` ↔ `ZendHashTable` (via `btree_map` module)
//! - `HashMap<K, V>` ↔ `ZendHashTable` (via `hash_map` module)
//! - `Vec<T>` and `Vec<(K, V)>` ↔ `ZendHashTable` (via `vec` module)

mod btree_map;
mod hash_map;
mod vec;
5 changes: 2 additions & 3 deletions src/types/array/conversions/vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,7 @@ mod tests {

let vec_mixed: Option<Vec<(String, String)>> =
Vec::<(String, String)>::from_zval(&zval_mixed);
assert!(vec_mixed.is_none());
assert!(vec_mixed.is_some());
});
}

Expand Down Expand Up @@ -345,8 +345,7 @@ mod tests {
ht2.insert(2, "value2").unwrap();

let vec2: crate::error::Result<Vec<(String, String)>> = ht2.as_ref().try_into();
assert!(vec2.is_err());
assert!(matches!(vec2.unwrap_err(), Error::InvalidProperty));
assert!(vec2.is_ok());
});
}

Expand Down
Loading
Loading