🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.arch
Article #28

Re: Optimization by programmers

#28
From: Dan Cross
Date: Thu, 08 Oct 2026 22:55
127 lines
5351 bytes
In article <jbPxS.600$MBQb.166@fx08.iad>,
EricP  <ThatWouldBeTelling@thevillage.com> wrote:
>[snip]
>The reference is less see-spot-run
>
>https://doc.rust-lang.org/stable/reference/
>
>Looking at the rules for type casting:
>
>https://doc.rust-lang.org/stable/reference/expressions/operator-expr.html#numeric-cast
>
>Some initial thoughts:
>
>There are no value range checks between cast types, just bit-wise reinterpretation
>to the new type with possible sign/zero extension or truncation for size change.
>
>They don't define the order in which those two operations, type and size change, occur.
>If one casts an i8 into a u16 it doesn't say whether the value is sign extended
>to i16 first then type changed to u16, or type changed to u8 first then zero
>extended to u16.

They do, but it requires looking at _two_ rules from that list.

The first,

|Casting between two integers of the same size (e.g. i32 -> u32)
|is a no-op (Rust uses 2’s complement for negative values of
|fixed integers)

and the third,

|Casting from a smaller integer to a larger integer (e.g. u8 ->
|u32) will
|
| * zero-extend if the source is unsigned
| * sign-extend if the source is signed

Note that the second of these, the third rule on the list,
mentions sign extension if the _source_ type is signed; the
signedness of the destination is not relevant.

Taken together, these imply that the source will be
sign-extended and then the conversion to unsigned will be
treated as a noop: rule #1 does not apply first because it is
specific to conversions between sign/unsigned integers of the
_same width_; so we start with rule #3, sign-extend, and _then_
we may apply rule #1.

For a negative value of a source type that is smaller than an
unsigned destination type, the result will be an unsigned value
in the upper half of the destination type's range.

term% cat cast.rs
fn main() {
    let n: i8 = -2;
    println!("-2 as u16 = {}", n as u16);
}
term% rustc cast.rs
term% ./cast
-2 as u16 = 65534
term%

If you wanted to force specific behavior, you could use multiple
casts (e.g., `n as u8 as u16`).

>Since an array index is defined as type usize, if the index expression
>is signed then it will be bit-wise reinterpreted as unsigned,

No, if the index expression is signed, it will be a compile-time
error since usize is, by definiton, unsigned, and usize is the
only permissible index type.  Rust is statically typed, and
there are no implicit conversions that factor here.

>and possibly turn a negative value into a large positive usize
>value.

In order for this to happen, one would have to use an explicit
cast to make the negative value a `usize` first.

A fair followup question is, "suppose I do a comparison against
a signed type, but don't account for zero, and then convert it
to usize; could the optimizer remove the bounds checks?"  For
example, this:

```rust
#[inline(never)]
pub fn get_a_number(k: i32) -> i32 {
    const ARR: [i32; 10] = [500, 1, 200, 3, 410, 5, 37, 7, 8, -5];
    if k < 10 { ARR[k as usize] } else { 0 }
}
```

When built with optimization enabled and linked with a simple
driver, panic's at runtime trying to use a negative value cast
to a (large) positive value as an index.  On the other hand, if
I modify it to check the lower bound on the array, that is
optimized away.  So this version,

```rust
#[inline(never)]
pub fn get_a_number(k: i32) -> i32 {
    const ARR: [i32; 10] = [500, 1, 200, 3, 410, 5, 37, 7, 8, -5];
    if 0 <= k && k < 10 { ARR[k as usize] } else { 0 }
}
```
yields this object code on x86_64:
```
0000000000014ad0 <rbounds::get_a_number>:
   14ad0:       31 c0                   xor    %eax,%eax
   14ad2:       83 ff 0a                cmp    $0xa,%edi
   14ad5:       73 0c                   jae    14ae3 <rbounds::get_a_number+0x13>
   14ad7:       89 f8                   mov    %edi,%eax
   14ad9:       48 8d 0d 04 19 ff ff    lea    -0xe6fc(%rip),%rcx        # 63e4 <__abi_tag+0x60e8>
   14ae0:       8b 04 81                mov    (%rcx,%rax,4),%eax
   14ae3:       c3                      ret
   14ae4:       cc                      int3
   ...
   14aef:       cc                      int3
```

>If bounds checks are disabled for
>production builds then you get exactly the same array overflow as in C.

See above.

	- Dan C.
Technical Details
Message-ID: <11a9704$ruu$1@reader2.panix.com>
Path: mbox-mo1.pugleaf.net!archive.usenet.blueworldhosting.com!usenet.blueworldhosting.com!diablo1.usenet.blueworldhosting.com!panix!.POSTED.spitfire.i.gajendra.net!not-for-mail
References: <1177fdi$26ea4$1@dont-email.me> <11a024r$f52$1@reader2.panix.com> <20261007222539.000033d0@yahoo.com> <jbPxS.600$MBQb.166@fx08.iad>

Show Full Headers
Complete Article Headers
Path: mbox-mo1.pugleaf.net!archive.usenet.blueworldhosting.com!usenet.blueworldhosting.com!diablo1.usenet.blueworldhosting.com!panix!.POSTED.spitfire.i.gajendra.net!not-for-mail
From: cross@spitfire.i.gajendra.net (Dan Cross)
Newsgroups: comp.arch
Subject: Re: Optimization by programmers
Date: Thu, 8 Oct 2026 22:55:00 -0000 (UTC)
Organization: PANIX Public Access Internet and UNIX, NYC
Message-ID: <11a9704$ruu$1@reader2.panix.com>
References: <1177fdi$26ea4$1@dont-email.me> <11a024r$f52$1@reader2.panix.com> <20261007222539.000033d0@yahoo.com> <jbPxS.600$MBQb.166@fx08.iad>
Injection-Date: Thu, 8 Oct 2026 22:55:00 -0000 (UTC)
Injection-Info: reader2.panix.com; posting-host="spitfire.i.gajendra.net:166.84.136.80";
	logging-data="28638"; mail-complaints-to="abuse@panix.com"
X-Newsreader: trn 4.0-test77 (Sep 1, 2010)
Originator: cross@spitfire.i.gajendra.net (Dan Cross)