Skip to content

Commit 4ff26ad

Browse files
authored
Support converting RDNAttribute values into Strings (#154)
Motivation RDNAttribute Values are mostly strings, and it's useful to be able to convert them. This patch adds that support. Modifications Add support for converting RDN attribute values into Strings. Result Easier to work with distinguished names.
1 parent 0369bc0 commit 4ff26ad

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

Sources/X509/RDNAttribute.swift

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -584,6 +584,22 @@ extension ASN1ObjectIdentifier {
584584
}
585585
}
586586

587+
extension String {
588+
/// Extract the textual representation of a given ``RelativeDistinguishedName/Attribute/Value-swift.struct``.
589+
///
590+
/// Returns `nil` if the value is not a printable or UTF8 string.
591+
public init?(_ value: RelativeDistinguishedName.Attribute.Value) {
592+
switch value.storage {
593+
case .printable(let printable):
594+
self = printable
595+
case .utf8(let utf8):
596+
self = utf8
597+
default:
598+
return nil
599+
}
600+
}
601+
}
602+
587603
extension RandomAccessCollection {
588604
@inlinable
589605
func suffix(while predicate: (Element) -> Bool) -> SubSequence {

Tests/X509Tests/DistinguishedNameTests.swift

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -415,4 +415,16 @@ final class DistinguishedNameTests: XCTestCase {
415415
RelativeDistinguishedName.Attribute.Value(utf8String: String(repeating: "A", count: Int(UInt16.max) + 1))
416416
)
417417
}
418+
419+
func testRDNAttributeValuesCanBeConvertedToStrings() throws {
420+
let examplesAndResults: [(RelativeDistinguishedName.Attribute, String?)] = try [
421+
(.init(type: .RDNAttributeType.commonName, printableString: "foo"), "foo"),
422+
(.init(type: .RDNAttributeType.commonName, utf8String: "bar"), "bar"),
423+
(.init(type: .RDNAttributeType.commonName, value: ASN1Any(erasing: ASN1IA5String("foo"))), nil),
424+
]
425+
426+
for (example, result) in examplesAndResults {
427+
XCTAssertEqual(String(example.value), result)
428+
}
429+
}
418430
}

0 commit comments

Comments
 (0)