Skip to content

Commit 3302d3a

Browse files
author
Andrew Haley
committed
8255544: Create a checked cast
Reviewed-by: adinn, iklam
1 parent 54c8813 commit 3302d3a

File tree

2 files changed

+17
-1
lines changed

2 files changed

+17
-1
lines changed

src/hotspot/share/memory/heap.cpp

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -770,7 +770,8 @@ int CodeHeap::segmap_hops(size_t beg, size_t end) {
770770
if (beg < end) {
771771
// setup _segmap pointers for faster indexing
772772
address p = (address)_segmap.low() + beg;
773-
int hops_expected = (int)(((end-beg-1)+(free_sentinel-2))/(free_sentinel-1));
773+
int hops_expected
774+
= checked_cast<int>(((end-beg-1)+(free_sentinel-2))/(free_sentinel-1));
774775
int nhops = 0;
775776
size_t ix = end-beg-1;
776777
while (p[ix] > 0) {

src/hotspot/share/utilities/globalDefinitions.hpp

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -446,6 +446,21 @@ inline size_t pointer_delta(const MetaWord* left, const MetaWord* right) {
446446
#define CAST_TO_FN_PTR(func_type, value) (reinterpret_cast<func_type>(value))
447447
#define CAST_FROM_FN_PTR(new_type, func_ptr) ((new_type)((address_word)(func_ptr)))
448448

449+
// In many places we've added C-style casts to silence compiler
450+
// warnings, for example when truncating a size_t to an int when we
451+
// know the size_t is a small struct. Such casts are risky because
452+
// they effectively disable useful compiler warnings. We can make our
453+
// lives safer with this function, which ensures that any cast is
454+
// reversible without loss of information. It doesn't check
455+
// everything: it isn't intended to make sure that pointer types are
456+
// compatible, for example.
457+
template <typename T2, typename T1>
458+
T2 checked_cast(T1 thing) {
459+
T2 result = static_cast<T2>(thing);
460+
assert(static_cast<T1>(result) == thing, "must be");
461+
return result;
462+
}
463+
449464
// Need the correct linkage to call qsort without warnings
450465
extern "C" {
451466
typedef int (*_sort_Fn)(const void *, const void *);

0 commit comments

Comments
 (0)