| ... | ... | @@ -8537,6 +8537,16 @@ test "@hasDecl" { |
| 8537 | 8537 | Attempting to convert a number which is out of range of the destination type results in |
| 8538 | 8538 | safety-protected {#link|Undefined Behavior#}. |
| 8539 | 8539 | </p> |
| 8540 | {#code_begin|test_err|cast truncated bits#} |
| 8541 | test "integer cast panic" { |
| 8542 | var a: u16 = 0xabcd; |
| 8543 | var b: u8 = @intCast(u8, a); |
| 8544 | _ = b; |
| 8545 | } |
| 8546 | {#code_end#} |
| 8547 | <p> |
| 8548 | To truncate the significant bits of a number out of range of the destination type, use {#link|@truncate#}. |
| 8549 | </p> |
| 8540 | 8550 | <p> |
| 8541 | 8551 | If {#syntax#}T{#endsyntax#} is {#syntax#}comptime_int{#endsyntax#}, |
| 8542 | 8552 | then this is semantically equivalent to {#link|Type Coercion#}. |
| ... | ... | @@ -9380,17 +9390,11 @@ fn List(comptime T: type) type { |
| 9380 | 9390 | or same-sized integer type. |
| 9381 | 9391 | </p> |
| 9382 | 9392 | <p> |
| 9383 | | The following produces safety-checked {#link|Undefined Behavior#}: |
| 9393 | This function always truncates the significant bits of the integer, regardless |
| 9394 | of endianness on the target platform. |
| 9384 | 9395 | </p> |
| 9385 | | {#code_begin|test_err|cast truncated bits#} |
| 9386 | | test "integer cast panic" { |
| 9387 | | var a: u16 = 0xabcd; |
| 9388 | | var b: u8 = @intCast(u8, a); |
| 9389 | | _ = b; |
| 9390 | | } |
| 9391 | | {#code_end#} |
| 9392 | 9396 | <p> |
| 9393 | | However this is well defined and working code: |
| 9397 | Calling {#syntax#}@truncate{#endsyntax#} on a number out of range of the destination type is well defined and working code: |
| 9394 | 9398 | </p> |
| 9395 | 9399 | {#code_begin|test|truncate#} |
| 9396 | 9400 | const std = @import("std"); |
| ... | ... | @@ -9403,8 +9407,7 @@ test "integer truncation" { |
| 9403 | 9407 | } |
| 9404 | 9408 | {#code_end#} |
| 9405 | 9409 | <p> |
| 9406 | | This function always truncates the significant bits of the integer, regardless |
| 9407 | | of endianness on the target platform. |
| 9410 | Use {#link|@intCast#} to convert numbers guaranteed to fit the destination type. |
| 9408 | 9411 | </p> |
| 9409 | 9412 | {#header_close#} |
| 9410 | 9413 | |