Skip to main content

low_luajit/lua/
gc.rs

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