Skip to content

Commit

Permalink
Avoid the use of overflowing_literals in the examples
Browse files Browse the repository at this point in the history
I think that it could have some potential confusion since it isn't
displayed in the text that these are overflowing, and it requires
an extra layer of reasoning needed to understand how it translates.
  • Loading branch information
ehuss committed Nov 14, 2024
1 parent 4226cec commit bb6f41b
Showing 1 changed file with 2 additions and 6 deletions.
8 changes: 2 additions & 6 deletions src/expressions/operator-expr.md
Original file line number Diff line number Diff line change
Expand Up @@ -400,39 +400,35 @@ reference types and `mut` or `const` in pointer types.
(Rust uses 2's complement for negative values of fixed integers)

```rust
# #![allow(overflowing_literals)]
assert_eq!(42i8 as u8, 42u8);
assert_eq!(-1i8 as u8, 255u8);
assert_eq!(255u8 as i8, -1i8);
assert_eq!(0xffu8 as i8, 0xffi8);
assert_eq!(-1i16 as u16, 65535u16);
```

* Casting from a larger integer to a smaller integer (e.g. u32 -> u8) will
truncate

```rust
# #![allow(overflowing_literals)]
assert_eq!(42u16 as u8, 42u8);
assert_eq!(1234u16 as u8, 210u8);
assert_eq!(0xabcdu16 as u8, 0xcdu8);

assert_eq!(-42i16 as i8, -42i8);
assert_eq!(1234u16 as i8, -46i8);
assert_eq!(0xabcdi16 as i8, 0xcdi8);
assert_eq!(0xabcdi32 as i8, -51i8);
```

* 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

```rust
# #![allow(overflowing_literals)]
assert_eq!(42i8 as i16, 42i16);
assert_eq!(-17i8 as i16, -17i16);
assert_eq!(0b1000_1010u8 as u16, 0b0000_0000_1000_1010u16, "Zero-extend");
assert_eq!(0b0000_1010i8 as i16, 0b0000_0000_0000_1010i16, "Sign-extend 0");
assert_eq!(0b1000_1010i8 as i16, 0b1111_1111_1000_1010i16, "Sign-extend 1");
assert_eq!(0b1000_1010u8 as i8 as i16, 0b1111_1111_1000_1010u16 as i16, "Sign-extend 1");
```

* Casting from a float to an integer will round the float towards zero
Expand Down

0 comments on commit bb6f41b

Please sign in to comment.