Skip to content

Commit

Permalink
Ensure all Readers & Writers have package access
Browse files Browse the repository at this point in the history
  • Loading branch information
kdubb committed Feb 11, 2023
1 parent f28fb20 commit 0047ef5
Show file tree
Hide file tree
Showing 18 changed files with 280 additions and 310 deletions.
37 changes: 10 additions & 27 deletions Sources/PotentASN1/ASN1DERReader.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,24 +15,7 @@ import PotentCodables

/// Read ASN.1/DER encoded data.
///
public enum ASN1DERReader {

public enum Error: Swift.Error {
/// Unexpectedly encounted end of data.
case unexpectedEOF
/// Invalid or unsupported string.
case invalidStringEncoding
/// Invalid characters for string.
case invalidStringCharacters
/// Unsupported non-constructed collection
case nonConstructedCollection
/// Incorrectly formatted UTC time.
case invalidUTCTime
/// Incorrectly formatted generalized time.
case invalidGeneralizedTime
/// Unsupported REAL type.
case unsupportedReal
}
internal enum ASN1DERReader {

/// Parse data into a collection of ``ASN1`` values.
///
Expand Down Expand Up @@ -194,7 +177,7 @@ public enum ASN1DERReader {
return .bmpString(try parseString(&itemBuffer, encoding: .ascii))

case .sequence, .set:
throw Error.nonConstructedCollection
throw ASN1Serialization.Error.nonConstructedCollection

case .objectDescriptor, .external, .enumerated, .embedded, .relativeOID:
// Default to saving tagged version
Expand All @@ -209,11 +192,11 @@ public enum ASN1DERReader {
) throws -> ZonedDate {

guard let string = String(data: Data(try buffer.popAll()), encoding: .ascii) else {
throw Error.invalidStringEncoding
throw ASN1Serialization.Error.invalidStringEncoding
}

guard let zonedDate = formatter.date(from: string) else {
throw Error.invalidUTCTime
throw ASN1Serialization.Error.invalidUTCTime
}

return zonedDate
Expand All @@ -237,7 +220,7 @@ public enum ASN1DERReader {
return Decimal(string: String(bytes: bytes, encoding: .ascii) ?? "") ?? .zero
}
else {
throw Error.unsupportedReal
throw ASN1Serialization.Error.unsupportedReal
}
}

Expand All @@ -248,11 +231,11 @@ public enum ASN1DERReader {
) throws -> String {

guard let string = String(data: Data(try buffer.popAll()), encoding: encoding) else {
throw Error.invalidStringEncoding
throw ASN1Serialization.Error.invalidStringEncoding
}

if let characterSet = characterSet, !string.unicodeScalars.allSatisfy({ characterSet.contains($0) }) {
throw Error.invalidStringCharacters
throw ASN1Serialization.Error.invalidStringCharacters
}

return string
Expand Down Expand Up @@ -333,7 +316,7 @@ private extension UnsafeBufferPointer {

mutating func popAll() throws -> UnsafeRawBufferPointer {
guard let baseAddress = baseAddress else {
throw ASN1DERReader.Error.unexpectedEOF
throw ASN1Serialization.Error.unexpectedEOF
}
let buffer = UnsafeRawBufferPointer(start: baseAddress, count: count)
self = UnsafeBufferPointer(start: baseAddress.advanced(by: count), count: 0)
Expand All @@ -342,7 +325,7 @@ private extension UnsafeBufferPointer {

mutating func pop(count: Int = 0) throws -> UnsafeBufferPointer {
guard let baseAddress = baseAddress, self.count >= count else {
throw ASN1DERReader.Error.unexpectedEOF
throw ASN1Serialization.Error.unexpectedEOF
}
let buffer = UnsafeBufferPointer(start: baseAddress, count: count)
self = UnsafeBufferPointer(start: baseAddress.advanced(by: count), count: self.count - count)
Expand All @@ -351,7 +334,7 @@ private extension UnsafeBufferPointer {

mutating func pop() throws -> Element {
guard let baseAddress = baseAddress, self.count >= 1 else {
throw ASN1DERReader.Error.unexpectedEOF
throw ASN1Serialization.Error.unexpectedEOF
}
defer {
self = UnsafeBufferPointer(start: baseAddress.advanced(by: 1), count: self.count - 1)
Expand Down
32 changes: 12 additions & 20 deletions Sources/PotentASN1/ASN1DERWriter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,21 +14,13 @@ import Foundation

/// Write ASN.1/DER encoded data.
///
public class ASN1DERWriter {

/// ASN.1 Writing Errors
public enum Error: Swift.Error {
/// Encoded value length could not be stored.
case lengthOverflow
case invalidObjectIdentifierLength
case invalidStringCharacters
}
internal class ASN1DERWriter {

/// Write a collection of ``ASN1`` values in ASN.1/DER format.
///
/// - Parameter values: Values to write.
/// - Throws: `Error` when unable to write data.
public static func write(_ values: [ASN1]) throws -> Data {
static func write(_ values: [ASN1]) throws -> Data {
let writer = ASN1DERWriter()
for value in values {
try writer.write(value)
Expand All @@ -40,15 +32,15 @@ public class ASN1DERWriter {
///
/// - Parameter value: Value to write.
/// - Throws: `Error` when unable to write data.
public static func write(_ value: ASN1) throws -> Data {
static func write(_ value: ASN1) throws -> Data {
let writer = ASN1DERWriter()
try writer.write(value)
return writer.data
}

public private(set) var data: Data
internal private(set) var data: Data

public required init() {
required init() {
data = Data(capacity: 256)
}

Expand Down Expand Up @@ -81,29 +73,29 @@ public class ASN1DERWriter {
private func append(length: BigUInt) throws {
let bytes = length.derEncoded()
guard let byteCount = Int8(exactly: bytes.count) else {
throw Error.lengthOverflow
throw ASN1Serialization.Error.lengthOverflow
}
append(byte: 0x80 | UInt8(byteCount))
append(data: bytes)
}

public func append(data: Data) {
private func append(data: Data) {
self.data.append(data)
}

public func append(tag: UInt8, length: Int) throws {
func append(tag: UInt8, length: Int) throws {
append(byte: tag)
try append(length: length)
}

public func append(tag: ASN1.Tag, length: Int) throws {
private func append(tag: ASN1.Tag, length: Int) throws {
append(byte: tag.rawValue)
try append(length: length)
}

private static let zero = Data(repeating: 0, count: 1)

public func write(_ value: ASN1) throws {
private func write(_ value: ASN1) throws {
switch value {
case .boolean(let value):
try append(tag: .boolean, length: 1)
Expand Down Expand Up @@ -249,7 +241,7 @@ public class ASN1DERWriter {
var iter = fields.makeIterator()

guard let first = iter.next(), let second = iter.next() else {
throw Error.invalidObjectIdentifierLength
throw ASN1Serialization.Error.invalidObjectIdentifierLength
}

var bytes = field(val: first * 40 + second)
Expand Down Expand Up @@ -283,7 +275,7 @@ public class ASN1DERWriter {

private func data(forString string: String, encoding: String.Encoding) throws -> Data {
guard let data = string.data(using: encoding) else {
throw Error.invalidStringCharacters
throw ASN1Serialization.Error.invalidStringCharacters
}
return data
}
Expand Down
22 changes: 22 additions & 0 deletions Sources/PotentASN1/ASN1Serialization.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,28 @@ import Foundation
///
public enum ASN1Serialization {

/// ASN.1 Data Errors
public enum Error: Swift.Error {
/// Unexpectedly encounted end of data.
case unexpectedEOF
/// Invalid or unsupported string.
case invalidStringEncoding
/// Invalid characters for string.
case invalidStringCharacters
/// Unsupported non-constructed collection
case nonConstructedCollection
/// Incorrectly formatted UTC time.
case invalidUTCTime
/// Incorrectly formatted generalized time.
case invalidGeneralizedTime
/// Unsupported REAL type.
case unsupportedReal
/// Encoded value length could not be stored.
case lengthOverflow
/// Number of fields in OID is invalid
case invalidObjectIdentifierLength
}

/// Read ASN.1/DER encoded data as a collection of ``ASN1`` values.
public static func asn1(fromDER data: Data) throws -> [ASN1] {
return try ASN1DERReader.parse(data: data)
Expand Down
2 changes: 1 addition & 1 deletion Sources/PotentCBOR/CBOREncoder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -254,7 +254,7 @@ public struct CBOREncoderTransform: InternalEncoderTransform, InternalValueSeria
}

public static func data(from value: CBOR, options: Options) throws -> Data {
return try CBORSerialization.data(with: value)
return try CBORSerialization.data(from: value)
}

}
Expand Down
32 changes: 16 additions & 16 deletions Sources/PotentCBOR/CBORReader.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,13 @@
import Foundation


private typealias CBORError = CBORSerialization.Error
internal struct CBORReader {

public struct CBORReader {
typealias Error = CBORSerialization.Error

private let stream: CBORInputStream

public init(stream: CBORInputStream) {
init(stream: CBORInputStream) {
self.stream = stream
}

Expand Down Expand Up @@ -48,7 +48,7 @@ public struct CBORReader {
let length = try readVarUInt(initByte, base: base)

guard length <= Int.max else {
throw CBORError.sequenceTooLong
throw Error.sequenceTooLong
}

return Int(length)
Expand All @@ -62,7 +62,7 @@ public struct CBORReader {
/// including `.invalidBreak` if a break indicator is encountered in
/// an item slot
/// - `Swift.Error`: If any I/O error occurs
public func decodeItems(count: Int) throws -> CBOR.Array {
private func decodeItems(count: Int) throws -> CBOR.Array {
var result: CBOR.Array = []
for _ in 0 ..< count {
let item = try decodeRequiredItem()
Expand All @@ -78,7 +78,7 @@ public struct CBORReader {
/// - Throws:
/// - `CBORSerialization.Error`: If corrupted data is encountered
/// - `Swift.Error`: If any I/O error occurs
public func decodeItemsUntilBreak() throws -> CBOR.Array {
private func decodeItemsUntilBreak() throws -> CBOR.Array {
var result: CBOR.Array = []
while let item = try decodeItem() {
result.append(item)
Expand All @@ -94,7 +94,7 @@ public struct CBORReader {
/// including `.invalidBreak` if a break indicator is encountered in
/// the either the key or value slot
/// - `Swift.Error`: If any I/O error occurs
public func decodeItemPairs(count: Int) throws -> CBOR.Map {
private func decodeItemPairs(count: Int) throws -> CBOR.Map {
var result: CBOR.Map = [:]
for _ in 0 ..< count {
let key = try decodeRequiredItem()
Expand All @@ -113,7 +113,7 @@ public struct CBORReader {
/// including `.invalidBreak` if a break indicator is encountered in
/// the value slot
/// - `Swift.Error`: If any I/O error occurs
public func decodeItemPairsUntilBreak() throws -> CBOR.Map {
private func decodeItemPairsUntilBreak() throws -> CBOR.Map {
var result: CBOR.Map = [:]
while let key = try decodeItem() {
let val = try decodeRequiredItem()
Expand All @@ -130,8 +130,8 @@ public struct CBORReader {
/// including `.invalidBreak` if an indefinite-element indicator is
/// encountered
/// - `Swift.Error`: If any I/O error occurs
public func decodeRequiredItem() throws -> CBOR {
guard let item = try decodeItem() else { throw CBORError.invalidBreak }
func decodeRequiredItem() throws -> CBOR {
guard let item = try decodeItem() else { throw Error.invalidBreak }
return item
}

Expand All @@ -141,7 +141,7 @@ public struct CBORReader {
/// - Throws:
/// - `CBORSerialization.Error`: If corrupted data is encountered
/// - `Swift.Error`: If any I/O error occurs
public func decodeItem() throws -> CBOR? {
private func decodeItem() throws -> CBOR? {
let initByte = try stream.readByte()

switch initByte {
Expand Down Expand Up @@ -215,28 +215,28 @@ public struct CBORReader {
return nil

default:
throw CBORError.invalidItemType
throw Error.invalidItemType
}
}

private func readFiniteString(initByte: UInt8) throws -> String {
let numBytes = try readLength(initByte, base: 0x60)
guard let string = String(data: try stream.readBytes(count: numBytes), encoding: .utf8) else {
throw CBORError.invalidUTF8String
throw Error.invalidUTF8String
}
return string
}

private func readIndefiniteString() throws -> String {
return try decodeItemsUntilBreak().map { item -> String in
guard case .utf8String(let string) = item else { throw CBORError.invalidIndefiniteElement }
guard case .utf8String(let string) = item else { throw Error.invalidIndefiniteElement }
return string
}.joined(separator: "")
}

private func readIndefiniteByteString() throws -> Data {
let datas = try decodeItemsUntilBreak().map { cbor -> Data in
guard case .byteString(let bytes) = cbor else { throw CBORError.invalidIndefiniteElement }
guard case .byteString(let bytes) = cbor else { throw Error.invalidIndefiniteElement }
return bytes
}.joined()
return Data(datas)
Expand All @@ -258,7 +258,7 @@ private enum VarUIntSize: UInt8 {
case 3: return .uint64
default:
// mask only allows values from 0-3
throw CBORError.invalidIntegerSize
throw CBORSerialization.Error.invalidIntegerSize
}
}
}
2 changes: 1 addition & 1 deletion Sources/PotentCBOR/CBORSerialization.swift
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public enum CBORSerialization {
/// - with: The `CBOR` item to serialize
/// - Throws:
/// - `Swift.Error`: If any stream I/O error is encountered
public static func data(with value: CBOR) throws -> Data {
public static func data(from value: CBOR) throws -> Data {
let stream = CBORDataStream()
let encoder = CBORWriter(stream: stream)
try encoder.encode(value)
Expand Down
Loading

0 comments on commit 0047ef5

Please sign in to comment.