Improve as guideline (gui_ADHABsmK9FXz)#426
Improve as guideline (gui_ADHABsmK9FXz)#426inkreasing wants to merge 1 commit intorustfoundation:mainfrom
Conversation
❌ Deploy Preview for scrc-coding-guidelines failed.
|
|
|
||
| **Exception:** ``as`` may be used with ``usize`` as the right operand and an expression of raw pointer | ||
| type as the left operand. | ||
| **Exception:** ``as`` may be used with an integer type as the right operand and an expression of floating |
There was a problem hiding this comment.
i added this exception because there is no way to go from float to int otherwise. If you want i can also remove this.
| A pointer-to-address cast does not lose value, but will be truncated unless the destination type is large | ||
| enough to hold the address value. The ``usize`` type is guaranteed to be wide enough for this purpose. | ||
| A pointer-to-address or address-to-pointer cast should be performed using the exposed or strict provenance APIs | ||
| (``addr``, ``expose_provenance``, ``with_addr`` or ``with_exposed_provenance``). |
There was a problem hiding this comment.
i would like to link to guideline that explains exposed and strict provenance and recommends one of them (probably strict). Depending on how strongly you want to discourage exposed i can also remove the suggestion here.
| let _a1 = p1 as usize; // compliant by exception | ||
| let _a2 = p1 as u16; // non-compliant - may lose address range | ||
| let _a3 = p1 as u64; // non-compliant - use usize to indicate intent | ||
| let _a3 = p1 as u64; // non-compliant - use .addr() or .expose_provenance() |
There was a problem hiding this comment.
could also remove exposed provance suggestion if you want
| Valid conversions that risk losing value, where doing so would be an error, can | ||
| communicate this and include an error check, with ``try_into`` or ``try_from``. | ||
| Other forms of conversion may find ``transmute`` better communicates their intent. | ||
| Other forms of conversion may find explicit functions better communicate their intent. |
There was a problem hiding this comment.
this sentence is really general now, but there are a lot of methods depending on the type and the conversion that should be done.
| // does something entirely different, | ||
| // reinterpreting the bits of z as the IEEE bit pattern of a double | ||
| // precision object, rather than converting the integer value | ||
| let _f1: f64 = _z.to_bits(); |
There was a problem hiding this comment.
don't know if this example is useful. It doesn't replace an as it does something completely different. But it shouldn't use transmute
|
Is the CI failure actually because of this PR or is it #425? |
should help with #338.
I don't know if the state of the guideline is "good" after this PR, but at least it's not indirectly recommending doing UB anymore.