Skip to content

Commit

Permalink
Remove unnecessary calls to #unsafe_as(UInt64) etc. (#14686)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
straight-shoota committed Jun 25, 2024
1 parent da8a9bd commit 28342af
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 6 deletions.
2 changes: 1 addition & 1 deletion src/compiler/crystal/interpreter/compiler.cr
Original file line number Diff line number Diff line change
Expand Up @@ -3350,7 +3350,7 @@ class Crystal::Repl::Compiler < Crystal::Visitor
end

private def append(value : Int8)
append value.unsafe_as(UInt8)
append value.to_u8!
end

private def append(value : Symbol)
Expand Down
2 changes: 1 addition & 1 deletion src/compiler/crystal/interpreter/instructions.cr
Original file line number Diff line number Diff line change
Expand Up @@ -1472,7 +1472,7 @@ require "./repl"
symbol_to_s: {
pop_values: [index : Int32],
push: true,
code: @context.index_to_symbol(index).object_id.unsafe_as(UInt64),
code: @context.index_to_symbol(index).object_id.to_u64!,
},
# >>> Symbol (1)

Expand Down
10 changes: 6 additions & 4 deletions src/crystal/hasher.cr
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ struct Crystal::Hasher

HASH_NAN = 0_u64
HASH_INF_PLUS = 314159_u64
HASH_INF_MINUS = (-314159_i64).unsafe_as(UInt64)
HASH_INF_MINUS = (-314159_i64).to_u64!

@@seed = uninitialized UInt64[2]
Crystal::System::Random.random_bytes(@@seed.to_slice.to_unsafe_bytes)
Expand Down Expand Up @@ -106,7 +106,7 @@ struct Crystal::Hasher
end

def self.reduce_num(value : Int8 | Int16 | Int32)
value.to_i64.unsafe_as(UInt64)
value.to_u64!
end

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

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

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

(x * (value < 0 ? -1 : 1)).to_i64.unsafe_as(UInt64)
(x * (value < 0 ? -1 : 1)).to_u64!
end

def self.reduce_num(value : Float32)
Expand Down

0 comments on commit 28342af

Please sign in to comment.