| ... | ... | @@ -7360,20 +7360,30 @@ fn List(comptime T: type) type { |
| 7360 | 7360 | <pre>{#syntax#}@truncate(comptime T: type, integer: var) T{#endsyntax#}</pre> |
| 7361 | 7361 | <p> |
| 7362 | 7362 | This function truncates bits from an integer type, resulting in a smaller |
| 7363 | | integer type. |
| 7363 | or same-sized integer type. |
| 7364 | 7364 | </p> |
| 7365 | 7365 | <p> |
| 7366 | | The following produces a crash in {#link|Debug#} mode and {#link|Undefined Behavior#} in |
| 7367 | | {#link|ReleaseFast#} mode: |
| 7366 | The following produces safety-checked {#link|Undefined Behavior#}: |
| 7368 | 7367 | </p> |
| 7369 | | <pre>{#syntax#}const a: u16 = 0xabcd; |
| 7370 | | const b: u8 = u8(a);{#endsyntax#}</pre> |
| 7368 | {#code_begin|test_err|cast truncated bits#} |
| 7369 | test "integer cast panic" { |
| 7370 | var a: u16 = 0xabcd; |
| 7371 | var b: u8 = @intCast(u8, a); |
| 7372 | } |
| 7373 | {#code_end#} |
| 7371 | 7374 | <p> |
| 7372 | 7375 | However this is well defined and working code: |
| 7373 | 7376 | </p> |
| 7374 | | <pre>{#syntax#}const a: u16 = 0xabcd; |
| 7375 | | const b: u8 = @truncate(u8, a); |
| 7376 | | // b is now 0xcd{#endsyntax#}</pre> |
| 7377 | {#code_begin|test|truncate#} |
| 7378 | const std = @import("std"); |
| 7379 | const assert = std.debug.assert; |
| 7380 | |
| 7381 | test "integer truncation" { |
| 7382 | var a: u16 = 0xabcd; |
| 7383 | var b: u8 = @truncate(u8, a); |
| 7384 | assert(b == 0xcd); |
| 7385 | } |
| 7386 | {#code_end#} |
| 7377 | 7387 | <p> |
| 7378 | 7388 | This function always truncates the significant bits of the integer, regardless |
| 7379 | 7389 | of endianness on the target platform. |