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