MathUtils.swift 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  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. import Foundation
  15. /// Remainder in standard modular arithmetic (modulo). This coincides with (%)
  16. /// when a > 0.
  17. ///
  18. /// - Parameters:
  19. /// - a: The dividend. Can be positive, 0 or negative.
  20. /// - b: The divisor. This must be positive, and is an error if 0 or negative.
  21. /// - Returns: The unique value r such that 0 <= r < b and b * q + r = a for some q.
  22. internal func mod<T: SignedInteger>(_ a: T, _ b: T) -> T {
  23. assert(b > 0)
  24. let r = a % b
  25. return r >= 0 ? r : r + b
  26. }
  27. /// Quotient in standard modular arithmetic (Euclidean division). This coincides
  28. /// with (/) when a > 0.
  29. ///
  30. /// - Parameters:
  31. /// - a: The dividend. Can be positive, 0 or negative.
  32. /// - b: The divisor. This must be positive, and is an error if 0 or negative.
  33. /// - Returns: The unique value q such that for some 0 <= r < b, b * q + r = a.
  34. internal func div<T: SignedInteger>(_ a: T, _ b: T) -> T {
  35. assert(b > 0)
  36. return a >= 0 ? a / b : (a + 1) / b - 1
  37. }