forked from Matway/mpl-sl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
IntrusiveStack.mpl
168 lines (145 loc) · 3.34 KB
/
IntrusiveStack.mpl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
# Copyright (C) Matway Burkow
#
# This repository and all its contents belong to Matway Burkow (referred here and below as "the owner").
# The content is for demonstration purposes only.
# It is forbidden to use the content or any part of it for any purpose without explicit permission from the owner.
# By contributing to the repository, contributors acknowledge that ownership of their work transfers to the owner.
"control.Ref" use
"control.assert" use
"control.dup" use
"control.nil?" use
"control.when" use
"control.while" use
# Intrusive singly linked list
# Requires item objects to have field 'prev' of type '[Item] Mref'
IntrusiveStack: [
Item:;
{
SCHEMA_NAME: "IntrusiveStack<" @Item schemaName & ">" & virtual;
INIT: [clear];
DIE: [];
empty?: [@last nil?];
append: [
item:;
@last @item.@prev.set
@item !last
];
clear: [@Item !last];
cutAllIf: [
body:;
count: 0;
empty? ~ [
item: @last;
skip: FALSE;
@item @body call [
[
count 1 + !count
@item.prev !item
@item nil? [
@Item !last
TRUE !skip
FALSE
] [
@item @body call dup ~ [
@item !last
] when
] if
] loop
] when
[skip ~] [
firstToKeep: @item;
[
@item.prev !item
@item nil? [
TRUE !skip
FALSE
] [
@item @body call ~ dup [
@item !firstToKeep
] when
] if
] loop
skip ~ [
[
count 1 + !count
@item.prev !item
@item nil? [
@Item @firstToKeep.@prev.set
TRUE !skip
FALSE
] [
@item @body call dup ~ [
@item @firstToKeep.@prev.set
] when
] if
] loop
] when
] while
] when
count
];
cutLast: [
[empty? ~] "stack is empty" assert
@last.prev !last
];
cutLastIf: [
body:;
count: 0;
empty? ~ [
item: @last;
@item @body call [
1 !count
cutLast
] [
[
next: @item;
@item.prev !item
@item nil? [FALSE] [
@item @body call ~ dup ~ [
1 !count
@item.prev @next.@prev.set
] when
] if
] loop
] if
] when
count
];
popLast: [
[empty? ~] "stack is empty" assert
@last
cutLast
];
reverse: [
empty? ~ [
item: @last.prev;
@item nil? ~ [
next: @last;
@Item @next.@prev.set
[
prev: @item.prev;
@next @item.@prev.set
@prev nil? ~ dup [
@item !next
@prev !item
] when
] loop
@item !last
] when
] when
];
reverseIter: [{
Item: virtual @Item Ref;
item: @last;
next: [
@item nil? [@Item FALSE] [
@item
@item.prev !item
TRUE
] if
];
}];
Item: @Item Ref virtual;
last: @Item;
}
];