Skip to content

Commit 0851048

Browse files
committed
Add set() method to Deque.
1 parent 7df83b6 commit 0851048

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

src/deque.rs

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,19 @@ impl<T: Serialize + DeserializeOwned> Deque<T> {
179179
.map(Some)
180180
}
181181

182+
/// Sets the value at the given position in the queue. Returns [`StdError::NotFound`] if index is out of bounds
183+
pub fn set(&self, storage: &mut dyn Storage, pos: u32, value: &T) -> StdResult<()> {
184+
let head = self.head(storage)?;
185+
let tail = self.tail(storage)?;
186+
187+
if pos >= calc_len(head, tail) {
188+
// out of bounds
189+
return Err(StdError::not_found(format!("deque position {}", pos)));
190+
}
191+
192+
self.set_unchecked(storage, pos, value)
193+
}
194+
182195
/// Tries to get the value at the given position
183196
/// Used internally
184197
fn get_unchecked(&self, storage: &dyn Storage, pos: u32) -> StdResult<Option<T>> {
@@ -676,4 +689,35 @@ mod tests {
676689
"out of bounds access should return None"
677690
);
678691
}
692+
693+
#[test]
694+
fn set() {
695+
let mut store = MockStorage::new();
696+
let deque = Deque::new("test");
697+
698+
deque.push_back(&mut store, &1u32).unwrap();
699+
deque.push_back(&mut store, &2).unwrap();
700+
701+
deque.set(&mut store, 1, &3).unwrap();
702+
703+
assert_eq!(deque.get(&store, 1).unwrap(), Some(3));
704+
assert_eq!(deque.back(&store).unwrap(), Some(3));
705+
assert_eq!(
706+
deque.get(&store, 2).unwrap(),
707+
None,
708+
"out of bounds access should return None"
709+
);
710+
711+
assert!(
712+
matches!(deque.set(&mut store, 2, &3), Err(StdError::NotFound { .. })),
713+
"setting value at an out of bounds index should error"
714+
);
715+
716+
assert_eq!(deque.pop_back(&mut store), Ok(Some(3)));
717+
718+
assert!(
719+
matches!(deque.set(&mut store, 1, &3), Err(StdError::NotFound { .. })),
720+
"setting value at an out of bounds index should error"
721+
);
722+
}
679723
}

0 commit comments

Comments
 (0)