authorgravatar for stel@comfy.monsterpraschke <stel@comfy.monster> 2021-11-28 11:28:47+00:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2022-02-02 22:00:00-07:00
log2b29424efd05fb059ba35f16eb804613676c869d
tree1c9e1f3119ed6a92862891629b6995549c3c20ea
parent8f89056dc27a77e0e35739db5b4310e68a49d9d3

docs: reorganize `@truncate` and `@intCast` for clarity


1 files changed, 14 insertions(+), 11 deletions(-)

doc/langref.html.in+14-11
...@@ -8537,6 +8537,16 @@ test "@hasDecl" {...@@ -8537,6 +8537,16 @@ test "@hasDecl" {
8537 Attempting to convert a number which is out of range of the destination type results in8537 Attempting to convert a number which is out of range of the destination type results in
8538 safety-protected {#link|Undefined Behavior#}.8538 safety-protected {#link|Undefined Behavior#}.
8539 </p>8539 </p>
8540 {#code_begin|test_err|cast truncated bits#}
8541test "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 <p>8550 <p>
8541 If {#syntax#}T{#endsyntax#} is {#syntax#}comptime_int{#endsyntax#},8551 If {#syntax#}T{#endsyntax#} is {#syntax#}comptime_int{#endsyntax#},
8542 then this is semantically equivalent to {#link|Type Coercion#}.8552 then this is semantically equivalent to {#link|Type Coercion#}.
...@@ -9380,17 +9390,11 @@ fn List(comptime T: type) type {...@@ -9380,17 +9390,11 @@ fn List(comptime T: type) type {
9380 or same-sized integer type.9390 or same-sized integer type.
9381 </p>9391 </p>
9382 <p>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 </p>9395 </p>
9385 {#code_begin|test_err|cast truncated bits#}
9386test "integer cast panic" {
9387 var a: u16 = 0xabcd;
9388 var b: u8 = @intCast(u8, a);
9389 _ = b;
9390}
9391 {#code_end#}
9392 <p>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 </p>9398 </p>
9395 {#code_begin|test|truncate#}9399 {#code_begin|test|truncate#}
9396const std = @import("std");9400const std = @import("std");
...@@ -9403,8 +9407,7 @@ test "integer truncation" {...@@ -9403,8 +9407,7 @@ test "integer truncation" {
9403}9407}
9404 {#code_end#}9408 {#code_end#}
9405 <p>9409 <p>
9406 This function always truncates the significant bits of the integer, regardless9410 Use {#link|@intCast#} to convert numbers guaranteed to fit the destination type.
9407 of endianness on the target platform.
9408 </p>9411 </p>
9409 {#header_close#}9412 {#header_close#}
94109413