-
Notifications
You must be signed in to change notification settings - Fork 0
/
faststack.nim
408 lines (309 loc) · 9.51 KB
/
faststack.nim
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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
# FastStack
# Copyright (c) 2016 Vladar
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# Vladar vladar4@gmail.com
## FastStack is dynamically resizable data structure
## optimized for fast iteration over the large arrays
## of similar elements avoiding memory fragmentation
## (e.g., update and rendering cycles of a game scene).
##
## ``Note:`` the indexes of items here are not set in stone,
## could change after ``push``, ``inject``, or ``eject`` operations,
## and may not start with `0`.
##
type
FastStack*[T] = ref object of RootObj
head, tail, size, growth: int
body: ptr T
template `+`[T](p: ptr T, off: int): ptr T =
cast[ptr T](cast[ByteAddress](p) +% off * sizeof(T))
template `[]`[T](p: ptr T, off: int): T =
(p + off)[]
template`[]=`[T](p: ptr T, off: int, val: T) =
(p + off)[] = val
proc init*[T](x: FastStack[T], size: int) =
## Initializer. Resets ``x``.
##
## ``size`` Initial size. Must be greater than `0`.
##
assert(size > 0)
x.head = 0
x.tail = 0
x.size = size
x.growth = size
if not x.body.isNil:
dealloc(x.body)
x.body = cast[ptr T](alloc0(size * sizeof(T)))
proc free*[T](x: FastStack[T]) =
## Finalizer. ``MUST`` be called to deallocate the memory.
##
if not x.body.isNil:
dealloc(x.body)
x.body = nil
proc flush*[T](x: FastStack[T]) =
## Discard all items.
##
x.head = 0
x.tail = 0
proc reset*[T](x: FastStack[T]) =
## Discard all items and reset to ``growth`` size.
##
x.init(x.growth)
proc newFastStack*[T](size: int): FastStack[T] =
## Constructor.
##
## ``size`` Initial size. Must be greater than `0`.
##
## It is best to set the maximum possible size
## to avoid additional memory reallocations.
##
assert(size > 0)
new result, free[T]
init result, size
proc len*(x: FastStack): int {.inline.} =
## ``Return`` the number of stored items.
##
x.tail - x.head
proc growth*(x: FastStack): int {.inline.} =
## ``Return`` the current growth value
## (for how much units ``x`` will reallocate if needed).
##
x.growth
proc `growth=`*(x: FastStack, value: int) {.inline.} =
## Set a new growth ``value``
## (for how much units ``x`` will reallocate if needed).
##
## Must be greater than `0`.
##
assert(value > 0)
x.growth = value
proc grow[T](x: FastStack[T]) =
assert(x.size <= (high(int) - x.growth)) # check for the integer limit
x.size += x.growth
x.body = cast[ptr T](realloc(x.body, x.size * sizeof(T)))
proc add*[T](x: FastStack[T], item: T) =
## Add a new ``item`` to the end of ``x``.
##
if x.tail > 0:
# the body is not empty
if x.tail >= x.size:
# the tail reached the end, need to grow
x.grow()
# add new item
x.body[x.tail] = item
inc x.tail
proc pop*[T](x: FastStack[T]): T =
## ``Return`` the last item and remove it from ``x``.
##
if x.tail < 1:
# the body is empty
return
dec x.tail
return x.body[x.tail]
proc shiftRight[T](x: FastStack[T], start: int) =
if x.tail >= x.size:
x.grow()
for idx in countdown(x.tail, start + 1):
x.body[idx] = x.body[idx - 1]
inc x.tail
proc shiftLeft[T](x: FastStack[T], start: int) =
for idx in start..(x.tail - 1):
x.body[idx] = x.body[idx + 1]
dec x.tail
proc splitLeft[T](x: FastStack[T], start: int) =
assert(x.head > 0)
for idx in (x.head - 1)..(start - 2):
x.body[idx] = x.body[idx + 1]
dec x.head
proc push*[T](x: FastStack[T], item: T) =
## Add a new ``item`` to the start of ``x``.
##
## Slow operation.
##
if x.tail > 0:
# the body is not empty
if x.head < 1:
# there isn't any free space in the start
shiftRight(x, x.head)
else:
# there is a free space in the start
dec x.head
# add new item
x.body[x.head] = item
proc pull*[T](x: FastStack[T]): T =
## ``Return`` the first item and remove it from ``x``.
##
if x.len < 1:
# the body is empty
return
result = x.body[x.head]
inc x.head
proc indexIsValid*[T](x: FastStack[T], index: int): bool {.inline.} =
## ``Return`` `true` if ``index`` is valid, `false` otherwise.
##
(index >= x.head) and (index < x.tail)
proc inject*[T](x: FastStack[T], value: T, index: int) =
## Inject a new ``value`` into the index ``i``
## shifting other items to the right starting with ``i``.
##
## Slow operation.
##
if index == x.head:
x.push(value)
return
if x.indexIsValid(index):
if x.head > 0:
# there is a free space in the start
splitLeft(x, index)
else:
# there isn't any free space in the start
shiftRight(x, index)
# after
x.body[index] = value
else:
raise newException(IndexError, "Index " & $index & " is out of bounds.")
proc eject*[T](x: FastStack[T], index: int): T =
## ``Return`` a value stored under the index ``i``
## and remove it from ``x``.
##
## Slow operation.
##
if index == x.head:
return x.pull()
if index == (x.tail - 1):
return x.pop()
if x.indexIsValid(index):
result = x.body[index]
shiftLeft(x, index)
else:
raise newException(IndexError, "Index " & $index & " is out of bounds.")
template iteratePairs() =
for idx in x.head..(x.tail - 1):
yield (idx, x.body[idx])
template iterate() =
for idx in x.head..(x.tail - 1):
yield x.body[idx]
iterator pairs*[T](x: FastStack[T]): tuple [key: int, val: T] {.inline.} =
## Iterates over each item. Yields ``(index, o[index])`` pairs.
##
iteratePairs()
iterator mpairs*[T](x: FastStack[T]): tuple [key: int, val: var T] {.inline.} =
## Iterates over each item. Yields ``(index, o[index])`` pairs.
## ``o[index]`` can be modified.
##
iteratePairs()
iterator items*[T](x: FastStack[T]): T {.inline.} =
## Iterate over each item.
##
iterate()
iterator mitems*[T](x: FastStack[T]): var T {.inline.} =
## Iterates over each item so that you can modify the yielded value.
##
iterate()
proc firstKey*(x: FastStack): int {.inline.} =
## ``Return`` the index of the first item or `-1` if there's no items.
##
if x.len < 1:
return -1
return x.head
proc firstVal*[T](x: FastStack[T]): T {.inline.} =
## ``Return`` the value of the first item.
##
if x.len < 1:
return
return x.body[x.head]
proc mFirstVal*[T](x: FastStack[T]): var T {.inline.} =
## ``Return`` the value of the first item so that you can modify it.
##
if x.len < 1:
return
return x.body[x.head]
proc lastKey*(x: FastStack): int {.inline.} =
## ``Return`` the index of the last item or `-1` if there's no items.
##
if x.len < 1:
return -1
return x.tail - 1
proc lastVal*[T](x: FastStack[T]): T {.inline.} =
## ``Return`` the value of the last item.
##
if x.len < 1:
return
return x.body[x.tail - 1]
proc mLastVal*[T](x: FastStack[T]): var T {.inline.} =
## ``Return`` the value of the last item so you can modify it.
##
if x.len < 1:
return
return x.body[x.tail - 1]
proc `$`*[T](x: FastStack[T]): string =
## The stringify operator.
##
result = "["
for item in x.items:
if result.len > 1: result.add(", ")
result.add($item)
result.add("]")
proc find*[T](x: FastStack[T], value: T): int =
## ``Return`` the index of the first appearance of a ``value``,
## or `-1` if there is no such value.
##
## ``Note:`` the index may be changed after following operations:
## ``push``, ``inject``, ``eject``.
##
for pair in x.pairs:
if pair.val == value:
return pair.key
return -1
proc contains*[T](x: FastStack[T], value: T): bool {.inline.} =
## ``Return`` `true` if ``x`` contains `value`.
##
x.find(value) > -1
proc `[]`*[T](x: FastStack[T], index: int): T =
## ``Return`` a value stored under the index ``i``.
##
## ``Note:`` the index may be changed after following operations:
## ``push``, ``inject``, ``eject``.
##
if x.indexIsValid(index):
return x.body[index]
raise newException(IndexError, "Index " & $index & " is out of bounds.")
proc `[]=`*[T](x: FastStack[T], index: int, value: T) =
## Overwrite the `value` stored under the index `i`.
##
## ``Note:`` the index may be changed after following operations:
## ``push``, ``inject``, ``eject``.
##
if x.indexIsValid(index):
x.body[index] = value
return
raise newException(IndexError, "Index " & $index & " is out of bounds.")
proc dump*[T](x: FastStack[T]): string =
## Debugging function.
##
## ``Return`` all contents of ``x`` as string.
##
result = "" & repr(x) & "["
for idx in 0..(x.size-1):
if idx > 0:
result &= ", "
result &= $x.body[idx]
result &= "]"