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
Copy file name to clipboardExpand all lines: Sources/IntegerUtilities/README.md
+27-1Lines changed: 27 additions & 1 deletion
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -4,7 +4,7 @@ _Note: This module is only present on `main`, and has not yet been stabilized an
4
4
5
5
## Utilities defined for `BinaryInteger`
6
6
7
-
The following API are defined for all integer types conforming to `BinaryInteger`:
7
+
The following API are defined for all integer types:
8
8
9
9
- The `gcd(_:_:)` free function implements the _Greatest Common Divisor_ operation.
10
10
@@ -36,7 +36,33 @@ The following API are defined for signed integer types:
36
36
37
37
- The `rotated(right:)` and `rotated(left:)` methods implement _bitwise rotation_ for signed and unsigned integer types.
38
38
The count parameter may be any `BinaryInteger` type.
39
+
40
+
### [Saturating Arithmetic][saturating]
41
+
42
+
The following saturating operations are defined as methods on `FixedWidthInteger`:
43
+
44
+
-`addingWithSaturation(_:)`
45
+
-`subtractingWithSaturation(_:)`
46
+
-`negatedWithSaturation(_:)`
47
+
-`multipliedWithSaturation(by:)`
48
+
-`shiftedWithSaturation(leftBy:rounding:)`
49
+
50
+
These implement _saturating arithmetic_.
51
+
They are an alternative to the usual `+`, `-`, and `*` operators, which trap if the result cannot be represented in the argument type, and `&+`, `&-`, `&*`, and `<<`, which wrap out-of-range results modulo 2ⁿ for some n.
52
+
Instead these methods clamp the result to the representable range of the type:
53
+
```
54
+
let x: Int8 = 84
55
+
let y: Int8 = 100
56
+
let a = x + y // traps due to overflow
57
+
let b = x &+ y // wraps to -72
58
+
let c = x.addingWithSaturation(y) // saturates to 127
59
+
```
60
+
61
+
If you are using saturating arithmetic, you may also want to perform saturating conversions between integer types; this functionality is provided by the standard library via the [`init(clamping:)` API][clamping].
39
62
40
63
## Types
41
64
42
65
The `RoundingRule` enum is used with shift, division, and round operations to specify how to round their results to a representable value.
0 commit comments