Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion Sources/SwiftASN1/Basic ASN1 Types/ASN1Strings.swift
Original file line number Diff line number Diff line change
Expand Up @@ -284,7 +284,19 @@ public struct ASN1BMPString: DERImplicitlyTaggable, BERImplicitlyTaggable, Hasha

@inlinable
public init(stringLiteral value: StringLiteralType) {
self.bytes = ArraySlice(value.utf8)
guard
value.utf16.allSatisfy({ codeUnit in
!(0xD800...0xDFFF).contains(codeUnit)
})
else {
fatalError("BMPString cannot contain characters outside the Basic Multilingual Plane: '\(value)'")
}

self.bytes = ArraySlice(
value.utf16.flatMap { codeUnit in
[UInt8(truncatingIfNeeded: codeUnit >> 8), UInt8(truncatingIfNeeded: codeUnit)]
}
)
}

@inlinable
Expand Down
31 changes: 31 additions & 0 deletions Tests/SwiftASN1Tests/ASN1StringTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,37 @@ final class ASN1StringTests: XCTestCase {
string.withUnsafeBytes { XCTAssertTrue($0.elementsEqual([1, 2, 3, 4])) }
}

func testBMPStringStringLiteral() throws {
typealias TestCase = (literal: String, utf16: [UInt8], asn1: [UInt8])

let testCases: [TestCase] = [
TestCase(
"Test",
[0, 84, 0, 101, 0, 115, 0, 116],
[30, 8, 0, 84, 0, 101, 0, 115, 0, 116]
),
TestCase(
"Tests",
[0, 84, 0, 101, 0, 115, 0, 116, 0, 115],
[30, 10, 0, 84, 0, 101, 0, 115, 0, 116, 0, 115]
),
TestCase(
"中文",
[78, 45, 101, 135],
[30, 4, 78, 45, 101, 135]
),
]

try testCases.forEach { testCase in
let string = ASN1BMPString(stringLiteral: testCase.literal)
XCTAssertEqual(Array(string.bytes), testCase.utf16)

var serializer = DER.Serializer()
try serializer.serialize(string)
XCTAssertEqual(serializer.serializedBytes, testCase.asn1)
}
}

func testUTF8StringCanCreateAString() throws {
let string = "hello, world!"
let utf8String = ASN1UTF8String(string)
Expand Down
Loading