mirror of
https://github.com/apple/swift-asn1
synced 2026-11-22 04:10:39 +00:00
Fixed BMPString encoding (#111)
* Fixed #110 by using UTF-16 to encode the string literal * Added a unit test to test the added functionality Co-authored-by: Bram Kolkman <bramkolkman@thinkerium.com>
This commit is contained in:
1 parent
823291a67d
commit
810496cf12
2 files changed
+44
-1
No files matched your search
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
Reference in new issue
Block a user