Skip to content

Commit 0b5ef91

Browse files
committed
Update Lua 5.2 FFI bindings (add buffer manipulation, etc)
1 parent a162b0c commit 0b5ef91

1 file changed

Lines changed: 62 additions & 1 deletion

File tree

mlua-sys/src/lua52/lauxlib.rs

Lines changed: 62 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,67 @@ pub unsafe fn luaL_loadbuffer(L: *mut lua_State, s: *const c_char, sz: usize, n:
173173
luaL_loadbufferx(L, s, sz, n, ptr::null())
174174
}
175175

176+
#[inline(always)]
177+
pub unsafe fn luaL_opt<T>(
178+
L: *mut lua_State,
179+
f: unsafe extern "C-unwind" fn(*mut lua_State, c_int) -> T,
180+
n: c_int,
181+
d: T,
182+
) -> T {
183+
if lua::lua_isnoneornil(L, n) != 0 {
184+
d
185+
} else {
186+
f(L, n)
187+
}
188+
}
189+
176190
//
177-
// TODO: Generic Buffer Manipulation
191+
// Generic Buffer Manipulation
178192
//
193+
194+
// The buffer size used by the lauxlib buffer system.
195+
// The "16384" workaround is taken from the LuaJIT source code.
196+
#[rustfmt::skip]
197+
pub const LUAL_BUFFERSIZE: usize = if libc::BUFSIZ > 16384 { 8192 } else { libc::BUFSIZ as usize };
198+
199+
#[repr(C)]
200+
pub struct luaL_Buffer {
201+
pub b: *mut c_char, // buffer address
202+
pub size: usize, // buffer size
203+
pub n: usize, // number of characters in buffer
204+
pub L: *mut lua_State,
205+
pub initb: [c_char; LUAL_BUFFERSIZE], // initial buffer space
206+
}
207+
208+
#[cfg_attr(all(windows, raw_dylib), link(name = "lua52", kind = "raw-dylib"))]
209+
unsafe extern "C-unwind" {
210+
pub fn luaL_buffinit(L: *mut lua_State, B: *mut luaL_Buffer);
211+
pub fn luaL_prepbuffsize(B: *mut luaL_Buffer, sz: usize) -> *mut c_char;
212+
pub fn luaL_addlstring(B: *mut luaL_Buffer, s: *const c_char, l: usize);
213+
pub fn luaL_addstring(B: *mut luaL_Buffer, s: *const c_char);
214+
pub fn luaL_addvalue(B: *mut luaL_Buffer);
215+
pub fn luaL_pushresult(B: *mut luaL_Buffer);
216+
pub fn luaL_pushresultsize(B: *mut luaL_Buffer, sz: usize);
217+
pub fn luaL_buffinitsize(L: *mut lua_State, B: *mut luaL_Buffer, sz: usize) -> *mut c_char;
218+
}
219+
220+
// Macro implementations as inline functions
221+
222+
#[inline(always)]
223+
pub unsafe fn luaL_prepbuffer(B: *mut luaL_Buffer) -> *mut c_char {
224+
luaL_prepbuffsize(B, LUAL_BUFFERSIZE)
225+
}
226+
227+
#[inline(always)]
228+
pub unsafe fn luaL_addchar(B: *mut luaL_Buffer, c: c_char) {
229+
if (*B).n >= (*B).size {
230+
luaL_prepbuffsize(B, 1);
231+
}
232+
*(*B).b.add((*B).n) = c;
233+
(*B).n += 1;
234+
}
235+
236+
#[inline(always)]
237+
pub unsafe fn luaL_addsize(B: *mut luaL_Buffer, n: usize) {
238+
(*B).n += n;
239+
}

0 commit comments

Comments
 (0)