Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit0daa796

Browse files
authored
Merge pull request#1009 from schungx/master
Replace casts with `try_from`
2 parents68fc201 +7b94e57 commit0daa796

27 files changed

+456
-512
lines changed

‎CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ Enhancements
1616

1717
*`CustomType` derive macro now supports generic types (thanks[`@ProphetOSpam`](https://github.com/ProphetOSpam)[#999](https://github.com/rhaiscript/rhai/pull/999)). The`rhai_codegen` crate dependency is bumped to`3.0.0` or later.
1818
*`Engine::eval_binary_op` is added to quickly compare two`Dynamic` values.
19+
* Better handling for 32-bit architectures.
1920

2021

2122
Version 1.22.2

‎codegen/src/custom_type.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ pub fn derive_custom_type_impl(input: DeriveInput) -> TokenStream {
4646
}
4747
}else{
4848
let key = path.get_ident().unwrap().to_string();
49-
let msg =format!("invalid option: '{}'", key);
49+
let msg =format!("invalid option: '{key}'");
5050
errors.push(syn::Error::new(path.span(), msg).into_compile_error());
5151
}
5252
}
@@ -57,7 +57,7 @@ pub fn derive_custom_type_impl(input: DeriveInput) -> TokenStream {
5757
// any other identifier
5858
Expr::Path(path)if path.path.get_ident().is_some() =>{
5959
let key = path.path.get_ident().unwrap().to_string();
60-
let msg =format!("invalid option: '{}'", key);
60+
let msg =format!("invalid option: '{key}'");
6161
errors.push(syn::Error::new(path.span(), msg).into_compile_error());
6262
}
6363
// Error

‎src/api/build_type.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -196,7 +196,7 @@ impl<T: Variant + Clone> TypeBuilder<'_, T> {
196196

197197
for&hashin&self.hashes{
198198
ifletSome(f) = module.get_fn_metadata_mut(hash){
199-
f.comments = comments.into_iter().map(|&s| s.into()).collect();
199+
f.comments = comments.iter().map(|&s| s.into()).collect();
200200
}
201201
}
202202

‎src/api/definitions/mod.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
//! Module that defines functions to output definition files for [`Engine`].
22
#![cfg(feature ="internals")]
3-
#![cfg(feature ="metadata")]
43

54
usecrate::module::FuncMetadata;
65
usecrate::tokenizer::{is_valid_function_name,Token};

‎src/eval/cache.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ impl FnResolutionCache {
4444
///
4545
/// The following caches are contained inside this type:
4646
/// * A stack of [function resolution caches][FnResolutionCache]
47-
#[derive(Debug,Clone)]
47+
#[derive(Debug,Clone,Default)]
4848
pubstructCaches{
4949
fn_resolution:StaticVec<FnResolutionCache>,
5050
}

‎src/eval/chaining.rs

Lines changed: 20 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,10 @@ use crate::{
1111
};
1212
#[cfg(feature ="no_std")]
1313
use std::prelude::v1::*;
14-
use std::{convert::TryInto, hash::Hash};
14+
use std::{
15+
convert::{TryFrom,TryInto},
16+
hash::Hash,
17+
};
1518

1619
/// Function call hashes to index getters and setters.
1720
staticINDEXER_HASHES:OnceCell<(u64,u64)> =OnceCell::new();
@@ -217,29 +220,23 @@ impl Engine {
217220
ERR::ErrorBitFieldBounds(crate::INT_BITS, start, idx_pos).into()
218221
})?;
219222
let end =super::calc_index(crate::INT_BITS, end,false, ||{
220-
if end >=0
221-
&& end <crate::MAX_USIZE_INT
222-
&&(endasusize) <=crate::INT_BITS
223-
{
224-
// Handle largest value
225-
Ok(endasusize)
226-
}else{
227-
ERR::ErrorBitFieldBounds(crate::INT_BITS, end, idx_pos).into()
228-
}
223+
usize::try_from(end)
224+
.ok()
225+
.and_then(|x|(x <=crate::INT_BITS).then_some(x))
226+
.ok_or_else(||ERR::ErrorBitFieldBounds(crate::INT_BITS, end, idx_pos))
229227
})?;
230228

231-
#[allow(clippy::cast_possible_truncation)]
232229
if end <= start{
233230
(0,0)
234231
}elseif end ==crate::INT_BITS && start ==0{
235232
// -1 = all bits set
236233
(0, -1)
237234
}else{
238235
(
239-
startasu8,
236+
u8::try_from(start).unwrap(),
240237
// 2^bits - 1
241-
(((2ascrate::UNSIGNED_INT).pow((end - start)asu32) -1)
242-
ascrate::INT)
238+
(((2ascrate::UNSIGNED_INT).pow(u32::try_from(end - start).unwrap())
239+
-1)ascrate::INT)
243240
<< start,
244241
)
245242
}
@@ -258,18 +255,18 @@ impl Engine {
258255
ERR::ErrorBitFieldBounds(crate::INT_BITS, end, idx_pos).into()
259256
})?;
260257

