diff --git a/src/eval/chaining.rs b/src/eval/chaining.rs index 351df42e..0e6869f9 100644 --- a/src/eval/chaining.rs +++ b/src/eval/chaining.rs @@ -989,7 +989,7 @@ impl Engine { } else { let abs_index = index.unsigned_abs(); - if abs_index as u64 >= usize::MAX as u64 { + if abs_index as u64 > usize::MAX as u64 { return Err( ERR::ErrorStringBounds(s.chars().count(), index, idx_pos).into() ); diff --git a/src/eval/debugger.rs b/src/eval/debugger.rs index bfdb2af5..e98771e7 100644 --- a/src/eval/debugger.rs +++ b/src/eval/debugger.rs @@ -397,7 +397,7 @@ impl Debugger { /// Get the custom state. #[inline(always)] #[must_use] - pub fn state(&self) -> &Dynamic { + pub const fn state(&self) -> &Dynamic { &self.state } /// Get a mutable reference to the custom state. diff --git a/src/eval/expr.rs b/src/eval/expr.rs index ab499a6a..9419e9e9 100644 --- a/src/eval/expr.rs +++ b/src/eval/expr.rs @@ -144,11 +144,10 @@ impl Engine { let (index, var_pos) = match expr { // Check if the variable is `this` Expr::Variable(v, None, pos) if v.0.is_none() && v.3 == KEYWORD_THIS => { - return if let Some(val) = this_ptr { - Ok(((*val).into(), *pos)) - } else { - Err(ERR::ErrorUnboundThis(*pos).into()) - } + return this_ptr.as_mut().map_or_else( + || Err(ERR::ErrorUnboundThis(*pos).into()), + |val| Ok(((*val).into(), *pos)), + ) } _ if global.always_search_scope => (0, expr.start_position()), Expr::Variable(.., Some(i), pos) => (i.get() as usize, *pos), diff --git a/src/eval/stmt.rs b/src/eval/stmt.rs index 1003e896..0076102d 100644 --- a/src/eval/stmt.rs +++ b/src/eval/stmt.rs @@ -484,12 +484,10 @@ impl Engine { self.eval_expr(scope, global, caches, lib, this_ptr, expr, level) } else if let Ok(None) = expr_result { // Default match clause - if let Some(index) = def_case { - let def_expr = &expressions[*index].expr; + def_case.as_ref().map_or(Ok(Dynamic::UNIT), |&index| { + let def_expr = &expressions[index].expr; self.eval_expr(scope, global, caches, lib, this_ptr, def_expr, level) - } else { - Ok(Dynamic::UNIT) - } + }) } else { expr_result.map(|_| Dynamic::UNIT) } diff --git a/src/eval/target.rs b/src/eval/target.rs index 0114fa5b..e20f5b07 100644 --- a/src/eval/target.rs +++ b/src/eval/target.rs @@ -15,7 +15,12 @@ use std::prelude::v1::*; #[allow(dead_code)] pub fn calc_offset_len(length: usize, start: crate::INT, len: crate::INT) -> (usize, usize) { let start = if start < 0 { - length - usize::min(start.unsigned_abs() as usize, length) + let abs_start = start.unsigned_abs(); + if abs_start as u64 > crate::MAX_USIZE_INT as u64 { + 0 + } else { + length - usize::min(abs_start as usize, length) + } } else if start > crate::MAX_USIZE_INT || start as usize >= length { return (length, 0); } else { diff --git a/src/func/call.rs b/src/func/call.rs index 071bb5c7..4b1696d8 100644 --- a/src/func/call.rs +++ b/src/func/call.rs @@ -1228,13 +1228,11 @@ impl Engine { if target_is_shared || target.is_temp_value() { arg_values.insert(0, target.take_or_clone().flatten()); - args.extend(arg_values.iter_mut()); } else { // Turn it into a method call only if the object is not shared and not a simple value is_ref_mut = true; let obj_ref = target.take_ref().expect("ref"); args.push(obj_ref); - args.extend(arg_values.iter_mut()); } } else { // func(..., ...) @@ -1246,8 +1244,9 @@ impl Engine { .map(|(value, ..)| arg_values.push(value.flatten())) })?; args.extend(curry.iter_mut()); - args.extend(arg_values.iter_mut()); } + + args.extend(arg_values.iter_mut()); } self.exec_fn_call( diff --git a/src/module/mod.rs b/src/module/mod.rs index 805c821a..672e2cf6 100644 --- a/src/module/mod.rs +++ b/src/module/mod.rs @@ -41,7 +41,7 @@ impl FnNamespace { /// Is this a module namespace? #[inline(always)] #[must_use] - pub fn is_module_namespace(self) -> bool { + pub const fn is_module_namespace(self) -> bool { match self { Self::Internal => true, Self::Global => false, @@ -50,7 +50,7 @@ impl FnNamespace { /// Is this a global namespace? #[inline(always)] #[must_use] - pub fn is_global_namespace(self) -> bool { + pub const fn is_global_namespace(self) -> bool { match self { Self::Internal => false, Self::Global => true, @@ -193,7 +193,6 @@ impl FuncInfo { sig.push_str(", "); } } - sig.push(')'); } else { let params: StaticVec<_> = self .metadata @@ -215,8 +214,8 @@ impl FuncInfo { }) .collect(); sig.push_str(¶ms.join(", ")); - sig.push(')'); } + sig.push(')'); if !self.func.is_script() && !return_type.is_empty() { sig.push_str(" -> "); diff --git a/src/optimizer.rs b/src/optimizer.rs index 851628e8..d76fc42c 100644 --- a/src/optimizer.rs +++ b/src/optimizer.rs @@ -988,7 +988,7 @@ fn optimize_expr(expr: &mut Expr, state: &mut OptimizerState, _chaining: bool) { #[cfg(not(feature = "no_index"))] Expr::Index(x, ..) if !_chaining => match (&mut x.lhs, &mut x.rhs) { // array[int] - (Expr::Array(a, pos), Expr::IntegerConstant(i, ..)) if *i >= 0 && (*i as usize) < a.len() && a.iter().all(Expr::is_pure) => { + (Expr::Array(a, pos), Expr::IntegerConstant(i, ..)) if *i >= 0 && *i <= crate::MAX_USIZE_INT && (*i as usize) < a.len() && a.iter().all(Expr::is_pure) => { // Array literal where everything is pure - promote the indexed item. // All other items can be thrown away. state.set_dirty(); @@ -997,7 +997,7 @@ fn optimize_expr(expr: &mut Expr, state: &mut OptimizerState, _chaining: bool) { *expr = result; } // array[-int] - (Expr::Array(a, pos), Expr::IntegerConstant(i, ..)) if *i < 0 && i.unsigned_abs() as usize <= a.len() && a.iter().all(Expr::is_pure) => { + (Expr::Array(a, pos), Expr::IntegerConstant(i, ..)) if *i < 0 && i.unsigned_abs() as u64 <= a.len() as u64 && a.iter().all(Expr::is_pure) => { // Array literal where everything is pure - promote the indexed item. // All other items can be thrown away. state.set_dirty(); @@ -1015,25 +1015,25 @@ fn optimize_expr(expr: &mut Expr, state: &mut OptimizerState, _chaining: bool) { .map_or_else(|| Expr::Unit(*pos), |(.., mut expr)| { expr.set_position(*pos); expr }); } // int[int] - (Expr::IntegerConstant(n, pos), Expr::IntegerConstant(i, ..)) if *i >= 0 && (*i as usize) < crate::INT_BITS => { + (Expr::IntegerConstant(n, pos), Expr::IntegerConstant(i, ..)) if *i >= 0 && *i <= crate::MAX_USIZE_INT && (*i as usize) < crate::INT_BITS => { // Bit-field literal indexing - get the bit state.set_dirty(); *expr = Expr::BoolConstant((*n & (1 << (*i as usize))) != 0, *pos); } // int[-int] - (Expr::IntegerConstant(n, pos), Expr::IntegerConstant(i, ..)) if *i < 0 && i.unsigned_abs() as usize <= crate::INT_BITS => { + (Expr::IntegerConstant(n, pos), Expr::IntegerConstant(i, ..)) if *i < 0 && i.unsigned_abs() as u64 <= crate::INT_BITS as u64 => { // Bit-field literal indexing - get the bit state.set_dirty(); *expr = Expr::BoolConstant((*n & (1 << (crate::INT_BITS - i.unsigned_abs() as usize))) != 0, *pos); } // string[int] - (Expr::StringConstant(s, pos), Expr::IntegerConstant(i, ..)) if *i >= 0 && (*i as usize) < s.chars().count() => { + (Expr::StringConstant(s, pos), Expr::IntegerConstant(i, ..)) if *i >= 0 && *i <= crate::MAX_USIZE_INT && (*i as usize) < s.chars().count() => { // String literal indexing - get the character state.set_dirty(); *expr = Expr::CharConstant(s.chars().nth(*i as usize).unwrap(), *pos); } // string[-int] - (Expr::StringConstant(s, pos), Expr::IntegerConstant(i, ..)) if *i < 0 && i.unsigned_abs() as usize <= s.chars().count() => { + (Expr::StringConstant(s, pos), Expr::IntegerConstant(i, ..)) if *i < 0 && i.unsigned_abs() as u64 <= s.chars().count() as u64 => { // String literal indexing - get the character state.set_dirty(); *expr = Expr::CharConstant(s.chars().rev().nth(i.unsigned_abs() as usize - 1).unwrap(), *pos); diff --git a/src/packages/array_basic.rs b/src/packages/array_basic.rs index 3b3e9e5a..0751a768 100644 --- a/src/packages/array_basic.rs +++ b/src/packages/array_basic.rs @@ -1312,8 +1312,7 @@ pub mod array_functions { /// /// print(x); // prints "[1, 2, 3, 4, 3, 2, 1]" /// ``` - #[rhai_fn(return_raw)] - pub fn dedup(ctx: NativeCallContext, array: &mut Array) -> RhaiResultOf<()> { + pub fn dedup(ctx: NativeCallContext, array: &mut Array) { let comparer = FnPtr::new_unchecked(OP_EQUALS, StaticVec::new_const()); dedup_by_comparer(ctx, array, comparer) } @@ -1340,14 +1339,10 @@ pub mod array_functions { /// /// print(x); // prints "[1, 2, 3, 4]" /// ``` - #[rhai_fn(name = "dedup", return_raw)] - pub fn dedup_by_comparer( - ctx: NativeCallContext, - array: &mut Array, - comparer: FnPtr, - ) -> RhaiResultOf<()> { + #[rhai_fn(name = "dedup")] + pub fn dedup_by_comparer(ctx: NativeCallContext, array: &mut Array, comparer: FnPtr) { if array.is_empty() { - return Ok(()); + return; } array.dedup_by(|x, y| { @@ -1357,8 +1352,6 @@ pub mod array_functions { .as_bool() .unwrap_or(false) }); - - Ok(()) } /// Remove duplicated _consecutive_ elements from the array that return `true` when applied a /// function named by `comparer`. @@ -1391,7 +1384,7 @@ pub mod array_functions { array: &mut Array, comparer: &str, ) -> RhaiResultOf<()> { - dedup_by_comparer(ctx, array, FnPtr::new(comparer)?) + Ok(dedup_by_comparer(ctx, array, FnPtr::new(comparer)?)) } /// Reduce an array by iterating through all elements while applying the `reducer` function. /// diff --git a/src/serde/de.rs b/src/serde/de.rs index 15c538cd..76c31c11 100644 --- a/src/serde/de.rs +++ b/src/serde/de.rs @@ -22,7 +22,7 @@ impl<'de> DynamicDeserializer<'de> { /// The reference is necessary because the deserialized type may hold references /// (especially `&str`) to the source [`Dynamic`][crate::Dynamic]. #[must_use] - pub fn from_dynamic(value: &'de Dynamic) -> Self { + pub const fn from_dynamic(value: &'de Dynamic) -> Self { Self { value } } /// Shortcut for a type conversion error. @@ -449,21 +449,22 @@ impl<'de> Deserializer<'de> for &mut DynamicDeserializer<'de> { visitor.visit_enum(s.as_str().into_deserializer()) } else { #[cfg(not(feature = "no_object"))] - if let Some(map) = self.value.downcast_ref::() { - let mut iter = map.iter(); - let first = iter.next(); - let second = iter.next(); - if let (Some((key, value)), None) = (first, second) { - visitor.visit_enum(EnumDeserializer { - tag: key, - content: DynamicDeserializer::from_dynamic(value), - }) - } else { - self.type_error() - } - } else { - self.type_error() - } + return self.value.downcast_ref::().map_or_else( + || self.type_error(), + |map| { + let mut iter = map.iter(); + let first = iter.next(); + let second = iter.next(); + if let (Some((key, value)), None) = (first, second) { + visitor.visit_enum(EnumDeserializer { + tag: key, + content: DynamicDeserializer::from_dynamic(value), + }) + } else { + self.type_error() + } + }, + ); #[cfg(feature = "no_object")] return self.type_error(); } @@ -488,7 +489,7 @@ struct IterateDynamicArray<'a, ITER: Iterator> { #[cfg(not(feature = "no_index"))] impl<'a, ITER: Iterator> IterateDynamicArray<'a, ITER> { #[must_use] - pub fn new(iter: ITER) -> Self { + pub const fn new(iter: ITER) -> Self { Self { iter } } } @@ -525,7 +526,7 @@ struct IterateMap<'a, K: Iterator, V: Iterator, V: Iterator> IterateMap<'a, K, V> { #[must_use] - pub fn new(keys: K, values: V) -> Self { + pub const fn new(keys: K, values: V) -> Self { Self { keys, values } } } diff --git a/src/serde/metadata.rs b/src/serde/metadata.rs index f4d9732f..7a562d5c 100644 --- a/src/serde/metadata.rs +++ b/src/serde/metadata.rs @@ -56,7 +56,7 @@ impl PartialOrd for FnMetadata<'_> { impl Ord for FnMetadata<'_> { fn cmp(&self, other: &Self) -> Ordering { - match self.name.cmp(&other.name) { + match self.name.cmp(other.name) { Ordering::Equal => self.num_params.cmp(&other.num_params), cmp => cmp, } @@ -79,8 +79,8 @@ impl<'a> From<&'a FuncInfo> for FnMetadata<'a> { base_hash, full_hash, #[cfg(not(feature = "no_module"))] - namespace: info.metadata.namespace.into(), - access: info.metadata.access.into(), + namespace: info.metadata.namespace, + access: info.metadata.access, name: &info.metadata.name, typ, num_params: info.metadata.params, @@ -150,7 +150,7 @@ impl<'a> From<&'a crate::Module> for ModuleMetadata<'a> { functions.sort(); Self { - doc: module.doc().into(), + doc: module.doc(), modules: module .iter_sub_modules() .map(|(name, m)| (name, m.as_ref().into())) @@ -206,7 +206,7 @@ pub fn gen_metadata_to_json( #[cfg(feature = "metadata")] if let Some(ast) = _ast { - global.doc = ast.doc().into(); + global.doc = ast.doc(); } serde_json::to_string_pretty(&global) diff --git a/src/serde/ser.rs b/src/serde/ser.rs index b7e2d915..1cdc8e28 100644 --- a/src/serde/ser.rs +++ b/src/serde/ser.rs @@ -20,7 +20,7 @@ struct DynamicSerializer { impl DynamicSerializer { /// Create a [`DynamicSerializer`] from a [`Dynamic`][crate::Dynamic] value. #[must_use] - pub fn new(_value: Dynamic) -> Self { + pub const fn new(_value: Dynamic) -> Self { Self { _key: Dynamic::UNIT, _value, diff --git a/src/serde/str.rs b/src/serde/str.rs index fd19de8c..df747a42 100644 --- a/src/serde/str.rs +++ b/src/serde/str.rs @@ -14,7 +14,7 @@ pub struct StringSliceDeserializer<'a> { impl<'a> StringSliceDeserializer<'a> { /// Create an `ImmutableStringDeserializer` from an `&str` reference. #[must_use] - pub fn from_str(value: &'a str) -> Self { + pub const fn from_str(value: &'a str) -> Self { Self { value } } /// Shortcut for a type conversion error. diff --git a/src/tokenizer.rs b/src/tokenizer.rs index 1eb5bd93..f69f2411 100644 --- a/src/tokenizer.rs +++ b/src/tokenizer.rs @@ -1701,11 +1701,11 @@ fn get_next_token_inner( // letter or underscore ... #[cfg(not(feature = "unicode-xid-ident"))] ('a'..='z' | '_' | 'A'..='Z', ..) => { - return get_identifier(stream, pos, start_pos, c); + return Some(get_identifier(stream, pos, start_pos, c)); } #[cfg(feature = "unicode-xid-ident")] (ch, ..) if unicode_xid::UnicodeXID::is_xid_start(ch) || ch == '_' => { - return get_identifier(stream, pos, start_pos, c); + return Some(get_identifier(stream, pos, start_pos, c)); } // " - string literal @@ -2178,7 +2178,7 @@ fn get_identifier( pos: &mut Position, start_pos: Position, first_char: char, -) -> Option<(Token, Position)> { +) -> (Token, Position) { let mut result = smallvec::SmallVec::<[char; 8]>::new(); result.push(first_char); @@ -2197,17 +2197,17 @@ fn get_identifier( let identifier: String = result.into_iter().collect(); if let Some(token) = Token::lookup_from_syntax(&identifier) { - return Some((token, start_pos)); + return (token, start_pos); } if !is_valid_identifier { - return Some(( + return ( Token::LexError(LERR::MalformedIdentifier(identifier).into()), start_pos, - )); + ); } - Some((Token::Identifier(identifier.into()), start_pos)) + (Token::Identifier(identifier.into()), start_pos) } /// Is a keyword allowed as a function? @@ -2272,7 +2272,7 @@ pub fn is_id_continue(x: char) -> bool { #[cfg(not(feature = "unicode-xid-ident"))] #[inline(always)] #[must_use] -pub fn is_id_first_alphabetic(x: char) -> bool { +pub const fn is_id_first_alphabetic(x: char) -> bool { x.is_ascii_alphabetic() } @@ -2280,7 +2280,7 @@ pub fn is_id_first_alphabetic(x: char) -> bool { #[cfg(not(feature = "unicode-xid-ident"))] #[inline(always)] #[must_use] -pub fn is_id_continue(x: char) -> bool { +pub const fn is_id_continue(x: char) -> bool { x.is_ascii_alphanumeric() || x == '_' } diff --git a/src/types/dynamic.rs b/src/types/dynamic.rs index 29a88336..5d4803d1 100644 --- a/src/types/dynamic.rs +++ b/src/types/dynamic.rs @@ -1166,7 +1166,7 @@ impl Dynamic { #[cfg(not(feature = "no_index"))] reify!(value, |v: crate::Blob| { // don't use blob.into() because it'll be converted into an Array - return Dynamic::from_blob(v); + return Self::from_blob(v); }); #[cfg(not(feature = "no_object"))] reify!(value, |v: crate::Map| return v.into()); @@ -1175,7 +1175,7 @@ impl Dynamic { #[cfg(not(feature = "no_std"))] reify!(value, |v: Instant| return v.into()); #[cfg(not(feature = "no_closure"))] - reify!(value, |v: crate::Shared>| return v + reify!(value, |v: crate::Shared>| return v .into()); Self(Union::Variant( @@ -1444,7 +1444,7 @@ impl Dynamic { let value = crate::func::locked_read(cell); return if (*value).type_id() != TypeId::of::() - && TypeId::of::() != TypeId::of::() + && TypeId::of::() != TypeId::of::() { None } else { @@ -1476,7 +1476,7 @@ impl Dynamic { let guard = crate::func::locked_write(cell); return if (*guard).type_id() != TypeId::of::() - && TypeId::of::() != TypeId::of::() + && TypeId::of::() != TypeId::of::() { None } else { @@ -1577,7 +1577,7 @@ impl Dynamic { _ => None, }; } - if TypeId::of::() == TypeId::of::() { + if TypeId::of::() == TypeId::of::() { return self.as_any().downcast_ref::(); } @@ -1675,7 +1675,7 @@ impl Dynamic { _ => None, }; } - if TypeId::of::() == TypeId::of::() { + if TypeId::of::() == TypeId::of::() { return self.as_any_mut().downcast_mut::(); } @@ -1962,7 +1962,7 @@ impl From> for Dynamic { #[inline] fn from(value: Vec) -> Self { Self(Union::Array( - Box::new(value.into_iter().map(Dynamic::from).collect()), + Box::new(value.into_iter().map(Self::from).collect()), DEFAULT_TAG_VALUE, ReadWrite, )) @@ -1973,7 +1973,7 @@ impl From<&[T]> for Dynamic { #[inline] fn from(value: &[T]) -> Self { Self(Union::Array( - Box::new(value.iter().cloned().map(Dynamic::from).collect()), + Box::new(value.iter().cloned().map(Self::from).collect()), DEFAULT_TAG_VALUE, ReadWrite, )) @@ -1984,7 +1984,7 @@ impl std::iter::FromIterator for Dynamic { #[inline] fn from_iter>(iter: X) -> Self { Self(Union::Array( - Box::new(iter.into_iter().map(Dynamic::from).collect()), + Box::new(iter.into_iter().map(Self::from).collect()), DEFAULT_TAG_VALUE, ReadWrite, )) @@ -2001,7 +2001,7 @@ impl, T: Variant + Clone> From> From> for Dynamic #[inline] fn from(value: std::collections::HashSet) -> Self { Self(Union::Map( - Box::new( - value - .into_iter() - .map(|k| (k.into(), Dynamic::UNIT)) - .collect(), - ), + Box::new(value.into_iter().map(|k| (k.into(), Self::UNIT)).collect()), DEFAULT_TAG_VALUE, ReadWrite, )) @@ -2036,7 +2031,7 @@ impl, T: Variant + Clone> From> From> for Dynamic #[inline] fn from(value: std::collections::BTreeSet) -> Self { Self(Union::Map( - Box::new( - value - .into_iter() - .map(|k| (k.into(), Dynamic::UNIT)) - .collect(), - ), + Box::new(value.into_iter().map(|k| (k.into(), Self::UNIT)).collect()), DEFAULT_TAG_VALUE, ReadWrite, )) @@ -2074,7 +2064,7 @@ impl From for Dynamic { } } #[cfg(not(feature = "no_closure"))] -impl From>> for Dynamic { +impl From>> for Dynamic { #[inline(always)] fn from(value: crate::Shared>) -> Self { Self(Union::Shared(value, DEFAULT_TAG_VALUE, ReadWrite)) @@ -2084,12 +2074,12 @@ impl From>> for Dynamic { impl From for Dynamic { #[inline(always)] fn from(value: ExclusiveRange) -> Self { - Dynamic::from(value) + Self::from(value) } } impl From for Dynamic { #[inline(always)] fn from(value: InclusiveRange) -> Self { - Dynamic::from(value) + Self::from(value) } } diff --git a/src/types/error.rs b/src/types/error.rs index 9c0133f4..6e9814cd 100644 --- a/src/types/error.rs +++ b/src/types/error.rs @@ -368,9 +368,6 @@ impl EvalAltResult { map.insert("function".into(), f.into()); map.insert("source".into(), s.into()); } - Self::ErrorInModule(m, ..) => { - map.insert("module".into(), m.into()); - } Self::ErrorMismatchDataType(r, a, ..) | Self::ErrorMismatchOutputType(r, a, ..) => { map.insert("requested".into(), r.into()); map.insert("actual".into(), a.into()); @@ -381,9 +378,6 @@ impl EvalAltResult { map.insert("length".into(), (*n as INT).into()); map.insert("index".into(), (*i as INT).into()); } - Self::ErrorIndexingType(t, ..) => { - map.insert("type".into(), t.into()); - } Self::ErrorVariableExists(v, ..) | Self::ErrorForbiddenVariable(v, ..) | Self::ErrorVariableNotFound(v, ..) @@ -395,14 +389,14 @@ impl EvalAltResult { Self::ErrorIndexNotFound(v, ..) => { map.insert("index".into(), v.clone()); } - Self::ErrorModuleNotFound(m, ..) => { + Self::ErrorInModule(m, ..) | Self::ErrorModuleNotFound(m, ..) => { map.insert("module".into(), m.into()); } Self::ErrorDotExpr(p, ..) => { map.insert("property".into(), p.into()); } - Self::ErrorDataTooLarge(t, ..) => { + Self::ErrorIndexingType(t, ..) | Self::ErrorDataTooLarge(t, ..) => { map.insert("type".into(), t.into()); } Self::ErrorTerminated(t, ..) => { diff --git a/src/types/immutable_string.rs b/src/types/immutable_string.rs index 5b4fefa5..6487efeb 100644 --- a/src/types/immutable_string.rs +++ b/src/types/immutable_string.rs @@ -264,9 +264,9 @@ impl Add for &ImmutableString { } } -impl AddAssign<&ImmutableString> for ImmutableString { +impl AddAssign<&Self> for ImmutableString { #[inline] - fn add_assign(&mut self, rhs: &ImmutableString) { + fn add_assign(&mut self, rhs: &Self) { if !rhs.is_empty() { if self.is_empty() { self.0 = rhs.0.clone(); @@ -277,9 +277,9 @@ impl AddAssign<&ImmutableString> for ImmutableString { } } -impl AddAssign for ImmutableString { +impl AddAssign for ImmutableString { #[inline] - fn add_assign(&mut self, rhs: ImmutableString) { + fn add_assign(&mut self, rhs: Self) { if !rhs.is_empty() { if self.is_empty() { self.0 = rhs.0; @@ -431,9 +431,9 @@ impl Sub for &ImmutableString { } } -impl SubAssign<&ImmutableString> for ImmutableString { +impl SubAssign<&Self> for ImmutableString { #[inline] - fn sub_assign(&mut self, rhs: &ImmutableString) { + fn sub_assign(&mut self, rhs: &Self) { if !rhs.is_empty() { if self.is_empty() { self.0 = rhs.0.clone(); @@ -445,9 +445,9 @@ impl SubAssign<&ImmutableString> for ImmutableString { } } -impl SubAssign for ImmutableString { +impl SubAssign for ImmutableString { #[inline] - fn sub_assign(&mut self, rhs: ImmutableString) { + fn sub_assign(&mut self, rhs: Self) { if !rhs.is_empty() { if self.is_empty() { self.0 = rhs.0; diff --git a/src/types/interner.rs b/src/types/interner.rs index 90c28461..40df1982 100644 --- a/src/types/interner.rs +++ b/src/types/interner.rs @@ -64,7 +64,7 @@ impl StringsInterner<'_> { #[inline(always)] #[must_use] pub fn get + Into>(&mut self, text: S) -> ImmutableString { - self.get_with_mapper(|s| s.into(), text) + self.get_with_mapper(Into::into, text) } /// Get an identifier from a text string, adding it to the interner if necessary. diff --git a/src/types/parse_error.rs b/src/types/parse_error.rs index a80255f0..47e3589a 100644 --- a/src/types/parse_error.rs +++ b/src/types/parse_error.rs @@ -302,13 +302,13 @@ impl ParseError { /// Get the [type][ParseErrorType] of this parse error. #[inline(always)] #[must_use] - pub fn err_type(&self) -> &ParseErrorType { + pub const fn err_type(&self) -> &ParseErrorType { &self.0 } /// Get the [position][Position] of this parse error. #[inline(always)] #[must_use] - pub fn position(&self) -> Position { + pub const fn position(&self) -> Position { self.1 } } @@ -323,7 +323,7 @@ impl From for RhaiError { impl From for ERR { #[inline(always)] fn from(err: ParseErrorType) -> Self { - ERR::ErrorParsing(err, Position::NONE) + Self::ErrorParsing(err, Position::NONE) } } @@ -337,6 +337,6 @@ impl From for RhaiError { impl From for ERR { #[inline(always)] fn from(err: ParseError) -> Self { - ERR::ErrorParsing(*err.0, err.1) + Self::ErrorParsing(*err.0, err.1) } } diff --git a/tests/build_type.rs b/tests/build_type.rs index 9fbcc1af..05b23bc2 100644 --- a/tests/build_type.rs +++ b/tests/build_type.rs @@ -3,7 +3,7 @@ use rhai::{CustomType, Engine, EvalAltResult, Position, TypeBuilder, INT}; #[test] fn build_type() -> Result<(), Box> { - #[derive(Debug, Clone, PartialEq)] + #[derive(Debug, Clone, PartialEq, Eq)] struct Vec3 { x: INT, y: INT, @@ -60,7 +60,8 @@ fn build_type() -> Result<(), Box> { .with_name("Vec3") .is_iterable() .with_fn("vec3", Self::new) - .is_iterable() + .with_fn("==", |x: &mut Vec3, y: Vec3| *x == y) + .with_fn("!=", |x: &mut Vec3, y: Vec3| *x != y) .with_get_set("x", Self::get_x, Self::set_x) .with_get_set("y", Self::get_y, Self::set_y) .with_get_set("z", Self::get_z, Self::set_z);