132 lines
2.4 KiB
Markdown
132 lines
2.4 KiB
Markdown
# Exemples / DO-DON'T — Chapitre 24 — Casts et conversions
|
|
|
|
> Document compagnon. Les exemples illustrent les règles du chapitre ; la formulation normative reste dans le chapitre lui-même.
|
|
|
|
## Conversion explicite
|
|
|
|
```text
|
|
int8 small = ...;
|
|
int32 large = small; // ERROR
|
|
int32 explicitLarge = small::toInt32(); // OK
|
|
```
|
|
|
|
## Widening total
|
|
|
|
```text
|
|
int8 value = ...;
|
|
int32 larger = value::toInt32();
|
|
```
|
|
|
|
Aucun `tryToInt32()` parallèle n'est nécessaire si toutes les valeurs source sont exactement représentables.
|
|
|
|
## Narrowing exact avec `Fault`
|
|
|
|
```text
|
|
int32 value = ...;
|
|
int8 smaller = value::toInt8();
|
|
```
|
|
|
|
La signature Core peut déclarer :
|
|
|
|
```text
|
|
toInt8() -> int8
|
|
faults NumericConversionFault
|
|
```
|
|
|
|
`OutOfRange` est produit lorsque la valeur ne tient pas dans `int8`.
|
|
|
|
## Politiques distinctes
|
|
|
|
```text
|
|
value::toInt8() // exact, peut fault
|
|
value::saturateToInt8()
|
|
value::wrapToInt8()
|
|
```
|
|
|
|
Ces opérations coexistent seulement lorsque leur résultat peut réellement différer.
|
|
|
|
## Flottant vers entier
|
|
|
|
```text
|
|
float64 value = ...;
|
|
|
|
int32 exact = value::toInt32();
|
|
```
|
|
|
|
La conversion exige une valeur finie, intégrale et dans la plage.
|
|
|
|
Pour choisir explicitement une politique mathématique :
|
|
|
|
```text
|
|
value::floor()::toInt32()
|
|
value::ceil()::toInt32()
|
|
value::round()::toInt32()
|
|
value::truncate()::toInt32()
|
|
```
|
|
|
|
Pour choisir la politique de plage :
|
|
|
|
```text
|
|
value::floor()::saturateToInt32()
|
|
value::round()::wrapToInt32()
|
|
```
|
|
|
|
## Entier vers flottant
|
|
|
|
```text
|
|
int64 value = ...;
|
|
|
|
float64 exact = value::toFloat64();
|
|
float64 approximated = value::roundToFloat64();
|
|
```
|
|
|
|
`toFloat64()` exige l'exactitude ; `roundToFloat64()` accepte explicitement la perte de précision.
|
|
|
|
## Flottant vers flottant
|
|
|
|
```text
|
|
toFloatXX()
|
|
exige l'exactitude
|
|
|
|
roundToFloatXX()
|
|
accepte l'arrondi canonique
|
|
peut fault OutOfRange sur une valeur finie
|
|
|
|
saturatingRoundToFloatXX()
|
|
accepte l'arrondi canonique
|
|
sature une valeur finie hors domaine
|
|
```
|
|
|
|
Les catégories suivantes sont préservées :
|
|
|
|
```text
|
|
NaN -> NaN
|
|
+Infinity -> +Infinity
|
|
-Infinity -> -Infinity
|
|
+0 -> +0
|
|
-0 -> -0
|
|
```
|
|
|
|
## `NumericConversionFault`
|
|
|
|
```text
|
|
NumericConversionFault extends Fault
|
|
```
|
|
|
|
Codes :
|
|
|
|
```text
|
|
NotFinite
|
|
NotIntegral
|
|
OutOfRange
|
|
Inexact
|
|
```
|
|
|
|
DON'T : introduire mécaniquement :
|
|
|
|
```text
|
|
tryToTarget() -> Result<Target,NumericConversionError>
|
|
```
|
|
|
|
si cette méthode ne ferait que dupliquer `toTarget() faults NumericConversionFault`.
|