/src/swift-protobuf/Sources/SwiftProtobuf/MathUtils.swift
Line | Count | Source (jump to first uncovered line) |
1 | | // Sources/SwiftProtobuf/MathUtils.swift - Generally useful mathematical functions |
2 | | // |
3 | | // Copyright (c) 2014 - 2017 Apple Inc. and the project authors |
4 | | // Licensed under Apache License v2.0 with Runtime Library Exception |
5 | | // |
6 | | // See LICENSE.txt for license information: |
7 | | // https://github.com/apple/swift-protobuf/blob/main/LICENSE.txt |
8 | | // |
9 | | // ----------------------------------------------------------------------------- |
10 | | /// |
11 | | /// Generally useful mathematical and arithmetic functions. |
12 | | /// |
13 | | // ----------------------------------------------------------------------------- |
14 | | |
15 | | import Foundation |
16 | | |
17 | | /// Remainder in standard modular arithmetic (modulo). This coincides with (%) |
18 | | /// when a > 0. |
19 | | /// |
20 | | /// - Parameters: |
21 | | /// - a: The dividend. Can be positive, 0 or negative. |
22 | | /// - b: The divisor. This must be positive, and is an error if 0 or negative. |
23 | | /// - Returns: The unique value r such that 0 <= r < b and b * q + r = a for some q. |
24 | 62.5k | internal func mod<T: SignedInteger>(_ a: T, _ b: T) -> T { |
25 | 62.5k | assert(b > 0) |
26 | 62.5k | let r = a % b |
27 | 62.5k | return r >= 0 ? r : r + b |
28 | 62.5k | } |
29 | | |
30 | | /// Quotient in standard modular arithmetic (Euclidean division). This coincides |
31 | | /// with (/) when a > 0. |
32 | | /// |
33 | | /// - Parameters: |
34 | | /// - a: The dividend. Can be positive, 0 or negative. |
35 | | /// - b: The divisor. This must be positive, and is an error if 0 or negative. |
36 | | /// - Returns: The unique value q such that for some 0 <= r < b, b * q + r = a. |
37 | 104k | internal func div<T: SignedInteger>(_ a: T, _ b: T) -> T { |
38 | 104k | assert(b > 0) |
39 | 104k | return a >= 0 ? a / b : (a + 1) / b - 1 |
40 | 104k | } |