Skip to content

Commit 9a512ae

Browse files
committed
Refactor: simplify and deduplicate code across modules
1 parent 29e59cf commit 9a512ae

15 files changed

Lines changed: 85 additions & 136 deletions

File tree

mlua_derive/src/userdata/userdata_impl.rs

Lines changed: 14 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -301,17 +301,16 @@ pub fn userdata_impl(attr: TokenStream, item: TokenStream) -> TokenStream {
301301
}
302302
let const_name = &const_item.ident;
303303
let lua_name = lua_attr.name(const_name);
304-
if lua_attr.meta {
305-
let tokens = quote! {
304+
let tokens = if lua_attr.meta {
305+
quote! {
306306
registry.add_meta_field(#lua_name, #type_path::#const_name);
307-
};
308-
registration_calls.push(with_cfg(tokens, &const_item.attrs));
307+
}
309308
} else {
310-
let tokens = quote! {
309+
quote! {
311310
registry.add_field(#lua_name, #type_path::#const_name);
312-
};
313-
registration_calls.push(with_cfg(tokens, &const_item.attrs));
314-
}
311+
}
312+
};
313+
registration_calls.push(with_cfg(tokens, &const_item.attrs));
315314
}
316315
ImplItem::Fn(method) => {
317316
let lua_attr = try_compile!(parse_lua_attr(&method.attrs));
@@ -410,17 +409,16 @@ pub fn userdata_impl(attr: TokenStream, item: TokenStream) -> TokenStream {
410409
.into();
411410
}
412411
let lua_name = lua_attr.name(fn_name);
413-
if lua_attr.meta {
414-
let tokens = quote! {
412+
let tokens = if lua_attr.meta {
413+
quote! {
415414
registry.add_meta_field(#lua_name, #type_path::#fn_name());
416-
};
417-
registration_calls.push(with_cfg(tokens, &method.attrs));
415+
}
418416
} else {
419-
let tokens = quote! {
417+
quote! {
420418
registry.add_field(#lua_name, #type_path::#fn_name());
421-
};
422-
registration_calls.push(with_cfg(tokens, &method.attrs));
423-
}
419+
}
420+
};
421+
registration_calls.push(with_cfg(tokens, &method.attrs));
424422
continue;
425423
}
426424

src/chunk.rs

Lines changed: 4 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -401,14 +401,11 @@ impl Compiler {
401401
use std::os::raw::{c_char, c_int};
402402
use std::ptr;
403403

404-
let vector_lib = self.vector_lib.clone();
405-
let vector_lib = vector_lib.and_then(|lib| CString::new(lib).ok());
404+
let vector_lib = (self.vector_lib.as_deref()).and_then(|lib| CString::new(lib).ok());
406405
let vector_lib = vector_lib.as_ref();
407-
let vector_ctor = self.vector_ctor.clone();
408-
let vector_ctor = vector_ctor.and_then(|ctor| CString::new(ctor).ok());
406+
let vector_ctor = (self.vector_ctor.as_deref()).and_then(|ctor| CString::new(ctor).ok());
409407
let vector_ctor = vector_ctor.as_ref();
410-
let vector_type = self.vector_type.clone();
411-
let vector_type = vector_type.and_then(|t| CString::new(t).ok());
408+
let vector_type = (self.vector_type.as_deref()).and_then(|t| CString::new(t).ok());
412409
let vector_type = vector_type.as_ref();
413410

414411
macro_rules! vec2cstring_ptr {
@@ -740,11 +737,7 @@ impl Chunk<'_> {
740737
.unwrap_or(source);
741738

742739
let name = Self::convert_name(self.name.clone())?;
743-
let env = match &self.env {
744-
Ok(Some(env)) => Some(env),
745-
Ok(None) => None,
746-
Err(err) => return Err(err.clone()),
747-
};
740+
let env = self.env.as_ref().map_err(Error::clone)?.as_ref();
748741
self.lua.lock().load_chunk(Some(&name), env, None, &source)
749742
}
750743

src/conversion.rs

Lines changed: 14 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1117,36 +1117,23 @@ impl<L: FromLua, R: FromLua> FromLua for Either<L, R> {
11171117
#[inline]
11181118
fn from_lua(value: Value, lua: &Lua) -> Result<Self> {
11191119
let value_type_name = value.type_name();
1120-
// Try the left type first
1121-
match L::from_lua(value.clone(), lua) {
1122-
Ok(l) => Ok(Either::Left(l)),
1123-
// Try the right type
1124-
Err(_) => match R::from_lua(value, lua).map(Either::Right) {
1125-
Ok(r) => Ok(r),
1126-
Err(_) => Err(Error::from_lua_conversion(
1127-
value_type_name,
1128-
Self::type_name(),
1129-
None,
1130-
)),
1131-
},
1132-
}
1120+
L::from_lua(value.clone(), lua)
1121+
.map(Either::Left)
1122+
.or_else(|_| R::from_lua(value, lua).map(Either::Right))
1123+
.map_err(|_| Error::from_lua_conversion(value_type_name, Self::type_name(), None))
11331124
}
11341125

11351126
#[inline]
11361127
unsafe fn from_stack(idx: c_int, lua: &RawLua) -> Result<Self> {
1137-
match L::from_stack(idx, lua) {
1138-
Ok(l) => Ok(Either::Left(l)),
1139-
Err(_) => match R::from_stack(idx, lua).map(Either::Right) {
1140-
Ok(r) => Ok(r),
1141-
Err(_) => {
1142-
let state = lua.state();
1143-
let from_type_name = CStr::from_ptr(ffi::lua_typename(state, ffi::lua_type(state, idx)))
1144-
.to_str()
1145-
.unwrap_or("unknown");
1146-
let err = Error::from_lua_conversion(from_type_name, Self::type_name(), None);
1147-
Err(err)
1148-
}
1149-
},
1150-
}
1128+
L::from_stack(idx, lua)
1129+
.map(Either::Left)
1130+
.or_else(|_| R::from_stack(idx, lua).map(Either::Right))
1131+
.map_err(|_| {
1132+
let state = lua.state();
1133+
let from_type_name = CStr::from_ptr(ffi::lua_typename(state, ffi::lua_type(state, idx)))
1134+
.to_str()
1135+
.unwrap_or("unknown");
1136+
Error::from_lua_conversion(from_type_name, Self::type_name(), None)
1137+
})
11511138
}
11521139
}

src/debug.rs

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -99,10 +99,7 @@ impl<'a> Debug<'a> {
9999
DebugNames {
100100
name: ptr_to_lossy_str((*self.ar).name),
101101
#[cfg(not(feature = "luau"))]
102-
name_what: match ptr_to_str((*self.ar).namewhat) {
103-
Some("") => None,
104-
val => val,
105-
},
102+
name_what: ptr_to_str((*self.ar).namewhat).filter(|s| !s.is_empty()),
106103
#[cfg(feature = "luau")]
107104
name_what: None,
108105
}
@@ -379,9 +376,7 @@ impl std::ops::BitOr for HookTriggers {
379376
self.on_calls |= rhs.on_calls;
380377
self.on_returns |= rhs.on_returns;
381378
self.every_line |= rhs.every_line;
382-
if self.every_nth_instruction.is_none() && rhs.every_nth_instruction.is_some() {
383-
self.every_nth_instruction = rhs.every_nth_instruction;
384-
}
379+
self.every_nth_instruction = self.every_nth_instruction.or(rhs.every_nth_instruction);
385380
self
386381
}
387382
}

src/function.rs

Lines changed: 3 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -457,10 +457,7 @@ impl Function {
457457
FunctionInfo {
458458
name: ptr_to_lossy_str(ar.name).map(|s| s.into_owned()),
459459
#[cfg(not(feature = "luau"))]
460-
name_what: match ptr_to_str(ar.namewhat) {
461-
Some("") => None,
462-
val => val,
463-
},
460+
name_what: ptr_to_str(ar.namewhat).filter(|s| !s.is_empty()),
464461
#[cfg(feature = "luau")]
465462
name_what: None,
466463
what: ptr_to_str(ar.what).unwrap_or("main"),
@@ -542,22 +539,15 @@ impl Function {
542539
where
543540
F: FnMut(CoverageInfo),
544541
{
545-
use std::ffi::CStr;
546-
use std::os::raw::c_char;
547-
548542
unsafe extern "C-unwind" fn callback<F: FnMut(CoverageInfo)>(
549543
data: *mut c_void,
550-
function: *const c_char,
544+
function: *const std::os::raw::c_char,
551545
line_defined: c_int,
552546
depth: c_int,
553547
hits: *const c_int,
554548
size: usize,
555549
) {
556-
let function = if !function.is_null() {
557-
Some(CStr::from_ptr(function).to_string_lossy().to_string())
558-
} else {
559-
None
560-
};
550+
let function = ptr_to_lossy_str(function).map(|s| s.into_owned());
561551
let rust_callback = &*(data as *const RefCell<F>);
562552
if let Ok(mut rust_callback) = rust_callback.try_borrow_mut() {
563553
// Call the Rust callback with CoverageInfo

src/luau/json.rs

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -52,8 +52,7 @@ impl<'a> Json<'a> {
5252
}
5353

5454
pub(crate) fn as_u64(&self) -> Option<u64> {
55-
self.as_i64()
56-
.and_then(|i| if i >= 0 { Some(i as u64) } else { None })
55+
self.as_i64().and_then(|i| u64::try_from(i).ok())
5756
}
5857

5958
pub(crate) fn as_array(&self) -> Option<&[Json<'a>]> {
@@ -74,8 +73,7 @@ impl<'a> Json<'a> {
7473
pub(crate) fn parse<'a>(s: &'a str) -> Result<Json<'a>, &'static str> {
7574
let s = s.trim_ascii();
7675
let mut chars = s.char_indices().peekable();
77-
let value = parse_value(s, &mut chars)?;
78-
Ok(value)
76+
parse_value(s, &mut chars)
7977
}
8078

8179
fn parse_value<'a>(s: &'a str, chars: &mut Peekable<CharIndices>) -> Result<Json<'a>, &'static str> {

src/luau/require.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -359,7 +359,7 @@ pub(super) unsafe extern "C-unwind" fn init_config(config: *mut ffi::luarequire_
359359
fn detect_config_format(data: &[u8]) -> ConfigStatus {
360360
let data = data.trim_ascii();
361361
if data.starts_with(b"{") {
362-
let data = &data[1..].trim_ascii_start();
362+
let data = data[1..].trim_ascii_start();
363363
if data.starts_with(b"\"") || data == b"}" {
364364
return ConfigStatus::PresentJson;
365365
}

src/luau/require/fs.rs

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -208,13 +208,15 @@ impl Require for FsRequirer {
208208
}
209209

210210
fn has_config(&self) -> bool {
211-
self.abs_path.is_dir() && self.abs_path.join(Self::LUAURC_CONFIG_FILENAME).is_file()
212-
|| self.abs_path.is_dir() && self.abs_path.join(Self::LUAU_CONFIG_FILENAME).is_file()
211+
self.abs_path.is_dir()
212+
&& (self.abs_path.join(Self::LUAURC_CONFIG_FILENAME).is_file()
213+
|| self.abs_path.join(Self::LUAU_CONFIG_FILENAME).is_file())
213214
}
214215

215216
fn config(&self) -> IoResult<Vec<u8>> {
216-
if self.abs_path.join(Self::LUAURC_CONFIG_FILENAME).is_file() {
217-
return fs::read(self.abs_path.join(Self::LUAURC_CONFIG_FILENAME));
217+
let path = self.abs_path.join(Self::LUAURC_CONFIG_FILENAME);
218+
if path.is_file() {
219+
return fs::read(path);
218220
}
219221
fs::read(self.abs_path.join(Self::LUAU_CONFIG_FILENAME))
220222
}

src/multi.rs

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
use std::collections::{VecDeque, vec_deque};
22
use std::iter::FromIterator;
3-
use std::mem;
43
use std::ops::{Deref, DerefMut};
54
use std::os::raw::c_int;
65
use std::result::Result as StdResult;
@@ -180,10 +179,8 @@ impl IntoIterator for MultiValue {
180179
type IntoIter = vec_deque::IntoIter<Value>;
181180

182181
#[inline]
183-
fn into_iter(mut self) -> Self::IntoIter {
184-
let deque = mem::take(&mut self.0);
185-
mem::forget(self);
186-
deque.into_iter()
182+
fn into_iter(self) -> Self::IntoIter {
183+
self.0.into_iter()
187184
}
188185
}
189186

src/state.rs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -975,11 +975,11 @@ impl Lua {
975975
#[cfg(any(feature = "lua55", feature = "lua54"))]
976976
#[cfg_attr(docsrs, doc(cfg(any(feature = "lua55", feature = "lua54"))))]
977977
pub fn warning(&self, msg: impl AsRef<str>, incomplete: bool) {
978-
let msg = msg.as_ref();
979-
let mut bytes = vec![0; msg.len() + 1];
980-
bytes[..msg.len()].copy_from_slice(msg.as_bytes());
981-
let real_len = bytes.iter().position(|&c| c == 0).unwrap();
982-
bytes.truncate(real_len);
978+
let msg = msg.as_ref().as_bytes();
979+
let end = msg.iter().position(|&c| c == 0).unwrap_or(msg.len());
980+
let mut bytes = Vec::with_capacity(end + 1);
981+
bytes.extend_from_slice(&msg[..end]);
982+
bytes.push(0);
983983
let lua = self.lock();
984984
unsafe {
985985
ffi::lua_warning(lua.state(), bytes.as_ptr() as *const _, incomplete as c_int);
@@ -1848,7 +1848,7 @@ impl Lua {
18481848
lua.push_value(&v)?;
18491849
let mut isint = 0;
18501850
let i = ffi::lua_tointegerx(state, -1, &mut isint);
1851-
if isint == 0 { None } else { Some(i) }
1851+
(isint != 0).then_some(i)
18521852
},
18531853
})
18541854
}
@@ -1870,7 +1870,7 @@ impl Lua {
18701870
lua.push_value(&v)?;
18711871
let mut isnum = 0;
18721872
let n = ffi::lua_tonumberx(state, -1, &mut isnum);
1873-
if isnum == 0 { None } else { Some(n) }
1873+
(isnum != 0).then_some(n)
18741874
},
18751875
})
18761876
}

0 commit comments

Comments
 (0)