You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Update shifting operations guidelines in expressions.rst
Clarify rules for shifting operations in Rust, emphasizing the importance of using checked functions and addressing inconsistent behavior in different compilation modes.
Copy file name to clipboardExpand all lines: src/coding-guidelines/expressions.rst
+10-12Lines changed: 10 additions & 12 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -795,7 +795,6 @@ Expressions
795
795
796
796
This rule applies to the following primitive types:
797
797
798
-
799
798
* ``i8``
800
799
* ``i16``
801
800
* ``i32``
@@ -815,37 +814,36 @@ Expressions
815
814
816
815
This is a Subset rule, directly inspired by `INT34-C. Do not shift an expression by a negative number of bits or by greater than or equal to the number of bits that exist in the operand <https://wiki.sei.cmu.edu/confluence/x/ItcxBQ>`_.
817
816
818
-
In Rust these out-of-range shifts don't give rise to Undefined Behavior; however, they are still problematic in Safety Critical contexts for two reasons.
817
+
Out-of-range shifts are not undefined behavior, but are problematic for the following reasons:
819
818
820
819
821
820
*
822
-
**Reason 1: inconsistent behavior**
821
+
**Inconsistent behavior**
823
822
824
-
The behavior of shift operations depends on the compilation mode. Say for example, that we have a number ``x`` of type ``uN``\ , and we perform the operation
823
+
The behavior of shift operations depends on the compilation mode.
824
+
A shift of an unsigned integer value ``x`` by ``M`` positions:
Note: the behavior is exactly the same for the ``>>`` operator.
841
-
842
-
843
841
Panicking in ``Debug`` is an issue by itself, however, a perhaps larger issue there is that its behavior is different from that of ``Release``. Such inconsistencies aren't acceptable in Safety Critical scenarios.
844
842
845
843
Therefore, a consistently-behaved operation should be required for performing shifts.
846
844
847
845
*
848
-
**Reason 2: programmer intent**
846
+
**Programmer intent**
849
847
850
848
There is no scenario in which it makes sense to perform a shift of negative length, or of more than ``N - 1`` bits. The operation itself becomes meaningless.
0 commit comments