From e309ad884a5d2fc8b78325199cd6e81d2efa220d Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Wed, 10 Apr 2019 22:58:42 -0400 Subject: [PATCH] fix outdated/incorrect docs for `@truncate` closes #2234 --- doc/langref.html.in | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/doc/langref.html.in b/doc/langref.html.in index 1d80c73a3e..a73e5d94d9 100644 --- a/doc/langref.html.in +++ b/doc/langref.html.in @@ -7360,20 +7360,30 @@ fn List(comptime T: type) type {
{#syntax#}@truncate(comptime T: type, integer: var) T{#endsyntax#}

This function truncates bits from an integer type, resulting in a smaller - integer type. + or same-sized integer type.

- The following produces a crash in {#link|Debug#} mode and {#link|Undefined Behavior#} in - {#link|ReleaseFast#} mode: + The following produces safety-checked {#link|Undefined Behavior#}:

-
{#syntax#}const a: u16 = 0xabcd;
-const b: u8 = u8(a);{#endsyntax#}
+ {#code_begin|test_err|cast truncated bits#} +test "integer cast panic" { + var a: u16 = 0xabcd; + var b: u8 = @intCast(u8, a); +} + {#code_end#}

However this is well defined and working code:

-
{#syntax#}const a: u16 = 0xabcd;
-const b: u8 = @truncate(u8, a);
-// b is now 0xcd{#endsyntax#}
+ {#code_begin|test|truncate#} +const std = @import("std"); +const assert = std.debug.assert; + +test "integer truncation" { + var a: u16 = 0xabcd; + var b: u8 = @truncate(u8, a); + assert(b == 0xcd); +} + {#code_end#}

This function always truncates the significant bits of the integer, regardless of endianness on the target platform.