Coverage Report

Created: 2026-05-16 06:46

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/swift-protobuf/Sources/SwiftProtobuf/MathUtils.swift
Line
Count
Source
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
#if canImport(FoundationEssentials)
16
import FoundationEssentials
17
#else
18
import Foundation
19
#endif
20
21
/// Remainder in standard modular arithmetic (modulo). This coincides with (%)
22
/// when a > 0.
23
///
24
/// - Parameters:
25
///   - a: The dividend. Can be positive, 0 or negative.
26
///   - b: The divisor. This must be positive, and is an error if 0 or negative.
27
/// - Returns: The unique value r such that 0 <= r < b and b * q + r = a for some q.
28
86.4k
internal func mod<T: SignedInteger>(_ a: T, _ b: T) -> T {
29
86.4k
    assert(b > 0)
30
86.4k
    let r = a % b
31
86.4k
    return r >= 0 ? r : r + b
32
86.4k
}
33
34
/// Quotient in standard modular arithmetic (Euclidean division). This coincides
35
/// with (/) when a > 0.
36
///
37
/// - Parameters:
38
///   - a: The dividend. Can be positive, 0 or negative.
39
///   - b: The divisor. This must be positive, and is an error if 0 or negative.
40
/// - Returns: The unique value q such that for some 0 <= r < b, b * q + r = a.
41
36.0k
internal func div<T: SignedInteger>(_ a: T, _ b: T) -> T {
42
36.0k
    assert(b > 0)
43
36.0k
    return a >= 0 ? a / b : (a + 1) / b - 1
44
36.0k
}