Skip to content

Commit b050976

Browse files
Fix clippy::cast_possible_truncation (#1423)
1 parent 9fcf5b1 commit b050976

27 files changed

Lines changed: 158 additions & 87 deletions

.bazelrc

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,7 @@ build --@rules_rust//:clippy_flag=-Wclippy::unimplemented
120120
build --@rules_rust//:clippy_flag=-Aclippy::unwrap_in_result
121121
build --@rules_rust//:clippy_flag=-Aclippy::unwrap_used
122122
build --@rules_rust//:clippy_flag=-Wclippy::use_debug
123-
build --@rules_rust//:clippy_flag=-Aclippy::cast_possible_truncation
123+
build --@rules_rust//:clippy_flag=-Dclippy::cast_possible_truncation
124124
build --@rules_rust//:clippy_flag=-Aclippy::cast_possible_wrap
125125
build --@rules_rust//:clippy_flag=-Aclippy::cast_precision_loss
126126
build --@rules_rust//:clippy_flag=-Aclippy::cast_sign_loss

Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -180,7 +180,7 @@ too-long-first-doc-paragraph = { level = "allow" } # TODO(jhpratt)
180180
uninhabited-references = { level = "allow", priority = 1 } # rust-lang/rust-clippy#11984
181181

182182
# TODO(palfrey): Remove these to get to pedantic.
183-
cast_possible_truncation = { level = "allow", priority = 1 }
183+
cast_possible_truncation = { level = "deny", priority = 1 }
184184
cast_possible_wrap = { level = "allow", priority = 1 }
185185
cast_precision_loss = { level = "allow", priority = 1 }
186186
cast_sign_loss = { level = "allow", priority = 1 }

nativelink-scheduler/src/awaited_action_db/awaited_action.rs

Lines changed: 19 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -239,29 +239,36 @@ impl MetricsComponent for AwaitedActionSortKey {
239239
}
240240

241241
impl AwaitedActionSortKey {
242-
#[rustfmt::skip]
243242
const fn new(priority: i32, insert_timestamp: u32) -> Self {
244-
// Shift `new_priority` so [`i32::MIN`] is represented by zero.
245-
// This makes it so any negative values are positive, but
246-
// maintains ordering.
247-
const MIN_I32: i64 = (i32::MIN as i64).abs();
248-
let priority = ((priority as i64 + MIN_I32) as u32).to_be_bytes();
243+
// Shift the signed i32 range [i32::MIN, i32::MAX] to the unsigned u32 range
244+
// [0, u32::MAX] to preserve ordering when we convert to bytes for sorting.
245+
let priority_u32 = i32::MIN.unsigned_abs().wrapping_add_signed(priority);
246+
let priority = priority_u32.to_be_bytes();
249247

250248
// Invert our timestamp so the larger the timestamp the lower the number.
251249
// This makes timestamp descending order instead of ascending.
252250
let timestamp = (insert_timestamp ^ u32::MAX).to_be_bytes();
253251

254252
Self(u64::from_be_bytes([
255-
priority[0], priority[1], priority[2], priority[3],
256-
timestamp[0], timestamp[1], timestamp[2], timestamp[3],
253+
priority[0],
254+
priority[1],
255+
priority[2],
256+
priority[3],
257+
timestamp[0],
258+
timestamp[1],
259+
timestamp[2],
260+
timestamp[3],
257261
]))
258262
}
259263

260264
fn new_with_unique_key(priority: i32, insert_timestamp: &SystemTime) -> Self {
261-
let timestamp = insert_timestamp
262-
.duration_since(UNIX_EPOCH)
263-
.unwrap()
264-
.as_secs() as u32;
265+
let timestamp = u32::try_from(
266+
insert_timestamp
267+
.duration_since(UNIX_EPOCH)
268+
.unwrap()
269+
.as_secs(),
270+
)
271+
.unwrap_or(u32::MAX);
265272
Self::new(priority, timestamp)
266273
}
267274

nativelink-scheduler/tests/redis_store_awaited_action_db_test.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -247,7 +247,7 @@ impl Mocks for FakeRedisBackend {
247247
}
248248
}
249249
}
250-
results[0] = ((results.len() - 1) as u32).into();
250+
results[0] = u32::try_from(results.len() - 1).unwrap_or(u32::MAX).into();
251251
return Ok(RedisValue::Array(vec![
252252
RedisValue::Array(results),
253253
RedisValue::Integer(0), // Means no more items in cursor.

nativelink-service/src/bytestream_server.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -494,9 +494,10 @@ impl ByteStreamServer {
494494
}
495495
continue;
496496
}
497-
write_request
498-
.data
499-
.slice((tx.get_bytes_written() - write_offset) as usize..)
497+
write_request.data.slice(
498+
usize::try_from(tx.get_bytes_written() - write_offset)
499+
.unwrap_or(usize::MAX)..,
500+
)
500501
} else {
501502
if write_offset != tx.get_bytes_written() {
502503
return Err(make_input_err!(

nativelink-service/src/cas_server.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -278,9 +278,12 @@ impl CasServer {
278278
.err_tip(|| "In Directory::file::digest")?;
279279
deque.push_back(digest);
280280
}
281+
282+
let page_size_usize = usize::try_from(page_size).unwrap_or(usize::MAX);
283+
281284
if page_token_matched {
282285
directories.push(directory);
283-
if directories.len() as i32 == page_size {
286+
if directories.len() == page_size_usize {
284287
break;
285288
}
286289
}

nativelink-service/tests/bep_server_test.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -331,7 +331,10 @@ async fn publish_build_tool_event_stream_test() -> Result<(), Box<dyn core::erro
331331
let (mut writer, mut reader) = make_buf_channel_pair();
332332
bep_store
333333
.get_part(
334-
store_keys[sequence_number as usize - 1].clone(),
334+
store_keys[usize::try_from(sequence_number)
335+
.expect("sequence_number exceeds usize::MAX")
336+
- 1]
337+
.clone(),
335338
&mut writer,
336339
0,
337340
None,

nativelink-store/src/compression_store.rs

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -195,7 +195,8 @@ impl UploadState {
195195
usize::try_from(max_index_count)
196196
.err_tip(|| "Could not convert max_index_count to usize")?
197197
],
198-
index_count: max_index_count as u32,
198+
index_count: u32::try_from(max_index_count)
199+
.err_tip(|| "Could not convert max_index_count to u32")?,
199200
uncompressed_data_size: 0, // Updated later.
200201
config: header.config,
201202
version: CURRENT_STREAM_FORMAT_VERSION,
@@ -361,14 +362,18 @@ impl StoreDriver for CompressionStore {
361362
}
362363

363364
// Now fill the size in our slice.
364-
LittleEndian::write_u32(&mut compressed_data_buf[1..5], compressed_data_sz as u32);
365+
LittleEndian::write_u32(
366+
&mut compressed_data_buf[1..5],
367+
u32::try_from(compressed_data_sz).unwrap_or(u32::MAX),
368+
);
365369

366370
// Now send our chunk.
367371
tx.send(compressed_data_buf.freeze())
368372
.await
369373
.err_tip(|| "Failed to write chunk to inner store in compression store")?;
370374

371-
index.position_from_prev_index = compressed_data_sz as u32;
375+
index.position_from_prev_index =
376+
u32::try_from(compressed_data_sz).unwrap_or(u32::MAX);
372377

373378
index_count += 1;
374379
}
@@ -384,7 +389,8 @@ impl StoreDriver for CompressionStore {
384389
.footer
385390
.indexes
386391
.resize(index_count as usize, SliceIndex::default());
387-
output_state.footer.index_count = output_state.footer.indexes.len() as u32;
392+
output_state.footer.index_count =
393+
u32::try_from(output_state.footer.indexes.len()).unwrap_or(u32::MAX);
388394
output_state.footer.uncompressed_data_size = received_amt;
389395
{
390396
// Write Footer.
@@ -395,7 +401,7 @@ impl StoreDriver for CompressionStore {
395401

396402
let mut footer = BytesMut::with_capacity(1 + 4 + serialized_footer.len());
397403
footer.put_u8(FOOTER_FRAME_TYPE);
398-
footer.put_u32_le(serialized_footer.len() as u32);
404+
footer.put_u32_le(u32::try_from(serialized_footer.len()).unwrap_or(u32::MAX));
399405
footer.extend_from_slice(&serialized_footer);
400406

401407
tx.send(footer.freeze())
@@ -453,7 +459,7 @@ impl StoreDriver for CompressionStore {
453459
};
454460
let header_size = serialized_size(&EMPTY_HEADER, self.bincode_config)?;
455461
let chunk = rx
456-
.consume(Some(header_size as usize))
462+
.consume(Some(usize::try_from(header_size).unwrap_or(usize::MAX)))
457463
.await
458464
.err_tip(|| "Failed to read header in get_part compression store")?;
459465
error_if!(
@@ -536,9 +542,13 @@ impl StoreDriver for CompressionStore {
536542
let new_uncompressed_data_sz =
537543
uncompressed_data_sz + uncompressed_chunk_sz as u64;
538544
if new_uncompressed_data_sz >= offset && remaining_bytes_to_send > 0 {
539-
let start_pos = offset.saturating_sub(uncompressed_data_sz) as usize;
545+
let start_pos =
546+
usize::try_from(offset.saturating_sub(uncompressed_data_sz))
547+
.unwrap_or(usize::MAX);
540548
let end_pos = cmp::min(
541-
start_pos + remaining_bytes_to_send as usize,
549+
start_pos.saturating_add(
550+
usize::try_from(remaining_bytes_to_send).unwrap_or(usize::MAX),
551+
),
542552
uncompressed_chunk_sz,
543553
);
544554
if end_pos != start_pos {

nativelink-store/src/filesystem_store.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -454,7 +454,7 @@ async fn add_files_to_cache<Fe: FileEntry>(
454454
.insert_with_time(
455455
key.into_owned().into(),
456456
Arc::new(file_entry),
457-
time_since_anchor.as_secs() as i32,
457+
i32::try_from(time_since_anchor.as_secs()).unwrap_or(i32::MAX),
458458
)
459459
.await;
460460
Ok(())

nativelink-store/src/gcs_client/client.rs

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -233,9 +233,12 @@ impl GcsClient {
233233
reader: &mut DropCloserReadHalf,
234234
max_size: u64,
235235
) -> Result<(), Error> {
236-
let initial_capacity = core::cmp::min(max_size as usize, 10 * 1024 * 1024);
236+
let initial_capacity = core::cmp::min(
237+
usize::try_from(max_size).unwrap_or(usize::MAX),
238+
10 * 1024 * 1024,
239+
);
237240
let mut data = Vec::with_capacity(initial_capacity);
238-
let max_size = max_size as usize;
241+
let max_size = usize::try_from(max_size).unwrap_or(usize::MAX);
239242
let mut total_size = 0usize;
240243

241244
while total_size < max_size {
@@ -286,7 +289,7 @@ impl GcsClient {
286289

287290
// Upload data in chunks
288291
let mut offset: u64 = 0;
289-
let max_size = max_size as usize;
292+
let max_size = usize::try_from(max_size).unwrap_or(usize::MAX);
290293
let mut total_uploaded = 0usize;
291294

292295
while total_uploaded < max_size {
@@ -559,7 +562,11 @@ impl GcsOperations for GcsClient {
559562

560563
let mut rng = rand::rng();
561564
let jitter_factor = rng.random::<f64>().mul_add(0.4, 0.8);
562-
retry_delay = (retry_delay as f64 * jitter_factor) as u64;
565+
retry_delay = Duration::from_millis(retry_delay)
566+
.mul_f64(jitter_factor)
567+
.as_millis()
568+
.try_into()
569+
.unwrap_or(u64::MAX);
563570

564571
retry_count += 1;
565572
}

0 commit comments

Comments
 (0)