python_ast/pytypes.rs
1use std::{collections::VecDeque, iter::Iterator};
2
3/// The Python list type. Generally, it's used with a `dyn Object` trait object to allow
4/// for arbitrary contents. Since Rust doesn't have a native type that supports mixed type
5/// lists, we need to invent something.
6pub type List<T> = VecDeque<Box<T>>;
7
8/// An interface for any data structure that works like a Python List.
9pub trait ListLike<T> {
10 fn append(&mut self, x: T);
11 fn insert(&mut self, i: usize, x: T);
12
13 fn extend(&mut self, iterable: Box<dyn Iterator<Item = T>>) {
14 for item in iterable {
15 self.append(item);
16 }
17 }
18
19 //fn remove(&mut self, x: Box<T>);
20}
21
22impl<T: Iterator> ListLike<T> for List<T> {
23 fn append(&mut self, x: T) {
24 self.push_back(Box::new(x));
25 }
26
27 fn insert(&mut self, i: usize, x: T) {
28 VecDeque::insert(self, i, Box::new(x))
29 }
30
31 // An important diffference between the Pythonic List and the Rust VecDeque is that
32 // VecDeque.remove() takes an index into the array, whereas Python List.remove() takes
33 // a *value*, searches the list for it, and removes the first instance of that.
34 /*fn remove(&mut self, x: Box<T>) {
35 match self.iter().position(|&i| i.into_inner() == x.into_inner()) {
36 Some(p) => VecDeque::remove(self, p).or_else(0),
37 _ => return,
38 };
39 }*/
40}