Skip to content

Commit

Permalink
Fix first/last_index_of functions to use deep object comparison (#612)
Browse files Browse the repository at this point in the history
  • Loading branch information
jayz22 authored Dec 15, 2022
1 parent 995386a commit 94a347c
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 6 deletions.
4 changes: 2 additions & 2 deletions soroban-env-host/src/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1649,7 +1649,7 @@ impl VmCallerCheckedEnv for Host {
) -> Result<RawVal, Self::Error> {
self.visit_obj(v, |hv: &HostVec| {
Ok(
match hv.first_index_of(|other| x.shallow_eq(other), &self.as_budget())? {
match hv.first_index_of(|other| self.compare(&x, other), &self.as_budget())? {
Some(u) => self.usize_to_rawval_u32(u)?,
None => RawVal::from_void(),
},
Expand All @@ -1665,7 +1665,7 @@ impl VmCallerCheckedEnv for Host {
) -> Result<RawVal, Self::Error> {
self.visit_obj(v, |hv: &HostVec| {
Ok(
match hv.last_index_of(|other| x.shallow_eq(other), self.as_budget())? {
match hv.last_index_of(|other| self.compare(&x, other), self.as_budget())? {
Some(u) => self.usize_to_rawval_u32(u)?,
None => RawVal::from_void(),
},
Expand Down
26 changes: 22 additions & 4 deletions soroban-env-host/src/host/metered_vector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -201,18 +201,36 @@ where

pub fn first_index_of<F>(&self, f: F, budget: &Budget) -> Result<Option<usize>, HostError>
where
F: FnMut(&A) -> bool,
F: Fn(&A) -> Result<Ordering, HostError>,
{
self.charge_scan(budget)?;
Ok(self.vec.iter().position(f))
let mut i = 0;
let mut iter = self.vec.iter();
// this is similar logic to `iter.position(f)` but is fallible
while let Some(val) = iter.next() {
if f(val)? == Ordering::Equal {
return Ok(Some(i));
}
i += 1;
}
Ok(None)
}

pub fn last_index_of<F>(&self, f: F, budget: &Budget) -> Result<Option<usize>, HostError>
where
F: FnMut(&A) -> bool,
F: Fn(&A) -> Result<Ordering, HostError>,
{
self.charge_scan(budget)?;
Ok(self.vec.iter().rposition(f))
let mut i = self.vec.len();
let mut iter = self.vec.iter();
// this is similar logic to `iter.rposition(f)` but is fallible
while let Some(val) = iter.next_back() {
i -= 1;
if f(val)? == Ordering::Equal {
return Ok(Some(i));
}
}
Ok(None)
}

pub fn binary_search_by<F>(
Expand Down

0 comments on commit 94a347c

Please sign in to comment.