Use more efficient serialization and deserialization for ARC types (#336)

### Motivation

The use of `Data.subdata(in:)` results in needless copies when decoding
fields from bytes. Additionally, the use of a long chain of
`Data.append(_:)` without a call to `Data.init(capacity:)` or
`Data.reserveCapacity(_:)` can result in needless reallocations.

### Modifications

- Remove unused `EncodeInt` and `DecodeInt` functions. They were unused
before this PR but are there from when ARC credential serialization
included the presentation limit. `DecodeInt` also happened to be
incorrect and would crash when called with a slice.
- Add some useful utility methods for popping bytes from a view without
copying.
- Add some generic functions for encoding and decoding
`FixedWidthInteger` types along with tests for concrete types over
`Data` and slices.
- In ARC decoding, replace the use of `Data.subdata(in:)` with code that
uses the `Data.Subsequence` slice (which happens to be `Data` since the
type is self-slicing).
- In ARC encoding, reserve enough capacity in the resulting `Data` when
the sizes are known to reduce allocations.

## Results

More performant serialization and deserialization for ARC types.
This commit is contained in:
Si Beaumont authored and GitHub committed 2025-03-12 13:03:42 +00:00
1 parent fca04734d7
commit a8a02ac79a
5 files changed
+336 -125

No files matched your search

+2
View File
@@ -99,6 +99,7 @@ Sources/_CryptoExtras/Util/BoringSSLHelpers.swift
Sources/_CryptoExtras/Util/DigestType.swift
Sources/_CryptoExtras/Util/Error.swift
Sources/_CryptoExtras/Util/I2OSP.swift
Sources/_CryptoExtras/Util/IntegerEncoding.swift
Sources/_CryptoExtras/Util/PEMDocument.swift
Sources/_CryptoExtras/Util/PrettyBytes.swift
Sources/_CryptoExtras/Util/SubjectPublicKeyInfo.swift
@@ -151,6 +152,7 @@ Tests/_CryptoExtrasTests/TestRSABlindSigning.swift
Tests/_CryptoExtrasTests/TestRSABlindSigningAPI.swift
Tests/_CryptoExtrasTests/TestRSAEncryption.swift
Tests/_CryptoExtrasTests/TestRSASigning.swift
Tests/_CryptoExtrasTests/Util/IntegerEncodingTests.swift
Tests/_CryptoExtrasTests/Utils/BytesUtil.swift
Tests/_CryptoExtrasTests/Utils/RFCVector.swift
Tests/_CryptoExtrasTests/Utils/SplitData.swift
+92 -125
View File
@@ -19,50 +19,30 @@ typealias ARCCurve = P384
@available(macOS 10.15, iOS 13.2, tvOS 13.2, watchOS 6.1, *)
typealias ARCH2G = HashToCurveImpl<ARCCurve>
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
internal func DecodeInt(value: Data) -> Int {
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
var result = Int(0)
for i in 0..<value.count {
result = result << 8
result += Int(value[i])
}
return result
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
internal func EncodeInt(value: Int) -> Data {
return I2OSP(value: value, outputByteCount: 4)
}
@available(macOS 10.15, iOS 13.2, tvOS 13.2, watchOS 6.1, *)
extension ARC.CredentialRequest where H2G == ARCH2G {
static let scalarCount = 5
static let pointCount = 2
static let serializedByteCount = pointCount * ARCCurve.compressedx962PointByteCount + scalarCount * ARCCurve.orderByteCount
static let serializedByteCount = 2 * ARCCurve.compressedx962PointByteCount + Self.scalarCount * ARCCurve.orderByteCount
func serialize() -> Data {
let m1Enc = self.m1Enc.compressedRepresentation
let m2Enc = self.m2Enc.compressedRepresentation
let proofData = self.proof.serialize()
return m1Enc + m2Enc + proofData
var result = Data(capacity: Self.serializedByteCount)
result.append(self.m1Enc.compressedRepresentation)
result.append(self.m2Enc.compressedRepresentation)
result.append(self.proof.serialize())
return result
}
static func deserialize<D: DataProtocol>(requestData: D) throws -> ARC.CredentialRequest<ARCH2G> {
guard requestData.count == self.serializedByteCount else {
guard requestData.count == Self.serializedByteCount else {
throw ARC.Errors.incorrectRequestDataSize
}
let requestData = Data(requestData)
var startPointer = 0
let m1Enc = try ARCH2G.G.Element(oprfRepresentation: requestData.subdata(in: startPointer..<startPointer+ARCCurve.compressedx962PointByteCount))
startPointer += ARCCurve.compressedx962PointByteCount
let m2Enc = try ARCH2G.G.Element(oprfRepresentation: requestData.subdata(in: startPointer..<startPointer+ARCCurve.compressedx962PointByteCount))
startPointer += ARCCurve.compressedx962PointByteCount
var bytes = Data(requestData)
let m1Enc = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
let m2Enc = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
let proof = try Proof.deserialize(proofData: bytes, scalarCount: Self.scalarCount)
let proof = try Proof.deserialize(proofData: requestData.subdata(in: startPointer..<startPointer + self.scalarCount * ARCCurve.orderByteCount), scalarCount: self.scalarCount)
return ARC.CredentialRequest(m1Enc: m1Enc, m2Enc: m2Enc, proof: proof)
}
}
@@ -70,43 +50,38 @@ extension ARC.CredentialRequest where H2G == ARCH2G {
@available(macOS 10.15, iOS 13.2, tvOS 13.2, watchOS 6.1, *)
extension ARC.CredentialResponse where H2G == ARCH2G {
static let scalarCount = 8
static let pointCount = 6
static let serializedByteCount = pointCount * ARCCurve.compressedx962PointByteCount + scalarCount * ARCCurve.orderByteCount
static let serializedByteCount = 6 * ARCCurve.compressedx962PointByteCount + Self.scalarCount * ARCCurve.orderByteCount
func serialize() -> Data {
let U = self.U.compressedRepresentation
let encUPrime = self.encUPrime.compressedRepresentation
let X0Aux = self.X0Aux.compressedRepresentation
let X1Aux = self.X1Aux.compressedRepresentation
let X2Aux = self.X2Aux.compressedRepresentation
let HAux = self.HAux.compressedRepresentation
let responsePoints = U + encUPrime + X0Aux + X1Aux + X2Aux + HAux
var result = Data(capacity: Self.serializedByteCount)
let proofData = self.proof.serialize()
return responsePoints + proofData
result.append(self.U.compressedRepresentation)
result.append(self.encUPrime.compressedRepresentation)
result.append(self.X0Aux.compressedRepresentation)
result.append(self.X1Aux.compressedRepresentation)
result.append(self.X2Aux.compressedRepresentation)
result.append(self.HAux.compressedRepresentation)
result.append(self.proof.serialize())
return result
}
static func deserialize<D: DataProtocol>(responseData: D) throws -> ARC.CredentialResponse<ARCH2G> {
guard responseData.count == self.serializedByteCount else {
throw ARC.Errors.incorrectResponseDataSize
}
let responseData = Data(responseData)
var startPointer = 0
let U = try ARCH2G.G.Element(oprfRepresentation: responseData.subdata(in: startPointer..<startPointer+ARCCurve.compressedx962PointByteCount))
startPointer += ARCCurve.compressedx962PointByteCount
let encUPrime = try ARCH2G.G.Element(oprfRepresentation: responseData.subdata(in: startPointer..<startPointer+ARCCurve.compressedx962PointByteCount))
startPointer += ARCCurve.compressedx962PointByteCount
let X0Aux = try ARCH2G.G.Element(oprfRepresentation: responseData.subdata(in: startPointer..<startPointer+ARCCurve.compressedx962PointByteCount))
startPointer += ARCCurve.compressedx962PointByteCount
let X1Aux = try ARCH2G.G.Element(oprfRepresentation: responseData.subdata(in: startPointer..<startPointer+ARCCurve.compressedx962PointByteCount))
startPointer += ARCCurve.compressedx962PointByteCount
let X2Aux = try ARCH2G.G.Element(oprfRepresentation: responseData.subdata(in: startPointer..<startPointer+ARCCurve.compressedx962PointByteCount))
startPointer += ARCCurve.compressedx962PointByteCount
let HAux = try ARCH2G.G.Element(oprfRepresentation: responseData.subdata(in: startPointer..<startPointer+ARCCurve.compressedx962PointByteCount))
startPointer += ARCCurve.compressedx962PointByteCount
var bytes = Data(responseData)
let U = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
let encUPrime = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
let X0Aux = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
let X1Aux = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
let X2Aux = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
let HAux = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
let proof = try Proof.deserialize(proofData: bytes, scalarCount: self.scalarCount)
let proof = try Proof.deserialize(proofData: responseData.subdata(in: startPointer..<startPointer + self.scalarCount * ARCCurve.orderByteCount), scalarCount: self.scalarCount)
return ARC.CredentialResponse(U: U, encUPrime: encUPrime, X0Aux: X0Aux, X1Aux: X1Aux, X2Aux: X2Aux, HAux: HAux, proof: proof)
}
}
@@ -118,65 +93,59 @@ extension ARC.Presentation where H2G == ARCH2G {
static let serializedByteCount = pointCount * ARCCurve.compressedx962PointByteCount + scalarCount * ARCCurve.orderByteCount
func serialize() -> Data {
// Serialize presentation elements
let U = self.U.compressedRepresentation
let UPrimeCommit = self.UPrimeCommit.compressedRepresentation
let m1Commit = self.m1Commit.compressedRepresentation
let tag = self.tag.compressedRepresentation
var result = Data(capacity: Self.serializedByteCount)
let presentationProofData = self.proof.serialize()
return U + UPrimeCommit + m1Commit + tag + presentationProofData
result.append(self.U.compressedRepresentation)
result.append(self.UPrimeCommit.compressedRepresentation)
result.append(self.m1Commit.compressedRepresentation)
result.append(self.tag.compressedRepresentation)
result.append(self.proof.serialize())
return result
}
static func deserialize<D: DataProtocol>(presentationData: D) throws -> ARC.Presentation<ARCH2G> {
guard presentationData.count == self.serializedByteCount else {
throw ARC.Errors.incorrectPresentationDataSize
}
let presentationData = Data(presentationData)
var startPointer = 0
// Deserialize presentation elements
let U = try ARCH2G.G.Element(oprfRepresentation: presentationData.subdata(in: startPointer..<startPointer+ARCCurve.compressedx962PointByteCount))
startPointer += ARCCurve.compressedx962PointByteCount
let UPrimeCommit = try ARCH2G.G.Element(oprfRepresentation: presentationData.subdata(in: startPointer..<startPointer+ARCCurve.compressedx962PointByteCount))
startPointer += ARCCurve.compressedx962PointByteCount
let m1Commit = try ARCH2G.G.Element(oprfRepresentation: presentationData.subdata(in: startPointer..<startPointer+ARCCurve.compressedx962PointByteCount))
startPointer += ARCCurve.compressedx962PointByteCount
let tag = try ARCH2G.G.Element(oprfRepresentation: presentationData.subdata(in: startPointer..<startPointer+ARCCurve.compressedx962PointByteCount))
startPointer += ARCCurve.compressedx962PointByteCount
var bytes = Data(presentationData)
let U = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
let UPrimeCommit = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
let m1Commit = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
let tag = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
let presentationProof = try Proof.deserialize(proofData: bytes, scalarCount: Self.scalarCount)
let presentationProof = try Proof.deserialize(proofData: presentationData.subdata(in: startPointer..<startPointer + self.scalarCount * ARCCurve.orderByteCount), scalarCount: self.scalarCount)
return ARC.Presentation(U: U, UPrimeCommit: UPrimeCommit, m1Commit: m1Commit, tag: tag, proof: presentationProof)
}
}
@available(macOS 10.15, iOS 13.2, tvOS 13.2, watchOS 6.1, *)
extension ARC.ServerPublicKey where H2G == ARCH2G {
static let pointCount = 3
static let serializedByteCount = 3 * ARCCurve.compressedx962PointByteCount
static let pointCount = 3 // TODO: delete
func serialize() -> Data {
// Serialize server commitment elements
let X0 = self.X0.compressedRepresentation
let X1 = self.X1.compressedRepresentation
let X2 = self.X2.compressedRepresentation
var result = Data(capacity: Self.serializedByteCount)
return X0 + X1 + X2
result.append(self.X0.compressedRepresentation)
result.append(self.X1.compressedRepresentation)
result.append(self.X2.compressedRepresentation)
return result
}
static func deserialize<D: DataProtocol>(serverPublicKeyData: D) throws -> ARC.ServerPublicKey<ARCH2G> {
guard serverPublicKeyData.count == self.pointCount * ARCCurve.compressedx962PointByteCount else {
throw ARC.Errors.incorrectServerCommitmentsSize
}
let serverPublicKeyData = Data(serverPublicKeyData)
var startPointer = 0
// Deserialize server commitment elements
let X0 = try ARCH2G.G.Element(oprfRepresentation: serverPublicKeyData.subdata(in: startPointer..<startPointer+ARCCurve.compressedx962PointByteCount))
startPointer += ARCCurve.compressedx962PointByteCount
let X1 = try ARCH2G.G.Element(oprfRepresentation: serverPublicKeyData.subdata(in: startPointer..<startPointer+ARCCurve.compressedx962PointByteCount))
startPointer += ARCCurve.compressedx962PointByteCount
let X2 = try ARCH2G.G.Element(oprfRepresentation: serverPublicKeyData.subdata(in: startPointer..<startPointer+ARCCurve.compressedx962PointByteCount))
startPointer += ARCCurve.compressedx962PointByteCount
var bytes = Data(serverPublicKeyData)
let X0 = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
let X1 = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
let X2 = try H2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
return ARC.ServerPublicKey(X0: X0, X1: X1, X2: X2)
}
@@ -201,19 +170,18 @@ extension Proof where H2G == ARCH2G {
guard proofData.count == scalarCount * ARCCurve.orderByteCount else {
throw ARC.Errors.incorrectProofDataSize
}
let proofData = Data(proofData)
var startPointer = 0
var bytes = Data(proofData)
// Deserialize challenge
let challenge = try GroupImpl<ARCCurve>.Scalar(bytes: proofData.subdata(in: startPointer..<startPointer+ARCCurve.orderByteCount))
startPointer += ARCCurve.orderByteCount
let challenge = try ARCH2G.G.Scalar(bytes: bytes.popFirst(ARCCurve.orderByteCount))
// Deserialize responses
var responses: [GroupImpl<ARCCurve>.Scalar] = []
responses.reserveCapacity(scalarCount - 1)
for _ in (0..<scalarCount-1) {
let response = try GroupImpl<ARCCurve>.Scalar(bytes: proofData.subdata(in: startPointer..<startPointer+ARCCurve.orderByteCount))
let response = try ARCH2G.G.Scalar(bytes: bytes.popFirst(ARCCurve.orderByteCount))
responses.append(response)
startPointer += ARCCurve.orderByteCount
}
return Proof(challenge: challenge, responses: responses)
@@ -227,42 +195,41 @@ extension ARC.Credential where H2G == ARCH2G {
static let scalarCount = 1
static let pointCount = 5
func serialize() throws -> Data {
let m1 = self.m1.rawRepresentation
let U = self.U.compressedRepresentation
let UPrime = self.UPrime.compressedRepresentation
let X1 = self.X1.compressedRepresentation
let genG = self.generatorG.compressedRepresentation
let genH = self.generatorH.compressedRepresentation
let presentationState = try self.presentationState.serialize()
static let serializedByteCountExcludingPresentationState = 1 * ARCCurve.orderByteCount + 5 * ARCCurve.compressedx962PointByteCount
return m1 + U + UPrime + X1 + genG + genH + presentationState
func serialize() throws -> Data {
let presentationStateBytes = try self.presentationState.serialize()
var result = Data(capacity: Self.serializedByteCountExcludingPresentationState + presentationStateBytes.count)
result.append(self.m1.rawRepresentation)
result.append(self.U.compressedRepresentation)
result.append(self.UPrime.compressedRepresentation)
result.append(self.X1.compressedRepresentation)
result.append(self.generatorG.compressedRepresentation)
result.append(self.generatorH.compressedRepresentation)
result.append(presentationStateBytes)
return result
}
static func deserialize<D: DataProtocol>(credentialData: D) throws -> ARC.Credential<ARCH2G> {
let stateByteCount = credentialData.count - self.scalarCount * ARCCurve.orderByteCount - self.pointCount * ARCCurve.compressedx962PointByteCount
guard stateByteCount >= 0 else {
guard credentialData.count - Self.serializedByteCountExcludingPresentationState >= 0 else {
throw ARC.Errors.incorrectCredentialDataSize
}
let credentialData = Data(credentialData)
var startPointer = 0
let m1 = try GroupImpl<ARCCurve>.Scalar(bytes: credentialData.subdata(in: startPointer..<startPointer+ARCCurve.orderByteCount))
startPointer += ARCCurve.orderByteCount
let U = try ARCH2G.G.Element(oprfRepresentation: credentialData.subdata(in: startPointer..<startPointer+ARCCurve.compressedx962PointByteCount))
startPointer += ARCCurve.compressedx962PointByteCount
let UPrime = try ARCH2G.G.Element(oprfRepresentation: credentialData.subdata(in: startPointer..<startPointer+ARCCurve.compressedx962PointByteCount))
startPointer += ARCCurve.compressedx962PointByteCount
let X1 = try ARCH2G.G.Element(oprfRepresentation: credentialData.subdata(in: startPointer..<startPointer+ARCCurve.compressedx962PointByteCount))
startPointer += ARCCurve.compressedx962PointByteCount
let genG = try ARCH2G.G.Element(oprfRepresentation: credentialData.subdata(in: startPointer..<startPointer+ARCCurve.compressedx962PointByteCount))
startPointer += ARCCurve.compressedx962PointByteCount
let genH = try ARCH2G.G.Element(oprfRepresentation: credentialData.subdata(in: startPointer..<startPointer+ARCCurve.compressedx962PointByteCount))
startPointer += ARCCurve.compressedx962PointByteCount
var bytes = Data(credentialData)
// Deserialize presentationState
let presentationStateData = credentialData.subdata(in: startPointer..<startPointer+stateByteCount)
let presentationState = try ARC.PresentationState.deserialize(presentationStateData: presentationStateData)
let m1 = try ARCH2G.G.Scalar(bytes: bytes.popFirst(ARCCurve.orderByteCount))
let U = try ARCH2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
let UPrime = try ARCH2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
let X1 = try ARCH2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
let genG = try ARCH2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
let genH = try ARCH2G.G.Element(oprfRepresentation: bytes.popFirst(ARCCurve.compressedx962PointByteCount))
// Deserialize presentationState from remaining bytes.
let presentationState = try ARC.PresentationState.deserialize(presentationStateData: bytes)
let ciphersuite = ARC.Ciphersuite(ARCH2G.self)
return ARC.Credential(m1: m1, U: U, UPrime: UPrime, X1: X1, ciphersuite: ciphersuite, generatorG: genG, generatorH: genH, presentationState: presentationState)
+1
View File
@@ -56,6 +56,7 @@ add_library(_CryptoExtras
"Util/DigestType.swift"
"Util/Error.swift"
"Util/I2OSP.swift"
"Util/IntegerEncoding.swift"
"Util/PEMDocument.swift"
"Util/PrettyBytes.swift"
"Util/SubjectPublicKeyInfo.swift"
@@ -0,0 +1,88 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
import Foundation
enum IntegerDecodingError: Error, Equatable {
case incorrectNumberOfBytes(expected: Int, actual: Int)
}
extension FixedWidthInteger {
/// Create an new value from a collection of its big endian bytes.
///
/// - Parameter bytes: Big endian bytes.
///
/// - Throws: A decoding error if the collection did not contain the exact number of bytes.
init(bigEndianBytes bytes: some Collection<UInt8>) throws {
guard bytes.count == Self.bitWidth / 8 else {
throw IntegerDecodingError.incorrectNumberOfBytes(expected: Self.bitWidth / 8, actual: bytes.count)
}
self = 0
var index = bytes.startIndex
for _ in 0..<(Self.bitWidth / 8) {
self <<= 8
self |= Self(bytes[index])
bytes.formIndex(after: &index)
}
}
fileprivate init(bigEndianContiguousBytes bytes: some ContiguousBytes) throws {
self = try bytes.withUnsafeBytes { try Self(bigEndianBytes: $0 ) }
}
/// Create an new value from its big endian bytes representation.
///
/// - Parameter bytes: Big endian bytes.
///
/// - Throws: A decoding error if the collection did not contain the exact number of bytes.
init(bigEndianBytes bytes: Data) throws {
self = try Self(bigEndianContiguousBytes: bytes)
}
/// The big endian bytes that represent this value.
var bigEndianBytes: Data { Data(bigEndianBytesOf: self) }
}
extension Data {
/// Creates a new instance initialized with the big endian bytes representation of the given integer.
init(bigEndianBytesOf integer: some FixedWidthInteger) {
self.init()
self.append(bigEndianBytesOf: integer)
}
/// Appends the big endian bytes of the given integer.
mutating func append<T: FixedWidthInteger>(bigEndianBytesOf integer: T) {
let previousCount = self.count
let newCount = previousCount + T.bitWidth / 8
self.reserveCapacity(newCount)
self.count = newCount
self.withUnsafeMutableBytes {
$0.storeBytes(of: integer.bigEndian, toByteOffset: previousCount, as: T.self)
}
}
/// Removes and returns the first k bytes.
mutating func popFirst(_ k: Int) -> Self {
let prefix = self.prefix(k)
self.removeFirst(k)
return prefix
}
/// Removes and returns the first k bytes, decoded as a value of the given type from its big endian bytes.
mutating func popFirst<T: FixedWidthInteger>(bigEndian: T.Type) throws -> T {
let value = try T(bigEndianBytes: self.prefix(T.bitWidth / 8))
self.removeFirst(T.bitWidth / 8)
return value
}
}
@@ -0,0 +1,153 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
@testable import _CryptoExtras
import XCTest
final class IntegerEncodingTests: XCTestCase {
func testIntegerDecoding() throws {
func test<T: FixedWidthInteger>(
decoding bytes: [UInt8],
as: T.Type,
expect expectedResult: Swift.Result<T, IntegerDecodingError>,
file: StaticString = #filePath, line: UInt = #line
) {
let actualResult = Swift.Result { try T(bigEndianBytes: bytes) }
switch (actualResult, expectedResult) {
case (.success(let actual), .success(let expected)):
XCTAssertEqual(actual, expected, file: file, line: line)
case (.success(let actual), .failure(let error)):
XCTFail("Expected error: \(error), got \(actual)", file: file, line: line)
case (.failure(let error), .success(let expected)):
XCTFail("Decode failed; expected: \(expected), got error: \(error)", file: file, line: line)
case (.failure(let actualError), .failure(let expectedError)):
guard let typedError = actualError as? IntegerDecodingError else {
XCTFail("Expected error but not this one: \(actualError)", file: file, line: line)
return
}
XCTAssertEqual(typedError, expectedError, file: file, line: line)
}
}
test(decoding: [0,0], as: UInt16.self, expect: .success(0))
test(decoding: [0,1], as: UInt16.self, expect: .success(1))
test(decoding: [1,0], as: UInt16.self, expect: .success(256))
test(decoding: [1,1], as: UInt16.self, expect: .success(257))
test(decoding: [0xff,0xff], as: UInt16.self, expect: .success(UInt16.max))
test(decoding: [], as: UInt16.self, expect: .failure(.incorrectNumberOfBytes(expected: 2, actual: 0)))
test(decoding: [0], as: UInt16.self, expect: .failure(.incorrectNumberOfBytes(expected: 2, actual: 1)))
test(decoding: [0,0,0], as: UInt16.self, expect: .failure(.incorrectNumberOfBytes(expected: 2, actual: 3)))
test(decoding: [0,0,0,0], as: UInt16.self, expect: .failure(.incorrectNumberOfBytes(expected: 2, actual: 4)))
test(decoding: [0,0], as: Int16.self, expect: .success(0))
test(decoding: [0,1], as: Int16.self, expect: .success(1))
test(decoding: [1,0], as: Int16.self, expect: .success(256))
test(decoding: [1,1], as: Int16.self, expect: .success(257))
test(decoding: [0xff,0xff], as: Int16.self, expect: .success(-1))
test(decoding: [0x80,0x00], as: Int16.self, expect: .success(Int16.min))
test(decoding: [0x7f,0xff], as: Int16.self, expect: .success(Int16.max))
test(decoding: [], as: Int16.self, expect: .failure(.incorrectNumberOfBytes(expected: 2, actual: 0)))
test(decoding: [0], as: Int16.self, expect: .failure(.incorrectNumberOfBytes(expected: 2, actual: 1)))
test(decoding: [0,0,0], as: Int16.self, expect: .failure(.incorrectNumberOfBytes(expected: 2, actual: 3)))
test(decoding: [0,0,0,0], as: Int16.self, expect: .failure(.incorrectNumberOfBytes(expected: 2, actual: 4)))
}
func testIntegerEncoding() throws {
func test<T: FixedWidthInteger>(encoding value: T, expect bytes: [UInt8], file: StaticString = #filePath, line: UInt = #line) {
XCTAssertEqual(value.bigEndianBytes, Data(bytes), file: file, line: line)
}
test(encoding: UInt16.zero, expect: [0,0])
test(encoding: UInt16(1), expect: [0,1])
test(encoding: UInt16(256), expect: [1,0])
test(encoding: UInt16(257), expect: [1,1])
test(encoding: UInt16.max, expect: [0xff,0xff])
test(encoding: Int16.zero, expect: [0,0])
test(encoding: Int16(1), expect: [0,1])
test(encoding: Int16(256), expect: [1,0])
test(encoding: Int16(257), expect: [1,1])
test(encoding: Int16(-1), expect: [0xff,0xff])
test(encoding: Int16.min, expect: [0x80,0x00])
test(encoding: Int16.max, expect: [0x7f,0xff])
}
func testIntegerEncodingDataAppend() throws {
var bytes = Data()
bytes.append(bigEndianBytesOf: Int32(1))
bytes.append(bigEndianBytesOf: Int16(2))
bytes.append(bigEndianBytesOf: Int8(3))
bytes.append(bigEndianBytesOf: Int64(4))
XCTAssertEqual(bytes.hexString, Data([0,0,0,1] + [0,2] + [3] + [0,0,0,0,0,0,0,4]).hexString)
}
func testIntegerDecodingFromDataSubsequence() throws {
let data = Data([0,0,0,1] + [0,2] + [3] + [0,0,0,0,0,0,0,4])
var bytes = data[...]
XCTAssertEqual(bytes.count, 15)
XCTAssertEqual(try Int32(bigEndianBytes: bytes[..<bytes.startIndex.advanced(by: 4)]), 1)
bytes.removeFirst(4)
XCTAssertEqual(try Int16(bigEndianBytes: bytes[..<bytes.startIndex.advanced(by: 2)]), 2)
bytes.removeFirst(2)
XCTAssertEqual(try Int8(bigEndianBytes: bytes[..<bytes.startIndex.advanced(by: 1)]), 3)
bytes.removeFirst(1)
XCTAssertEqual(try Int64(bigEndianBytes: bytes[..<bytes.startIndex.advanced(by: 8)]), 4)
bytes.removeFirst(8)
XCTAssert(bytes.isEmpty)
}
func testIntegerDecodingUsingDataPopFirstK() throws {
var bytes = Data([0,0,0,1] + [0,2] + [3] + [0,0,0,0,0,0,0,4])
XCTAssertEqual(bytes.count, 15)
XCTAssertEqual(try Int32(bigEndianBytes: bytes.popFirst(4)), 1)
XCTAssertEqual(try Int16(bigEndianBytes: bytes.popFirst(2)), 2)
XCTAssertEqual(try Int8(bigEndianBytes: bytes.popFirst(1)), 3)
XCTAssertEqual(try Int64(bigEndianBytes: bytes.popFirst(8)), 4)
XCTAssert(bytes.isEmpty)
}
func testIntegerDecodingUsingDataPopFirst() throws {
var bytes = Data([0,0,0,1] + [0,2] + [3] + [0,0,0,0,0,0,0,4])
XCTAssertEqual(bytes.count, 15)
XCTAssertEqual(try bytes.popFirst(bigEndian: Int32.self), 1)
XCTAssertEqual(try bytes.popFirst(bigEndian: Int16.self), 2)
XCTAssertEqual(try bytes.popFirst(bigEndian: Int8.self), 3)
XCTAssertEqual(try bytes.popFirst(bigEndian: Int64.self), 4)
XCTAssert(bytes.isEmpty)
}
func testIntegerDecodingUsingDataPopFirstTooFewBytes() throws {
var bytes = Data([0])
XCTAssertThrowsError(try bytes.popFirst(bigEndian: Int16.self))
XCTAssertThrowsError(try bytes.popFirst(bigEndian: Int32.self))
XCTAssertThrowsError(try bytes.popFirst(bigEndian: Int64.self))
}
}