Skip to content

Commit

Permalink
reduce duplicated code for iter key
Browse files Browse the repository at this point in the history
  • Loading branch information
joelwurtz committed Oct 17, 2023
1 parent cdfc362 commit 91972dd
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 31 deletions.
25 changes: 6 additions & 19 deletions src/types/array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ use std::{
};

use crate::types::iterator::IterKey;
use crate::types::ZendLong;
use crate::{
boxed::{ZBox, ZBoxable},
convert::{FromZval, IntoZval},
Expand Down Expand Up @@ -622,15 +621,9 @@ impl<'a> Iterator for Iter<'a> {
)
};

let r = match key.is_long() {
true => (
IterKey::Long(key.long().unwrap_or(self.current_num as ZendLong) as u64),
value,
),
false => match key.try_into() {
Ok(key) => (IterKey::String(key), value),
Err(_) => (IterKey::Long(self.current_num), value),
},
let r = match IterKey::from_zval(&key) {
Some(key) => (key, value),
None => (IterKey::Long(self.current_num), value),
};

unsafe {
Expand Down Expand Up @@ -686,15 +679,9 @@ impl<'a> DoubleEndedIterator for Iter<'a> {
)
};

let r = match key.is_long() {
true => (
IterKey::Long(key.long().unwrap_or(self.current_num as ZendLong) as u64),
value,
),
false => match key.try_into() {
Ok(key) => (IterKey::String(key), value),
Err(_) => (IterKey::Long(self.current_num), value),
},
let r = match IterKey::from_zval(&key) {
Some(key) => (key, value),
None => (IterKey::Long(self.current_num), value),
};

unsafe {
Expand Down
28 changes: 16 additions & 12 deletions src/types/iterator.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
use crate::convert::FromZvalMut;
use crate::convert::{FromZval, FromZvalMut};
use crate::ffi::zend_object_iterator;
use crate::flags::DataType;
use crate::types::{ZendLong, Zval};
use std::convert::TryInto;
use crate::types::Zval;
use std::fmt::{Debug, Display, Formatter};

/// A PHP Iterator.
Expand Down Expand Up @@ -93,6 +92,17 @@ impl Display for IterKey {
}
}

impl FromZval<'_> for IterKey {
const TYPE: DataType = DataType::String;

fn from_zval(zval: &Zval) -> Option<Self> {
match zval.long() {
Some(key) => Some(IterKey::Long(key as u64)),
None => zval.string().map(|key| IterKey::String(key)),
}
}
}

pub struct Iter<'a> {
zi: &'a mut ZendIterator,
}
Expand All @@ -117,15 +127,9 @@ impl<'a> Iterator for Iter<'a> {
let real_index = self.zi.index - 1;

Some(match key {
Some(key) => match key.is_long() {
false => match key.try_into() {
Ok(key) => (IterKey::String(key), value),
Err(_) => (IterKey::Long(real_index), value),
},
true => (
IterKey::Long(key.long().unwrap_or(real_index as ZendLong) as u64),
value,
),
Some(key) => match IterKey::from_zval(&key) {
Some(key) => (key, value),
None => (IterKey::Long(real_index), value),
},
None => (IterKey::Long(real_index), value),
})
Expand Down

0 comments on commit 91972dd

Please sign in to comment.