Skip to content

Commit 28342af

Browse files
Remove unnecessary calls to #unsafe_as(UInt64) etc. (#14686)
Rewrites calls of `unsafe_as` which are casting between integer types. These conversions are not unsafe and don't need `unsafe_as`. They can be expressed with appropriate `to_uX!` calls.
1 parent da8a9bd commit 28342af

File tree

3 files changed

+8
-6
lines changed

3 files changed

+8
-6
lines changed

src/compiler/crystal/interpreter/compiler.cr

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3350,7 +3350,7 @@ class Crystal::Repl::Compiler < Crystal::Visitor
33503350
end
33513351

33523352
private def append(value : Int8)
3353-
append value.unsafe_as(UInt8)
3353+
append value.to_u8!
33543354
end
33553355

33563356
private def append(value : Symbol)

src/compiler/crystal/interpreter/instructions.cr

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1472,7 +1472,7 @@ require "./repl"
14721472
symbol_to_s: {
14731473
pop_values: [index : Int32],
14741474
push: true,
1475-
code: @context.index_to_symbol(index).object_id.unsafe_as(UInt64),
1475+
code: @context.index_to_symbol(index).object_id.to_u64!,
14761476
},
14771477
# >>> Symbol (1)
14781478

src/crystal/hasher.cr

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ struct Crystal::Hasher
7777

7878
HASH_NAN = 0_u64
7979
HASH_INF_PLUS = 314159_u64
80-
HASH_INF_MINUS = (-314159_i64).unsafe_as(UInt64)
80+
HASH_INF_MINUS = (-314159_i64).to_u64!
8181

8282
@@seed = uninitialized UInt64[2]
8383
Crystal::System::Random.random_bytes(@@seed.to_slice.to_unsafe_bytes)
@@ -106,7 +106,7 @@ struct Crystal::Hasher
106106
end
107107

108108
def self.reduce_num(value : Int8 | Int16 | Int32)
109-
value.to_i64.unsafe_as(UInt64)
109+
value.to_u64!
110110
end
111111

112112
def self.reduce_num(value : UInt8 | UInt16 | UInt32)
@@ -118,7 +118,9 @@ struct Crystal::Hasher
118118
end
119119

120120
def self.reduce_num(value : Int)
121-
value.remainder(HASH_MODULUS).to_i64.unsafe_as(UInt64)
121+
# The result of `remainder(HASH_MODULUS)` is a 64-bit integer,
122+
# and thus guaranteed to fit into `UInt64`
123+
value.remainder(HASH_MODULUS).to_u64!
122124
end
123125

124126
# This function is for reference implementation, and it is used for `BigFloat`.
@@ -157,7 +159,7 @@ struct Crystal::Hasher
157159
exp = exp >= 0 ? exp % HASH_BITS : HASH_BITS - 1 - ((-1 - exp) % HASH_BITS)
158160
x = ((x << exp) & HASH_MODULUS) | x >> (HASH_BITS - exp)
159161

160-
(x * (value < 0 ? -1 : 1)).to_i64.unsafe_as(UInt64)
162+
(x * (value < 0 ? -1 : 1)).to_u64!
161163
end
162164

163165
def self.reduce_num(value : Float32)

0 commit comments

Comments
 (0)