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