261-
#[allow(clippy::cast_possible_truncation)]
262258
if end < start{
263259
(0,0)
264260
}elseif end ==crate::INT_BITS -1 && start ==0{
265261
// -1 = all bits set
266262
(0, -1)
267263
}else{
268264
(
269-
startasu8,
265+
u8::try_from(start).unwrap(),
270266
// 2^bits - 1
271-
(((2ascrate::UNSIGNED_INT).pow((end - start +1)asu32) -1)
272-
ascrate::INT)
267+
(((2ascrate::UNSIGNED_INT)
268+
.pow(u32::try_from(end - start +1).unwrap())
269+
-1)ascrate::INT)
273270
<< start,
274271
)
275272
}
@@ -299,8 +296,7 @@ impl Engine {
299296
})?;
300297

301298
let bit_value =(*value&(1 << bit)) !=0;
302-
#[allow(clippy::cast_possible_truncation)]
303-
let bit = bitasu8;
299+
let bit = u8::try_from(bit).unwrap();
304300

305301
Ok(Target::Bit{
306302
source: target,
@@ -315,39 +311,31 @@ impl Engine {
315311
match idx.as_int(){
316312
Ok(index) =>{
317313
let(ch, offset) =if index >=0{
318-
#[allow(clippy::absurd_extreme_comparisons)]
319-
if index >=crate::MAX_USIZE_INT{
314+
letOk(offset) = usize::try_from(index)else{
320315
returnErr(ERR::ErrorStringBounds(
321316
s.chars().count(),
322317
index,
323318
idx_pos,
324319
)
325320
.into());
326-
}
321+
};
327322

328-
#[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
329-
let offset = indexasusize;
330323
(
331324
s.chars().nth(offset).ok_or_else(||{
332325
ERR::ErrorStringBounds(s.chars().count(), index, idx_pos)
333326
})?,
334327
offset,
335328
)
336329
}else{
337-
let abs_index = index.unsigned_abs();
338-
339-
#[allow(clippy::unnecessary_cast)]
340-
if abs_indexasu64 > usize::MAXasu64{
330+
letOk(offset) = usize::try_from(index.unsigned_abs())else{
341331
returnErr(ERR::ErrorStringBounds(
342332
s.chars().count(),
343333
index,
344334
idx_pos,
345335
)
346336
.into());
347-
}
337+
};
348338

349-
#[allow(clippy::cast_possible_truncation)]
350-
let offset = abs_indexasusize;
351339
(
352340
// Count from end if negative
353341
s.chars().rev().nth(offset -1).ok_or_else(||{

‎src/eval/stmt.rs

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -721,23 +721,25 @@ impl Engine {
721721
self.track_operation(global, body.position())?;
722722
}
723723
}else{
724-
for(i, iter_value)initer_func(iter_obj).enumerate(){
725-
// Increment counter
726-
ifletSome(counter_index) = counter_index{
727-
// As the variable increments from 0, this should always work
728-
// since any overflow will first be caught below.
729-
let index_value = iasINT;
724+
letmut index_value:INT = -1;
730725

731-
#[cfg(not(feature ="unchecked"))]
732-
#[allow(clippy::absurd_extreme_comparisons)]
733-
if index_value >crate::MAX_USIZE_INT{
734-
returnErr(ERR::ErrorArithmetic(
735-
format!("for-loop counter overflow: {i}"),
736-
counter.as_ref().unwrap().pos,
726+
for iter_valueiniter_func(iter_obj){
727+
#[cfg(not(feature ="unchecked"))]
728+
{
729+
index_value = index_value.checked_add(1).ok_or_else(||{
730+
ERR::ErrorArithmetic(
731+
format!("for-loop counter overflow: {index_value}"),
732+
var_name.pos,
737733
)
738-
.into());
739-
}
734+
})?;
735+
}
736+
#[cfg(feature ="unchecked")]
737+
{
738+
index_value +=1;
739+
}
740740

741+
// Increment counter
742+
ifletSome(counter_index) = counter_index{
741743
*scope.get_mut_by_index(counter_index).write_lock().unwrap() =
742744
Dynamic::from_int(index_value);
743745
}

‎src/eval/target.rs

Lines changed: 17 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -15,33 +15,24 @@ use std::{
1515
/// Values going over bounds are limited to the actual length.
1616
#[cfg(not(feature ="no_index"))]
1717
#[inline]
18-
#[allow(
19-
clippy::cast_sign_loss,
20-
clippy::absurd_extreme_comparisons,
21-
clippy::cast_possible_truncation
22-
)]
2318
pubfncalc_offset_len(length:usize,start:crate::INT,len:crate::INT) ->(usize,usize){
2419
let start =if start <0{
25-
let abs_start = start.unsigned_abs();
26-
27-
#[allow(clippy::unnecessary_cast)]
28-
if abs_startasu64 >crate::MAX_USIZE_INTasu64{
29-
0
30-
}else{
31-
length - usize::min(abs_startasusize, length)
32-
}
33-
}elseif start >crate::MAX_USIZE_INT || startasusize >= length{
20+
usize::try_from(start.unsigned_abs()).map_or(0, |x| length - usize::min(x, length))
21+
}elseif usize::try_from(start).map(|x| x >= length).unwrap_or(true){
3422
return(length,0);
3523
}else{
36-
startasusize
24+
usize::try_from(start).unwrap()
3725
};
3826

3927
let len =if len <=0{
4028
0
41-
}elseif len >crate::MAX_USIZE_INT || lenasusize > length - start{
29+
}elseif usize::try_from(len)
30+
.map(|x| x > length - start)
31+
.unwrap_or(true)
32+
{
4233
length - start
4334
}else{
44-
lenasusize
35+
usize::try_from(len).unwrap()
4536
};
4637

4738
(start, len)
@@ -54,11 +45,6 @@ pub fn calc_offset_len(length: usize, start: crate::INT, len: crate::INT) -> (us
5445
/// Values going over bounds call the provided closure to return a default value or an error.
5546
#[inline]
5647
#[allow(dead_code)]
57-
#[allow(
58-
clippy::cast_sign_loss,
59-
clippy::cast_possible_truncation,
60-
clippy::absurd_extreme_comparisons
61-
)]
6248
pubfncalc_index<E>(
6349
length:usize,
6450
index:crate::INT,
@@ -69,15 +55,16 @@ pub fn calc_index<E>(
6955
// Empty array, do nothing
7056
}elseif index <0{
7157
if negative_count_from_end{
72-
let abs_index = index.unsigned_abs();
73-
74-
#[allow(clippy::unnecessary_cast)]
75-
if abs_indexasu64 <=crate::MAX_USIZE_INTasu64 &&(abs_indexasusize) <= length{
76-
returnOk(length -(abs_indexasusize));
58+
ifletOk(abs_index) = usize::try_from(index.unsigned_abs()){
59+
if abs_index <= length{
60+
returnOk(length - abs_index);
61+
}
7762
}
7863
}
79-
}elseif index <=crate::MAX_USIZE_INT &&(indexasusize) < length{
80-
returnOk(indexasusize);
64+
}elseifletOk(index) = usize::try_from(index){
65+
if index < length{
66+
returnOk(index);
67+
}
8168
}
8269

8370
err_func()
@@ -361,10 +348,7 @@ impl<'a> Target<'a> {
361348

362349
let value =&mut*source.write_lock::<crate::Blob>().unwrap();
363350

364-
#[allow(clippy::cast_sign_loss)]
365-
{
366-
value[*index] =(new_byte&0x00ff)asu8;
367-
}
351+
value[*index] = u8::try_from(new_byte&0x00ff).unwrap();
368352
}
369353
#[cfg(not(feature ="no_index"))]
370354
Self::StringChar{

‎src/func/call.rs

Lines changed: 19 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -750,7 +750,7 @@ impl Engine {
750750
defer!{let orig_level = global.level; global.level +=1}
751751

752752
self.call_script_fn(
753-
global, caches, scope,None, env,&*fn_def,&mut args,true, pos,
753+
global, caches, scope,None, env, fn_def,&mut args,true, pos,
754754
)
755755
.map(|v|(v,false))
756756
}
@@ -1247,15 +1247,12 @@ impl Engine {
12471247
.as_int()
12481248
.map_err(|typ|self.make_type_mismatch_err::<crate::INT>(typ, arg_pos))?;
12491249

1250-
returnOk(if num_params >crate::MAX_USIZE_INT{
1251-
Dynamic::FALSE
1252-
}elseif num_params >=0{
1253-
#[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
1254-
let hash_script =calc_fn_hash(None,&fn_name, num_paramsasusize);
1255-
self.has_script_fn(global, caches, hash_script).into()
1256-
}else{
1257-
Dynamic::FALSE
1258-
});
1250+
returnOk(usize::try_from(num_params)
1251+
.map(|num_params|{
1252+
let hash_script =calc_fn_hash(None,&fn_name, num_params);
1253+
self.has_script_fn(global, caches, hash_script).into()
1254+
})
1255+
.unwrap_or(Dynamic::FALSE));
12591256
}
12601257

12611258
// Handle is_def_fn(this_type, fn_name, arity)
@@ -1289,18 +1286,15 @@ impl Engine {
12891286
.as_int()
12901287
.map_err(|typ|self.make_type_mismatch_err::<crate::INT>(typ, arg_pos))?;
12911288

1292-
returnOk(if num_params >crate::MAX_USIZE_INT{
1293-
Dynamic::FALSE
1294-
}elseif num_params >=0{
1295-
#[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
1296-
let hash_script =crate::calc_typed_method_hash(
1297-
calc_fn_hash(None,&fn_name, num_paramsasusize),
1298-
&this_type,
1299-
);
1300-
self.has_script_fn(global, caches, hash_script).into()
1301-
}else{
1302-
Dynamic::FALSE
1303-
});
1289+
returnOk(usize::try_from(num_params)
1290+
.map(|num_params|{
1291+
let hash_script =crate::calc_typed_method_hash(
1292+
calc_fn_hash(None,&fn_name, num_params),
1293+
&this_type,
1294+
);
1295+
self.has_script_fn(global, caches, hash_script).into()
1296+
})
1297+
.unwrap_or(Dynamic::FALSE));
13041298
}
13051299

13061300
// Handle is_def_var(fn_name)
@@ -1766,14 +1760,13 @@ impl Engine {
17661760
.0
17671761
.flatten();
17681762

1769-
#[allow(clippy::unnecessary_unwrap)]
1770-
let op_token = op_token.unwrap();
1771-
17721763
if lhs.is_variant() || rhs.is_variant(){
17731764
// For custom types, give registered functions a chance to run first before considering the built-in fallback
17741765
}else{
17751766
// For other types, try to get a built-in
1776-
ifletSome((func, need_context)) =get_builtin_binary_op_fn(op_token,&lhs,&rhs){
1767+
ifletSome((func, need_context)) =
1768+
get_builtin_binary_op_fn(op_token.unwrap(),&lhs,&rhs)
1769+
{
17771770
// We may not need to bump the level because built-in's do not need it.
17781771
//defer! { let orig_level = global.level; global.level += 1 }
17791772

@@ -1784,7 +1777,6 @@ impl Engine {
17841777
}
17851778

17861779
let operands =&mut[&mut lhs,&mut rhs];
1787-
let op_token =Some(op_token);
17881780

17891781
returnself
17901782
.exec_fn_call(

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp