python/list/
list.rs

1//! NOT VISIBLE TO THE docs.rs
2//! this is only for lib.rs
3//! it wasnt visible because this module somehow was private
4//! now its visible
5
6#![allow(
7    dead_code,
8    unused_imports,
9    unused_variables,
10    unused_macros,
11    unused_assignments,
12    unused_mut,
13    non_snake_case,
14    unused_must_use
15)]
16
17
18use std::collections::VecDeque;
19
20use std::fmt;
21
22use std::error;
23
24use std::ops::Add;
25use std::ops::Deref;
26
27use std::str::FromStr;
28
29
30use crate::_Object;
31use crate::Object;
32use crate::Int;
33use crate::Float;
34use crate::_String;
35use crate::Char;
36use crate::Bool;
37use crate::type_of;
38use crate::print;
39
40
41use super::Append;
42use crate::Iterable;
43
44// mod object;
45// use object::Object;
46
47
48/// the main component
49///
50/// contens structure of good docs
51/// [short sentence explaining what it is]
52///
53/// [more detailed explanation]
54///
55/// [at least one code example that users can copy/paste to try it]
56///
57/// [even more advanced explanations if necessary]
58// #[derive(Copy, Clone)]
59pub struct List {
60    /// _list which holds all the python objects together
61    pub _list: VecDeque<Object>,
62}
63
64/// if you want to use max(&list) you need the impl for &List
65/// how comes that for Object work by default
66impl Iterable for List {
67    fn __len__(&self) -> usize {
68        self._list.len()
69    }
70}
71
72// impl Iterable for &List {
73//     fn __len__(&self) -> usize {
74//         self._list.len()
75//     }
76// }
77
78
79// TODO implement PartialEq for List
80// impl PartialEq for List {
81//     fn eq(&self, _List: &Self) -> bool {
82//         for (o1, o2) in _List._list.iter().zip() {
83//             if o1 == o2 {
84//                 true
85//             }
86//         }
87//         false
88//     }
89
90//     fn ne(&self, other: &Self) -> bool {
91//         for (o1, o2) in _List._list.iter().zip() {
92//             if o1 != o2 {
93//                 true
94//             }
95//         }
96//         false
97//     }
98// }
99
100
101/// its implementation
102impl List {
103    /// new function
104    pub fn new() -> List {
105        List {
106            _list: VecDeque::new(),
107        }
108    }
109
110    /// check whether or not its a char or string type inside list
111    /// designed and created for __repr__
112    fn _contains_char_or_string(&self) -> bool {
113        for _object in &self._list {
114            match _object {
115                Object::String(_object) => {
116                    return true;
117                },
118                Object::Char(_object) => {
119                    return true;
120                },
121                _ => {},
122            }
123        }
124        false
125    }
126}
127
128
129impl Default for List {
130    fn default() -> Self {
131        Self::new()
132    }
133}
134
135
136impl _Object for List {
137    // >>>  x = ['hello', '1', '2', '3', '1', '2', '3', 123, 123, ['w', 'o', 'r', 'k', 'i', 'n', 'g'], 123.123, 123.123, 123.123, 'asdasd', ['s', 'o', 'm', 'e', 't', 'h', 'i', 'n',
138    // ... 'g'], 'python string', True, False, False]
139    // >>> x
140    // ['hello', '1', '2', '3', '1', '2', '3', 123, 123, ['w', 'o', 'r', 'k', 'i', 'n', 'g'], 123.123, 123.123, 123.123, 'asdasd', ['s', 'o', 'm', 'e', 't', 'h', 'i', 'n', 'g'], 'python string', True, False, False]
141    // >>> repr(x)
142    // "['hello', '1', '2', '3', '1', '2', '3', 123, 123, ['w', 'o', 'r', 'k', 'i', 'n', 'g'], 123.123, 123.123, 123.123, 'asdasd', ['s', 'o', 'm', 'e', 't', 'h', 'i', 'n', 'g'], 'python string', True, False, False]"
143    // >>> repr(["asd"])
144    // "['asd']"
145    // >>> repr(['asd'])
146    // "['asd']"
147    // >>> repr([123, 123])
148    // '[123, 123]'
149
150    /// rules for __repr__
151    /// daca nu ai string or char -> '[]' (single quotes outsiode)
152    /// daca ai string or char -> "[]" (double quotes outside)
153    fn __repr__(&self) -> String {
154        if self._contains_char_or_string() {
155            format!("\"{}\"", self.__str__())
156        } else {
157            format!("'{}'", self.__str__())
158        }
159    }
160
161    /// __str__ documentation in List
162    fn __str__(&self) -> String {
163        // if list is empty then we print '[]'
164        if self._list.is_empty() {
165            return String::from("[]");
166        }
167
168
169        let mut string_representation = String::new();
170        let zero = self._list.get(0).unwrap();
171        // print the first element of the list
172        match zero {
173            Object::String(_object) => {
174                string_representation.push_str(
175                    format!("[{}", _object.__repr__()).as_str(),
176                );
177            },
178            Object::Char(_object) => {
179                string_representation.push_str(
180                    format!("[{}", _object.__repr__()).as_str(),
181                );
182            },
183            _ => {
184                string_representation
185                    .push_str(format!("[{}", zero).as_str());
186            },
187        };
188
189        // print the other elements of the list but from index = 1
190        for _object in self._list.iter().skip(1) {
191            match _object {
192                Object::String(_object) => {
193                    string_representation.push_str(
194                        format!(", {}", _object.__repr__()).as_str(),
195                    );
196                },
197                Object::Char(_object) => {
198                    string_representation.push_str(
199                        format!(", {}", _object.__repr__()).as_str(),
200                    );
201                },
202                _ => {
203                    string_representation
204                        .push_str(format!(", {}", _object).as_str());
205                },
206            };
207        }
208        string_representation.push(']');
209        string_representation
210    }
211}
212
213
214impl fmt::Display for List {
215    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
216        // if list is empty then we print '[]'
217        if self._list.is_empty() {
218            write!(f, "[]");
219            return Ok(());
220        }
221
222
223        let zero = self._list.get(0).unwrap();
224        // print the first element of the list
225        match zero {
226            Object::String(obj) => write!(f, "[{}", obj.__repr__()),
227            Object::Char(obj) => write!(f, "[{}", obj.__repr__()),
228            _ => write!(f, "[{}", zero),
229        };
230
231        // print the other elements of the list but from index = 1
232        for _object in self._list.iter().skip(1) {
233            match _object {
234                Object::String(obj) => {
235                    write!(f, ", {}", obj.__repr__())
236                },
237                Object::Char(obj) => {
238                    write!(f, ", {}", obj.__repr__())
239                },
240                _ => write!(f, ", {}", _object),
241            };
242
243            // ostream.push_str(&_object.fmt(f).unwrap());
244        }
245        write!(f, "]")
246    }
247}
248
249impl fmt::Debug for List {
250    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
251        // if list is empty then we print '[]'
252        if self._list.is_empty() {
253            write!(f, "[]");
254            return Ok(());
255        }
256
257
258        let zero = self._list.get(0).unwrap();
259        // print the first element of the list
260        match zero {
261            Object::String(obj) => write!(f, "[{:?}", obj.__repr__()),
262            Object::Char(obj) => write!(f, "[{:?}", obj.__repr__()),
263            _ => write!(f, "[{:?}", zero),
264        };
265
266        // print the other elements of the list but from index = 1
267        for _object in self._list.iter().skip(1) {
268            match _object {
269                Object::String(obj) => {
270                    write!(f, ", {}", obj.__repr__())
271                },
272                Object::Char(obj) => {
273                    write!(f, ", {}", obj.__repr__())
274                },
275                _ => write!(f, ", {}", _object),
276            };
277
278            // ostream.push_str(&_object.fmt(f).unwrap());
279        }
280        write!(f, "]")
281    }
282}
283
284
285impl Deref for List {
286    type Target = VecDeque<Object>;
287
288    /// usage
289    /// for o in python_list.iter() {
290    ///     print(o)
291    /// }
292    fn deref(&self) -> &Self::Target {
293        &self._list
294    }
295}
296
297
298impl From<&str> for List {
299    fn from(_static_string: &str) -> List {
300        List {
301            _list: _static_string
302                .chars()
303                .map(|c| Object::Char(Char::from(c)))
304                .collect(),
305        }
306    }
307}
308
309
310/// creates a list from string
311/// example
312/// let list = List::from("q23123123".to_string())
313/// or
314/// let list = List::from(String::from("q23123123"))
315impl From<&String> for List {
316    fn from(_string: &String) -> List {
317        List {
318            _list: _string
319                .chars()
320                .map(|c| Object::Char(Char::from(c)))
321                .collect(),
322        }
323    }
324}
325
326impl From<String> for List {
327    fn from(_string: String) -> List {
328        List {
329            _list: _string
330                .chars()
331                .map(|c| Object::Char(Char::from(c)))
332                .collect(),
333        }
334    }
335}
336
337impl From<i32> for List {
338    // include markdown file as doc comment for this function
339    #[doc = include_str!("../../docs/python_list/showcase.md")]
340    fn from(_integer: i32) -> List {
341        let mut vector_deque = VecDeque::new();
342        vector_deque
343            .push_back(Object::Int32(Int::<i32>::new(_integer)));
344        List {
345            _list: vector_deque,
346        }
347    }
348}
349
350
351impl From<&List> for List {
352    /// creates a list from another list; like copy constructor
353    fn from(_list: &List) -> List {
354        let mut temp_list: VecDeque<Object> = VecDeque::new();
355        for _object in &_list._list {
356            // temp_list.push_back(_object);
357        }
358        List {
359            _list: temp_list
360        }
361    }
362}
363
364
365impl FromStr for List {
366    type Err = Box<dyn error::Error>;
367
368    fn from_str(_static_str: &str) -> Result<Self, Self::Err> {
369        Ok(List::from(_static_str))
370    }
371}
372
373
374impl FromIterator<i32> for List {
375    fn from_iter<T: IntoIterator<Item = i32>>(
376        _integer_iterator: T,
377    ) -> Self {
378        let mut integer_list = List::new();
379        for integer in _integer_iterator {
380            integer_list.append_back(integer);
381        }
382        integer_list
383    }
384}
385
386
387impl FromIterator<String> for List {
388    fn from_iter<T: IntoIterator<Item = String>>(
389        _string_iterator: T,
390    ) -> Self {
391        let mut string_list = List::new();
392        for _string in _string_iterator {
393            string_list.append_back(_string);
394        }
395        string_list
396    }
397}
398
399
400/// list concatenation
401impl Add for List {
402    type Output = List;
403
404    /// list1 + list2 == list3
405    fn add(self, rhs: Self) -> Self::Output {
406        let mut new_list = List::new();
407        for _object in self._list {
408            new_list.append_back(_object);
409        }
410        for _object in rhs._list {
411            new_list.append_back(_object);
412        }
413        new_list
414    }
415}