fix(chainbase): Implicit narrowing conversion in compound assignment #6420
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Compound assignment statements of the form x += y or x *= y perform an implicit narrowing conversion if the type of x is narrower than the type of y. For example, x += y is equivalent to x = (T)(x + y), where T is the type of x. This can result in information loss and numeric errors such as overflows.
fix the problem, we should avoid the implicit narrowing conversion in the compound assignment. Instead of using
v += 27;
(which implicitly casts the result ofv + 27
fromint
tobyte
), we should perform the addition inint
and then explicitly cast the result tobyte
when assigning it back tov
. This makes the narrowing conversion explicit and clear to readers and static analysis tools.Specifically, in
getBase64FromByteString
, replace:with:
No new imports or method definitions are needed.
References
Compound Assignment Operators, Narrowing Primitive Conversion
SEI CERT Oracle Coding Standard for Java: NUM00-J. Detect or prevent integer overflow