1use crate::hashmap;
2use crate::mem::Object;
3use std::collections::HashMap;
4
5pub type Stack = Vec<Object>;
6type GStack = Vec<Stack>;
7type GHash = Vec<HashMap<String, Object>>;
8
9#[derive(Clone, Debug)]
10pub struct StackMemory {
11 gstack: GStack,
12}
13
14#[derive(Clone, Debug)]
15pub struct HashMemory {
16 ghashs: GHash,
17}
18
19impl StackMemory {
20 pub fn new() -> Self {
21 Self {
22 gstack: vec![vec![]],
23 }
24 }
25
26 pub fn pop(&mut self) -> Option<Object> {
28 for stack in self.gstack.iter_mut().rev() {
29 match stack.pop() {
30 Some(a) => return Some(a.clone()),
31 None => (),
32 }
33 }
34 None
35 }
36 pub fn push(&mut self, a: Object) {
37 if let Some(last) = self.gstack.last_mut() {
38 last.push(a);
39 }
40 }
41 pub fn push_glob(&mut self, a: Object) {
42 if let Some(first) = self.gstack.first_mut() {
43 first.push(a);
44 }
45 }
46 pub fn push_ret(&mut self, a: Object) {
47 let glen = self.gstack.len();
48 if let Some(ret) = self.gstack.get_mut(glen - 2) {
49 ret.push(a);
50 }
51 }
52 pub fn new_stack(&mut self) {
53 self.gstack.push(vec![]);
54 }
55 pub fn del_stack(&mut self) -> Option<Stack> {
56 self.gstack.pop()
57 }
58
59 pub fn len(&self) -> usize {
61 let mut l: usize = 0;
62 for stack in self.gstack.iter() {
63 l += stack.len();
64 }
65 l
66 }
67
68 pub fn iter_vec(&mut self) -> Vec<Object> {
70 let mut s = vec![];
71 for stack in self.gstack.iter_mut() {
72 s.append(stack);
73 }
74 s
75 }
76}
77
78impl HashMemory {
79 pub fn new() -> Self {
80 Self {
81 ghashs: vec![hashmap! {}],
82 }
83 }
84
85 pub fn remove(&mut self, key: String) -> Option<Object> {
87 for hash in self.ghashs.iter_mut().rev() {
88 match hash.remove(&key) {
89 Some(a) => return Some(a.clone()),
90 None => (),
91 }
92 }
93 None
94 }
95
96 pub fn insert(&mut self, key: String, val: Object) {
97 if let Some(last) = self.ghashs.last_mut() {
98 last.insert(key, val);
99 }
100 }
101
102 pub fn insert_glob(&mut self, key: String, val: Object) {
103 if let Some(first) = self.ghashs.first_mut() {
104 first.insert(key, val);
105 }
106 }
107
108 pub fn new_hash(&mut self) {
109 self.ghashs.push(hashmap! {});
110 }
111
112 pub fn del_hash(&mut self) -> Option<HashMap<String, Object>> {
113 self.ghashs.pop()
114 }
115
116 pub fn get(&mut self, key: &String) -> Option<&Object> {
117 for hash in self.ghashs.iter().rev() {
118 match hash.get(key) {
119 Some(a) => return Some(a),
120 None => (),
121 }
122 }
123 None
124 }
125
126 pub fn get_mut(&mut self, key: &String) -> Option<&mut Object> {
127 for hash in self.ghashs.iter_mut().rev() {
128 match hash.get_mut(key) {
129 Some(a) => return Some(a),
130 None => (),
131 }
132 }
133 None
134 }
135
136 pub fn into_keys(&mut self) -> Vec<String> {
137 let mut s: Vec<String> = vec![];
138 for i in self.ghashs.iter_mut().rev() {
139 s.append(&mut i.clone().into_keys().collect::<Vec<String>>());
140 }
141 s
142 }
143}