low_luajit/lua/gc.rs
1#![allow(clippy::must_use_candidate)]
2
3use crate::{LuaState, ffi::{self, lua_gc}};
4
5/// Garbage collector handling functions.
6///
7/// See [ยง2.10](https://www.lua.org/manual/5.1/manual.html#2.10) for more information on the garbage collector.
8impl LuaState {
9 /// Generic garbage collector controller function.
10 ///
11 /// This function's behavior changes based on the given `what`. Use the `LUA_GC*` constants found in the [`ffi`] module.
12 ///
13 /// Invalid `what` values return `-1`.
14 #[inline]
15 pub fn gc(&self, what: i32, data: i32) -> i32 {
16 // SAFETY: self.as_ptr() is always valid.
17 unsafe { lua_gc(self.as_ptr(), what, data) }
18 }
19
20 /// Stops the garbage collector.
21 #[inline]
22 pub fn gc_stop(&self) {
23 // SAFETY: self.0 is always valid.
24 self.gc(ffi::LUA_GCSTOP, 0);
25 }
26
27 /// Restarts the garbage collector.
28 #[inline]
29 pub fn gc_restart(&self) {
30 // SAFETY: self.0 is always valid.
31 self.gc(ffi::LUA_GCRESTART, 0);
32 }
33
34 /// Performs a full garbage collection cycle.
35 #[inline]
36 pub fn gc_collect(&self) {
37 // SAFETY: self.0 is always valid.
38 self.gc(ffi::LUA_GCCOLLECT, 0);
39 }
40
41 /// Returns the amount of memory in use by Lua, in Kbytes.
42 #[inline]
43 #[must_use]
44 pub fn gc_count(&self) -> i32 {
45 // SAFETY: self.0 is always valid.
46 self.gc(ffi::LUA_GCCOUNT, 0)
47 }
48
49 /// Returns the remainder of dividing the current amount of bytes of memory in use by Lua by 1024.
50 #[inline]
51 #[must_use]
52 pub fn gc_count_b(&self) -> i32 {
53 // SAFETY: self.0 is always valid.
54 self.gc(ffi::LUA_GCCOUNTB, 0)
55 }
56
57 /// Performs an incremental step of garbage collection.
58 ///
59 /// `size` controls the step "size" in a non-specific way (larger values -> larger steps).
60 ///
61 /// This function returns `true` if it finished a garbage collection cycle, `false` otherwise.
62 #[inline]
63 pub fn gc_step(&self, size: i32) -> bool {
64 // SAFETY: self.0 is always valid.
65 self.gc(ffi::LUA_GCSTEP, size) != 0
66 }
67
68 /// Sets `pause` as the new pause value of the collector, returning the previous value.
69 #[inline]
70 pub fn gc_set_pause(&self, pause: i32) -> i32 {
71 // SAFETY: self.0 is always valid.
72 self.gc(ffi::LUA_GCSETPAUSE, pause)
73 }
74
75 /// Sets `step_multiplier` as the new step multiplier value of the collector, returning the previous value.
76 #[inline]
77 pub fn gc_set_step_multiplier(&self, step_multiplier: i32) -> i32 {
78 // SAFETY: self.0 is always valid.
79 self.gc(ffi::LUA_GCSETSTEPMUL, step_multiplier)
80 }
81
82 /// Returns `true` if the garbage collector is currently running, `false` otherwise.
83 #[inline]
84 #[must_use]
85 pub fn gc_is_running(&self) -> bool {
86 // SAFETY: self.0 is always valid.
87 self.gc(ffi::LUA_GCISRUNNING, 0) != 0
88 }
89}