From c9b15eedacc8d18f4f1c08a09c33dd5525ffe58a Mon Sep 17 00:00:00 2001 From: Michael Madden Date: Thu, 29 Aug 2024 21:44:28 -0500 Subject: [PATCH] Safely handle type conversions to avoid potential truncation: - Replaced direct cast from `usize` to `i32` with `try_into()` to ensure safe conversion and prevent overflow, adding explicit error handling if `usize` exceeds the `i32` range. - Replaced direct cast from `i64` to `usize` with `usize::try_from()` to safely handle conversion and avoid truncation on 32-bit systems. - Added error handling for the conversion of `pagination.total` to `usize`, ensuring the value fits within the valid range for `usize`. - Updated loop conditions to use the results of `try_into()` and `try_from()` conversions to continue iterating only if the casts are successful. --- examples/falcon_discover_hosts.rs | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/examples/falcon_discover_hosts.rs b/examples/falcon_discover_hosts.rs index 0ad4dda0..527e40a6 100644 --- a/examples/falcon_discover_hosts.rs +++ b/examples/falcon_discover_hosts.rs @@ -1,9 +1,9 @@ use clap::Parser; - use rusty_falcon::{ apis::discover_api::{get_hosts, query_hosts}, easy::client::FalconHandle, }; +use std::convert::{TryFrom, TryInto}; // We set API limits to a constant value as the `get_hosts` takes max 100 elements. const LIMIT: i32 = 100; @@ -33,9 +33,12 @@ async fn main() { let mut offset = 0usize; loop { + // Use try_into() for safe conversion from usize to i32 + let offset_i32: i32 = offset.try_into().expect("Offset exceeded i32 range"); + let response = query_hosts( &falcon.cfg, - Some(offset as i32), + Some(offset_i32), Some(LIMIT), Some(args.sort.as_str()), args.filter.as_deref(), @@ -65,7 +68,15 @@ async fn main() { details.extend(batch_details); match response.meta.pagination { - Some(pagination) if offset < pagination.total as usize => {} + Some(pagination) => { + // Use `try_from()` to safely convert `i64` to `usize` + if let Ok(total_usize) = usize::try_from(pagination.total) { + if offset < total_usize { + continue; + } + } + break; + } _ => break, }; }