Skip to content

Commit

Permalink
Fix some warnings about encoding and decoding Data and Date types
Browse files Browse the repository at this point in the history
  • Loading branch information
hamchapman committed Oct 28, 2024
1 parent 074a260 commit aed2b2a
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 32 deletions.
33 changes: 6 additions & 27 deletions Sources/Decoder/SingleValueDecodingContainer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -231,35 +231,14 @@ extension _CBORDecoder.SingleValueContainer: SingleValueDecodingContainer {
}
}

func decode(_ type: Data.Type) throws -> Data {
guard let cbor = try? CBOR.decode(self.data.map { $0 }) else {
let context = DecodingError.Context(codingPath: self.codingPath, debugDescription: "Invalid format: \(self.data)")
throw DecodingError.dataCorrupted(context)
}
switch cbor {
case .byteString(let bytes): return Data(bytes)
default:
let context = DecodingError.Context(codingPath: self.codingPath, debugDescription: "Invalid format: \(self.data)")
throw DecodingError.typeMismatch(Data.self, context)
}
}

func decode<T: Decodable>(_ type: T.Type) throws -> T {
switch type {
// TODO: These seem unnecessary/wrong?!
case is Data.Type:
return try decode(Data.self) as! T
case is Date.Type:
return try decode(Date.self) as! T
default:
let decoder = _CBORDecoder(data: self.data, options: self.options)
let value = try T(from: decoder)
if let nextIndex = decoder.container?.index {
self.index = nextIndex
}

return value
let decoder = _CBORDecoder(data: self.data, options: self.options)
let value = try T(from: decoder)
if let nextIndex = decoder.container?.index {
self.index = nextIndex
}

return value
}
}

Expand Down
9 changes: 4 additions & 5 deletions Sources/Encoder/SingleValueEncodingContainer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -131,14 +131,14 @@ extension _CBOREncoder.SingleValueContainer: SingleValueEncodingContainer {
self.storage.append(contentsOf: CBOR.encode(value))
}

func encode(_ value: Date) throws {
func encodeDate(_ value: Date) throws {
try checkCanEncode(value: value)
defer { self.canEncodeNewValue = false }

self.storage.append(contentsOf: CBOR.encodeDate(value, options: self.options.toCBOROptions()))
}

func encode(_ value: Data) throws {
func encodeData(_ value: Data) throws {
try checkCanEncode(value: value)
defer { self.canEncodeNewValue = false }

Expand All @@ -151,15 +151,14 @@ extension _CBOREncoder.SingleValueContainer: SingleValueEncodingContainer {

switch value {
case let data as Data:
try self.encode(data)
try self.encodeData(data)
case let date as Date:
try self.encode(date)
try self.encodeDate(date)
default:
let encoder = _CBOREncoder(options: self.options)
try value.encode(to: encoder)
self.storage.append(encoder.data)
}

}
}

Expand Down

0 comments on commit aed2b2a

Please sign in to comment.