mirror of
https://github.com/apple/swift-crypto
synced 2026-11-29 05:14:21 +00:00
Following on from #281, opened as a new PR as the conflicts were too many ### Checklist - [x] I've run tests to see all new and existing tests pass - [x] I've followed the code style of the rest of the project - [x] I've read the [Contribution Guidelines](CONTRIBUTING.md) - [x] I've updated the documentation if necessary #### If you've made changes to `gyb` files - [ ] I've run `.script/generate_boilerplate_files_with_gyb` and included updated generated files in a commit of this pull request ### Motivation: _[Explain here the context, and why you're making that change. What is the problem you're trying to solve.]_ ### Modifications: _[Describe the modifications you've done.]_ ### Result: _[After your change, what will change.]_
51 lines
1.6 KiB
Swift
51 lines
1.6 KiB
Swift
//===----------------------------------------------------------------------===//
|
|
//
|
|
// This source file is part of the SwiftCrypto open source project
|
|
//
|
|
// Copyright (c) 2024 Apple Inc. and the SwiftCrypto project authors
|
|
// Licensed under Apache License v2.0
|
|
//
|
|
// See LICENSE.txt for license information
|
|
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
|
|
//
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
//
|
|
//===----------------------------------------------------------------------===//
|
|
#if canImport(FoundationEssentials)
|
|
#if os(Windows)
|
|
import ucrt
|
|
#elseif canImport(Darwin)
|
|
import Darwin
|
|
#elseif canImport(Glibc)
|
|
import Glibc
|
|
#elseif canImport(Musl)
|
|
import Musl
|
|
#elseif canImport(Android)
|
|
import Android
|
|
#elseif canImport(WASILibc)
|
|
import WASILibc
|
|
#endif
|
|
import FoundationEssentials
|
|
#else
|
|
import Foundation
|
|
#endif
|
|
|
|
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
func I2OSP(value: Int, outputByteCount: Int) -> Data {
|
|
precondition(outputByteCount > 0, "Cannot I2OSP with no output length.")
|
|
precondition(value >= 0, "I2OSP requires a non-null value.")
|
|
|
|
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
let requiredBytes = Int(ceil(log2(Double(max(value, 1) + 1)) / 8))
|
|
precondition(outputByteCount >= requiredBytes)
|
|
|
|
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
var data = Data(repeating: 0, count: outputByteCount)
|
|
|
|
for i in (outputByteCount - requiredBytes)...(outputByteCount - 1) {
|
|
data[i] = UInt8(truncatingIfNeeded: (value >> (8 * (outputByteCount - 1 - i))))
|
|
}
|
|
|
|
return data
|
|
}
|