repo_name stringlengths 1 62 | dataset stringclasses 1 value | lang stringclasses 11 values | pr_id int64 1 20.1k | owner stringlengths 2 34 | reviewer stringlengths 2 39 | diff_hunk stringlengths 15 262k | code_review_comment stringlengths 1 99.6k |
|---|---|---|---|---|---|---|---|
swift-openapi-runtime | github_2023 | others | 115 | apple | czechboy0 | @@ -46,7 +56,18 @@ extension ServerSentEventsDeserializationSequence: AsyncSequence {
var upstream: UpstreamIterator
/// The state machine of the iterator.
- var stateMachine: StateMachine = .init()
+ var stateMachine: StateMachine
+
+ /// A closure that determines whether the given byte sequence is the terminating byte sequence defined by the API. | ```suggestion
/// A closure that determines whether the given byte chunk should be forwarded to the consumer.
``` |
swift-openapi-runtime | github_2023 | others | 115 | apple | czechboy0 | @@ -46,7 +56,18 @@ extension ServerSentEventsDeserializationSequence: AsyncSequence {
var upstream: UpstreamIterator
/// The state machine of the iterator.
- var stateMachine: StateMachine = .init()
+ var stateMachine: StateMachine
+
+ /// A closure that determines whether the given byte sequence is the terminating byte sequence defined by the API.
+ /// - Parameter: A byte chunk.
+ /// - Returns: `True` until the terminating byte sequence is received. | ```suggestion
/// - Returns: `true` if the byte chunk should be forwarded, `false` if this byte chunk is the terminating sequence.
``` |
swift-openapi-runtime | github_2023 | others | 115 | apple | czechboy0 | @@ -46,7 +56,18 @@ extension ServerSentEventsDeserializationSequence: AsyncSequence {
var upstream: UpstreamIterator
/// The state machine of the iterator.
- var stateMachine: StateMachine = .init()
+ var stateMachine: StateMachine
+
+ /// A closure that determines whether the given byte sequence is the terminating byte sequence defined by the API.
+ /// - Parameter: A byte chunk.
+ /// - Returns: `True` until the terminating byte sequence is received.
+ let predicate: (ArraySlice<UInt8>) -> Bool
+
+ init(upstream: any AsyncIteratorProtocol, while predicate: @escaping ((ArraySlice<UInt8>) -> Bool)) {
+ self.upstream = upstream as! UpstreamIterator | ```suggestion
init(upstream: UpstreamIterator, while predicate: @escaping ((ArraySlice<UInt8>) -> Bool)) {
self.upstream = upstream
```
Also, please add a doc comment for the initializer as well. |
swift-openapi-runtime | github_2023 | others | 115 | apple | czechboy0 | @@ -133,8 +157,16 @@ extension ServerSentEventsDeserializationSequence.Iterator {
/// The current state of the state machine.
private(set) var state: State
+
+ /// A closure that determines whether the given byte sequence is the terminating byte sequence defined by the API.
+ /// - Parameter: A sequence of byte chunks.
+ /// - Returns: `True` until the terminating byte sequence is received.
+ let predicate: (ArraySlice<UInt8>) -> Bool | The closure should be added as an associated value to the State enum, rather than being a property next to it. That'll ensure we correctly handle it in all cases, and discard it when not needed anymore. |
swift-openapi-runtime | github_2023 | others | 115 | apple | czechboy0 | @@ -165,6 +197,12 @@ extension ServerSentEventsDeserializationSequence.Iterator {
state = .accumulatingEvent(.init(), buffer: buffer)
// If the last character of data is a newline, strip it.
if event.data?.hasSuffix("\n") ?? false { event.data?.removeLast() }
+
+ if let data = event.data {
+ if !predicate(ArraySlice(Data(data.utf8))) {
+ return .returnNil
+ }
+ }
return .emitEvent(event) | ```suggestion
// If the last character of data is a newline, strip it.
if event.data?.hasSuffix("\n") ?? false { event.data?.removeLast() }
state = .accumulatingEvent(.init(), buffer: buffer)
if let data = event.data, !predicate(ArraySlice(data.utf8)) {
state = .finished
return .returnNil
}
return .emitEvent(event)
``` |
swift-openapi-runtime | github_2023 | others | 115 | apple | czechboy0 | @@ -16,17 +16,19 @@ import XCTest
import Foundation
final class Test_ServerSentEventsDecoding: Test_Runtime {
- func _test(input: String, output: [ServerSentEvent], file: StaticString = #filePath, line: UInt = #line)
+ func _test(input: String, output: [ServerSentEvent], file: StaticString = #filePath, line: UInt = #line, while predicate: (ArraySlice<UInt8>) -> Bool = { _ in true }, eventCountOffset: Int = 0) | Do we need `eventCountOffset`? The test always accumulates the sequence in its fullness, and we can just verify the number of expected events passed through (so excluding the terminating event). |
swift-openapi-runtime | github_2023 | others | 115 | apple | czechboy0 | @@ -46,7 +56,22 @@ extension ServerSentEventsDeserializationSequence: AsyncSequence {
var upstream: UpstreamIterator
/// The state machine of the iterator.
- var stateMachine: StateMachine = .init()
+ var stateMachine: StateMachine
+
+ /// A closure that determines whether the given byte chunk should be forwarded to the consumer.
+ /// - Parameter: A byte chunk.
+ /// - Returns: `true` if the byte chunk should be forwarded, `false` if this byte chunk is the terminating sequence.
+ let predicate: (ArraySlice<UInt8>) -> Bool | Would it be possible to also remove the `predicate` property from the iterator type? I believe it should be enough for it to be owned by the state machine.
So it'd stay in the initializer of the iterator, but wouldn't be persisted as a property on the iterator, only forwarded to the state machine's iterator. |
swift-openapi-runtime | github_2023 | others | 115 | apple | czechboy0 | @@ -79,26 +104,29 @@ extension AsyncSequence where Element == ArraySlice<UInt8>, Self: Sendable {
/// Returns another sequence that decodes each event's data as the provided type using the provided decoder.
///
/// Use this method if the event's `data` field is not JSON, or if you don't want to parse it using `asDecodedServerSentEventsWithJSONData`.
+ /// - Parameter: A closure that determines whether the given byte sequence is the terminating byte sequence defined by the API. | ```suggestion
/// - Parameter: A closure that determines whether the given byte chunk should be forwarded to the consumer.
``` |
swift-openapi-runtime | github_2023 | others | 115 | apple | czechboy0 | @@ -28,9 +28,19 @@ where Upstream.Element == ArraySlice<UInt8> {
/// The upstream sequence.
private let upstream: Upstream
+ /// A closure that determines whether the given byte chunk should be forwarded to the consumer.
+ /// - Parameter: A byte chunk.
+ /// - Returns: `true` if the byte chunk should be forwarded, `false` if this byte chunk is the terminating sequence.
+ private let predicate: @Sendable (ArraySlice<UInt8>) -> Bool
+
/// Creates a new sequence.
- /// - Parameter upstream: The upstream sequence of arbitrary byte chunks.
- public init(upstream: Upstream) { self.upstream = upstream }
+ /// - Parameters:
+ /// - upstream: The upstream sequence of arbitrary byte chunks.
+ /// - while: A closure that determines whether the given byte chunk should be forwarded to the consumer. | ```suggestion
/// - predicate: A closure that determines whether the given byte chunk should be forwarded to the consumer.
```
IIRC the parameter name (not the label) is what's used in docs - try to run the soundness script to verify. |
swift-openapi-runtime | github_2023 | others | 115 | apple | czechboy0 | @@ -156,20 +180,26 @@ extension ServerSentEventsDeserializationSequence.Iterator {
/// - Returns: An action to perform.
mutating func next() -> NextAction {
switch state {
- case .accumulatingEvent(var event, var buffer):
+ case .accumulatingEvent(var event, var buffer, let predicate):
guard let line = buffer.first else { return .needsMore }
state = .mutating
buffer.removeFirst()
if line.isEmpty {
// Dispatch the accumulated event.
- state = .accumulatingEvent(.init(), buffer: buffer)
// If the last character of data is a newline, strip it.
if event.data?.hasSuffix("\n") ?? false { event.data?.removeLast() }
+
+ state = .accumulatingEvent(.init(), buffer: buffer, predicate: predicate)
+
+ if let data = event.data, !predicate(ArraySlice(data.utf8)) {
+ state = .finished
+ return .returnNil
+ }
return .emitEvent(event) | ```suggestion
if let data = event.data, !predicate(ArraySlice(data.utf8)) {
state = .finished
return .returnNil
}
state = .accumulatingEvent(.init(), buffer: buffer, predicate: predicate)
return .emitEvent(event)
```
Minor - the state should only be assigned a single time in each pass. |
swift-openapi-runtime | github_2023 | others | 107 | apple | czechboy0 | @@ -1,4 +1,4 @@
-// swift-tools-version: 5.9
+// swift-tools-version: 6.0 | This would break existing users on pre-6.0 toolchains, so we can't do it this way. |
swift-openapi-runtime | github_2023 | others | 107 | apple | czechboy0 | @@ -17,7 +17,7 @@ extension URL {
/// Returns the default server URL of "/".
///
/// Specification: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#fixed-fields
- public static let defaultOpenAPIServerURL: Self = {
+ public nonisolated(unsafe) static let defaultOpenAPIServerURL: Self = { | This would be better fixed by Foundation.URL being Sendable on Linux (it already is on Darwin). |
swift-openapi-runtime | github_2023 | others | 107 | apple | czechboy0 | @@ -50,16 +50,16 @@ extension CharacterSet {
/// A character set of unreserved symbols only from RFC 6570 (excludes
/// alphanumeric characters).
- fileprivate static let unreservedSymbols: CharacterSet = .init(charactersIn: "-._~")
+ fileprivate nonisolated(unsafe) static let unreservedSymbols: CharacterSet = .init(charactersIn: "-._~") | This would be better fixed by Foundation.CharacterSet being Sendable on Linux (it already is on Darwin). |
swift-openapi-runtime | github_2023 | others | 107 | apple | czechboy0 | @@ -342,8 +342,13 @@ extension MultipartFramesToRawPartsSequence {
switch stateMachine.nextFromPartSequence() {
case .returnNil: return nil
case .fetchFrame:
+ let frame : Upstream.AsyncIterator.Element? | Could you break out these async sequence iteration fixes into a separate PR? These I think we'll be able to land soon, but the other ones (CharacterSet and URL), I'd like us to fix in swift-corelibs-foundation instead.
The shape of this fix is correct, but I wonder if we can make the `#if` more selective to the stdlib having `next(isolation:)`, rather than to switch by platform? |
swift-openapi-runtime | github_2023 | others | 112 | apple | simonjbeaumont | @@ -12,7 +12,7 @@
//
//===----------------------------------------------------------------------===//
import XCTest
-@_spi(Generated) import OpenAPIRuntime
+@_spi(Generated) @testable import OpenAPIRuntime | OOI, why was the `@testable` import needed here? Could we write the tests to use only the API? |
swift-openapi-runtime | github_2023 | others | 108 | apple | czechboy0 | @@ -342,8 +342,17 @@ extension MultipartFramesToRawPartsSequence {
switch stateMachine.nextFromPartSequence() {
case .returnNil: return nil
case .fetchFrame:
+ let frame: Upstream.AsyncIterator.Element?
var upstream = upstream
- let frame = try await upstream.next()
+ if #available(macOS 15, iOS 18.0, tvOS 18.0, watchOS 11.0, macCatalyst 18.0, visionOS 2.0, *) {
+ #if compiler(>=6.0)
+ frame = try await upstream.next(isolation: self)
+ #else
+ frame = try await upstream.next()
+ #endif
+ } else {
+ frame = try await upstream.next()
+ } | While we're here, would you mind creating an extension on `AsyncIteratorProtocol` that adds a utility method for this dance, and call it from these two places you're updating in the PR? It'd take the actor as a parameter. |
swift-openapi-runtime | github_2023 | others | 100 | apple | simonjbeaumont | @@ -61,13 +61,15 @@ extension URIParser {
switch configuration.style {
case .form: return [:]
case .simple: return ["": [""]]
+ case .deepObject: return [:]
}
}
switch (configuration.style, configuration.explode) {
case (.form, true): return try parseExplodedFormRoot()
case (.form, false): return try parseUnexplodedFormRoot()
case (.simple, true): return try parseExplodedSimpleRoot()
case (.simple, false): return try parseUnexplodedSimpleRoot()
+ case (.deepObject, _): return try parseExplodedDeepObjectRoot() | My reading of the OAS is that `deepObject` is only valid with `explode: true`[^0]. If that's the case, we should probably guard against that somehow.
[^0]: https://spec.openapis.org/oas/latest.html#style-examples |
swift-openapi-runtime | github_2023 | others | 100 | apple | simonjbeaumont | @@ -205,6 +207,50 @@ extension URIParser {
}
}
}
+
+ /// Parses the root node assuming the raw string uses the deepObject style
+ /// and the explode parameter is enabled.
+ /// - Returns: The parsed root node.
+ /// - Throws: An error if parsing fails.
+ private mutating func parseExplodedDeepObjectRoot() throws -> URIParsedNode {
+ try parseGenericRoot { data, appendPair in
+ let keyValueSeparator: Character = "="
+ let pairSeparator: Character = "&"
+ let nestedKeyStartingCharacter: Character = "["
+ let nestedKeyEndingCharacter: Character = "]"
+
+ func nestedKey(from deepObjectKey: String.SubSequence) -> Raw {
+ var unescapedFirstValue = Substring(deepObjectKey.removingPercentEncoding ?? "")
+ let nestedKey = unescapedFirstValue.parseBetweenCharacters(
+ startingCharacter: nestedKeyStartingCharacter,
+ endingCharacter: nestedKeyEndingCharacter
+ )
+ return nestedKey
+ }
+
+ while !data.isEmpty {
+ let (firstResult, firstValue) = data.parseUpToEitherCharacterOrEnd(
+ first: keyValueSeparator,
+ second: pairSeparator
+ )
+ let key: Raw
+ let value: Raw
+ switch firstResult {
+ case .foundFirst:
+ // Hit the key/value separator, so a value will follow.
+ let secondValue = data.parseUpToCharacterOrEnd(pairSeparator)
+
+ key = nestedKey(from: firstValue)
+ value = secondValue
+ case .foundSecondOrEnd:
+ // No key/value separator, treat the string as the key.
+ key = nestedKey(from: firstValue)
+ value = .init()
+ } | Can you give an example for this case? The spec is light on examples and IIUC doesn't have an example that _isn't_ the `object[key]=value` form. |
swift-openapi-runtime | github_2023 | others | 100 | apple | simonjbeaumont | @@ -326,4 +372,35 @@ extension String.SubSequence {
}
return finalize()
}
+
+
+ /// Accumulates characters from the `startingCharacter` character provided,
+ /// until the `endingCharacter` is reached. Moves the underlying startIndex.
+ /// - Parameters:
+ /// - startingCharacter: A character to start with.
+ /// - endingCharacter: A character to stop at.
+ /// - Returns: The accumulated substring.
+ fileprivate mutating func parseBetweenCharacters(startingCharacter: Character, endingCharacter: Character) -> Self {
+ let startIndex = startIndex | This seems redundant? |
swift-openapi-runtime | github_2023 | others | 100 | apple | simonjbeaumont | @@ -326,4 +372,35 @@ extension String.SubSequence {
}
return finalize()
}
+
+
+ /// Accumulates characters from the `startingCharacter` character provided,
+ /// until the `endingCharacter` is reached. Moves the underlying startIndex.
+ /// - Parameters:
+ /// - startingCharacter: A character to start with.
+ /// - endingCharacter: A character to stop at.
+ /// - Returns: The accumulated substring.
+ fileprivate mutating func parseBetweenCharacters(startingCharacter: Character, endingCharacter: Character) -> Self {
+ let startIndex = startIndex
+ guard startIndex != endIndex else { return .init() }
+ guard let startingCharacterIndex = firstIndex(of: startingCharacter) else { return self }
+ var currentIndex = startingCharacterIndex
+
+// var x = self.firstIndex(of: startingCharacter) | Presumably this can now be removed? |
swift-openapi-runtime | github_2023 | others | 100 | apple | simonjbeaumont | @@ -326,4 +372,35 @@ extension String.SubSequence {
}
return finalize()
}
+
+
+ /// Accumulates characters from the `startingCharacter` character provided,
+ /// until the `endingCharacter` is reached. Moves the underlying startIndex.
+ /// - Parameters:
+ /// - startingCharacter: A character to start with.
+ /// - endingCharacter: A character to stop at.
+ /// - Returns: The accumulated substring.
+ fileprivate mutating func parseBetweenCharacters(startingCharacter: Character, endingCharacter: Character) -> Self { | This function seems to overlap significantly with `parseUpToCharacterOrEnd(_:)`, the only difference is that we move the index forward to the first occurrence of `startingCharacter` first. Do we need the duplication, or can we implement one in terms of the other? |
swift-openapi-runtime | github_2023 | others | 100 | apple | simonjbeaumont | @@ -387,16 +407,20 @@ final class Test_URICodingRoundtrip: Test_Runtime {
let decodedValue = try decoder.decode(T.self, forKey: key, from: encodedString[...])
XCTAssertEqual(decodedValue, variant.customValue ?? value, "Variant: \(name)", file: file, line: line)
}
- try testVariant(name: "formExplode", configuration: .formExplode, variant: variants.formExplode)
- try testVariant(name: "formUnexplode", configuration: .formUnexplode, variant: variants.formUnexplode)
- try testVariant(name: "simpleExplode", configuration: .simpleExplode, variant: variants.simpleExplode)
- try testVariant(name: "simpleUnexplode", configuration: .simpleUnexplode, variant: variants.simpleUnexplode)
- try testVariant(name: "formDataExplode", configuration: .formDataExplode, variant: variants.formDataExplode)
+// try testVariant(name: "formExplode", configuration: .formExplode, variant: variants.formExplode)
+// try testVariant(name: "formUnexplode", configuration: .formUnexplode, variant: variants.formUnexplode)
+// try testVariant(name: "simpleExplode", configuration: .simpleExplode, variant: variants.simpleExplode)
+// try testVariant(name: "simpleUnexplode", configuration: .simpleUnexplode, variant260*52: variants.simpleUnexplode)
+// try testVariant(name: "formDataExplode", configuration: .formDataExplode, variant: variants.formDataExplode)
+// try testVariant(
+// name: "formDataUnexplode",
+// configuration: .formDataUnexplode,
+// variant: variants.formDataUnexplode
+// )
try testVariant(
- name: "formDataUnexplode",
- configuration: .formDataUnexplode,
- variant: variants.formDataUnexplode
+ name: "deepObjectExplode",
+ configuration: .deepObjectExplode,
+ variant: variants.deepObjectExplode | This appears to have disabled a bunch of tests. |
swift-openapi-runtime | github_2023 | others | 100 | apple | czechboy0 | @@ -26,6 +26,11 @@
///
/// Details: https://datatracker.ietf.org/doc/html/rfc6570#section-3.2.2
case simple
+
+ /// The deepObject style.
+ ///
+ /// Details: Should update datatracker | Can you put a link to the RFC please? |
swift-openapi-runtime | github_2023 | others | 100 | apple | czechboy0 | @@ -205,6 +207,50 @@ extension URIParser {
}
}
}
+
+ /// Parses the root node assuming the raw string uses the deepObject style
+ /// and the explode parameter is enabled.
+ /// - Returns: The parsed root node.
+ /// - Throws: An error if parsing fails.
+ private mutating func parseExplodedDeepObjectRoot() throws -> URIParsedNode {
+ try parseGenericRoot { data, appendPair in
+ let keyValueSeparator: Character = "="
+ let pairSeparator: Character = "&"
+ let nestedKeyStartingCharacter: Character = "["
+ let nestedKeyEndingCharacter: Character = "]"
+
+ func nestedKey(from deepObjectKey: String.SubSequence) -> Raw {
+ var unescapedFirstValue = Substring(deepObjectKey.removingPercentEncoding ?? "")
+ let nestedKey = unescapedFirstValue.parseBetweenCharacters(
+ startingCharacter: nestedKeyStartingCharacter,
+ endingCharacter: nestedKeyEndingCharacter
+ )
+ return nestedKey
+ }
+
+ while !data.isEmpty {
+ let (firstResult, firstValue) = data.parseUpToEitherCharacterOrEnd(
+ first: keyValueSeparator,
+ second: pairSeparator
+ )
+ let key: Raw
+ let value: Raw
+ switch firstResult {
+ case .foundFirst:
+ // Hit the key/value separator, so a value will follow.
+ let secondValue = data.parseUpToCharacterOrEnd(pairSeparator)
+ | ```suggestion
``` |
swift-openapi-runtime | github_2023 | others | 100 | apple | czechboy0 | @@ -180,6 +181,9 @@ extension URISerializer {
case (.simple, _):
keyAndValueSeparator = nil
pairSeparator = ","
+ case (.deepObject, _): | By my reading of the OpenAPI 3.1 specification, deepObject _must_ have a JSON object at the top, so an array would not be supported? https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-examples |
swift-openapi-runtime | github_2023 | others | 100 | apple | czechboy0 | @@ -228,8 +232,15 @@ extension URISerializer {
case (.simple, false):
keyAndValueSeparator = ","
pairSeparator = ","
+ case (.deepObject, _): | I think we should again validate that explode is true, and throw an error on false. |
swift-openapi-runtime | github_2023 | others | 100 | apple | czechboy0 | @@ -228,8 +232,15 @@ extension URISerializer {
case (.simple, false):
keyAndValueSeparator = ","
pairSeparator = ","
+ case (.deepObject, _):
+ keyAndValueSeparator = "="
+ pairSeparator = "&"
}
+ func serializeNestedKey(_ elementKey: String, forKey rootKey: String) -> String {
+ guard case .deepObject = configuration.style else { return elementKey }
+ return rootKey + "[" + elementKey + "]" | Can you check that we end up percent-escaping the `[` and `]` characters? Technically they should be escaped.
However, when parsing, we should be flexible and support both escaped and unescaped. |
swift-openapi-runtime | github_2023 | others | 100 | apple | czechboy0 | @@ -23,4 +23,12 @@ final class Test_URIEncoder: Test_Runtime {
let encodedString = try encoder.encode(Foo(bar: "hello world"), forKey: "root")
XCTAssertEqual(encodedString, "bar=hello+world")
}
+
+ func testNestedEncoding() throws {
+ struct Foo: Encodable { var bar: String }
+ let serializer = URISerializer(configuration: .deepObjectExplode)
+ let encoder = URIEncoder(serializer: serializer)
+ let encodedString = try encoder.encode(Foo(bar: "hello world"), forKey: "root")
+ XCTAssertEqual(encodedString, "root%5Bbar%5D=hello+world") | Are we sure that deepObject uses `+` instead of `%20` for encoding spaces? Can you find it in the RFC? |
swift-openapi-runtime | github_2023 | others | 100 | apple | czechboy0 | @@ -103,7 +109,8 @@ final class Test_URISerializer: Test_Runtime {
simpleExplode: "red,green,blue",
simpleUnexplode: "red,green,blue",
formDataExplode: "list=red&list=green&list=blue",
- formDataUnexplode: "list=red,green,blue"
+ formDataUnexplode: "list=red,green,blue",
+ deepObjectExplode: "list=red&list=green&list=blue" | Let's figure out what we do with arrays, I think either we don't support them, or they should be something like `list[]=red&...` or `list[0]=red&...` |
swift-openapi-runtime | github_2023 | others | 100 | apple | czechboy0 | @@ -118,7 +125,8 @@ final class Test_URISerializer: Test_Runtime {
simpleExplode: "comma=%2C,dot=.,semi=%3B",
simpleUnexplode: "comma,%2C,dot,.,semi,%3B",
formDataExplode: "comma=%2C&dot=.&semi=%3B",
- formDataUnexplode: "keys=comma,%2C,dot,.,semi,%3B"
+ formDataUnexplode: "keys=comma,%2C,dot,.,semi,%3B",
+ deepObjectExplode: "keys%5Bcomma%5D=%2C&keys%5Bdot%5D=.&keys%5Bsemi%5D=%3B" | Ah cool, this answers my question about escaping. Can you add another test case that verifies that we successfully parse strings with the `[` and `]` unescaped? |
swift-openapi-runtime | github_2023 | others | 100 | apple | czechboy0 | @@ -302,17 +349,55 @@ extension String.SubSequence {
return finalize(.foundSecondOrEnd)
}
+
/// Accumulates characters until the provided character is found,
/// or the end is reached. Moves the underlying startIndex.
- /// - Parameter character: A character to stop at.
+ /// - Parameters:
+ /// - startingCharacter: A character to start with.
+ /// - endingCharacter: A character to stop at.
+ /// If not provided or not found then uses the current start index as a starting character.
/// - Returns: The accumulated substring.
- fileprivate mutating func parseUpToCharacterOrEnd(_ character: Character) -> Self {
- let startIndex = startIndex
+ fileprivate mutating func parseUpToCharacterOrEnd(startingCharacter: Character? = nil, _ endingCharacter: Character) -> Self { | Can we take one more look here? Could you try to revert this part and go back to the original parseUpToCharacterOrEnd(_ character: Character) function, and explain why it can't work for you? |
swift-openapi-runtime | github_2023 | others | 100 | apple | czechboy0 | @@ -205,6 +213,45 @@ extension URIParser {
}
}
}
+
+ /// Parses the root node assuming the raw string uses the deepObject style
+ /// and the explode parameter is enabled.
+ /// - Returns: The parsed root node.
+ /// - Throws: An error if parsing fails.
+ private mutating func parseExplodedDeepObjectRoot() throws -> URIParsedNode {
+ try parseGenericRoot { data, appendPair in
+ let keyValueSeparator: Character = "="
+ let pairSeparator: Character = "&"
+ let nestedKeyStartingCharacter: Character = "["
+ let nestedKeyEndingCharacter: Character = "]"
+
+ func nestedKey(from deepObjectKey: String.SubSequence) -> Raw {
+ var unescapedFirstValue = Substring(deepObjectKey.removingPercentEncoding ?? "") | Here you should verify that the first character is `[`, otherwise this is a malformed key. For the rest of the characters, you should be able to use `parseUpToCharacterOrEnd` as originally was. |
swift-openapi-runtime | github_2023 | others | 100 | apple | czechboy0 | @@ -29,7 +29,8 @@ final class Test_URIParser: Test_Runtime {
simpleExplode: .custom("", value: ["": [""]]),
simpleUnexplode: .custom("", value: ["": [""]]),
formDataExplode: "empty=",
- formDataUnexplode: "empty="
+ formDataUnexplode: "empty=",
+ deepObjectExplode: "empty=" | Shouldn't this have some square brackets? |
swift-openapi-runtime | github_2023 | others | 100 | apple | czechboy0 | @@ -51,7 +53,8 @@ final class Test_URIParser: Test_Runtime {
simpleExplode: .custom("fred", value: ["": ["fred"]]),
simpleUnexplode: .custom("fred", value: ["": ["fred"]]),
formDataExplode: "who=fred",
- formDataUnexplode: "who=fred"
+ formDataUnexplode: "who=fred",
+ deepObjectExplode: "who=fred" | Shouldn't this have some square brackets? |
swift-openapi-runtime | github_2023 | others | 100 | apple | czechboy0 | @@ -62,7 +65,8 @@ final class Test_URIParser: Test_Runtime {
simpleExplode: .custom("Hello%20World", value: ["": ["Hello World"]]),
simpleUnexplode: .custom("Hello%20World", value: ["": ["Hello World"]]),
formDataExplode: "hello=Hello+World",
- formDataUnexplode: "hello=Hello+World"
+ formDataUnexplode: "hello=Hello+World",
+ deepObjectExplode: "hello=Hello%20World" | Shouldn't this have some square brackets? |
swift-openapi-runtime | github_2023 | others | 100 | apple | czechboy0 | @@ -73,7 +77,8 @@ final class Test_URIParser: Test_Runtime {
simpleExplode: .custom("red,green,blue", value: ["": ["red", "green", "blue"]]),
simpleUnexplode: .custom("red,green,blue", value: ["": ["red", "green", "blue"]]),
formDataExplode: "list=red&list=green&list=blue",
- formDataUnexplode: "list=red,green,blue"
+ formDataUnexplode: "list=red,green,blue",
+ deepObjectExplode: "list=red&list=green&list=blue" | Shouldn't this have some square brackets? Or be unsupported, as an array? |
swift-openapi-runtime | github_2023 | others | 100 | apple | czechboy0 | @@ -93,7 +98,8 @@ final class Test_URIParser: Test_Runtime {
formDataUnexplode: .custom(
"keys=comma,%2C,dot,.,semi,%3B",
value: ["keys": ["comma", ",", "dot", ".", "semi", ";"]]
- )
+ ),
+ deepObjectExplode: "comma=%2C&dot=.&semi=%3B" | Shouldn't this have some square brackets? |
swift-openapi-runtime | github_2023 | others | 100 | apple | czechboy0 | @@ -31,7 +31,8 @@ final class Test_URISerializer: Test_Runtime {
simpleExplode: "",
simpleUnexplode: "",
formDataExplode: "empty=",
- formDataUnexplode: "empty="
+ formDataUnexplode: "empty=",
+ deepObjectExplode: "empty=" | Same in this whole file: Shouldn't this have some square brackets? |
swift-openapi-runtime | github_2023 | others | 100 | apple | czechboy0 | @@ -140,6 +148,9 @@ final class Test_URISerializer: Test_Runtime {
try testVariant(.simpleUnexplode, testCase.variants.simpleUnexplode)
try testVariant(.formDataExplode, testCase.variants.formDataExplode)
try testVariant(.formDataUnexplode, testCase.variants.formDataUnexplode)
+ if let deepObjectExplode = testCase.variants.deepObjectExplode { | Why is this if statement here instead of running the variant unconditionally like the previous few? |
swift-openapi-runtime | github_2023 | others | 100 | apple | czechboy0 | @@ -36,13 +36,16 @@ struct URIParser: Sendable {
}
/// A typealias for the underlying raw string storage.
-private typealias Raw = String.SubSequence
+typealias Raw = String.SubSequence
/// A parser error.
-private enum ParsingError: Swift.Error {
+enum ParsingError: Swift.Error, Equatable { | ```suggestion
enum ParsingError: Swift.Error, Hashable {
```
We should always customize both together (Equatable and Hashable), this does that. |
swift-openapi-runtime | github_2023 | others | 102 | apple | czechboy0 | @@ -144,6 +144,32 @@ extension Converter {
return HTTPBody(data)
}
+ /// Returns a value decoded from a XML body.
+ /// - Parameter body: The body containing the raw XML bytes.
+ /// - Returns: A decoded value.
+ /// - Throws: An error if decoding from the body fails.
+ /// - Throws: An error if no custom coder is present for XML coding.
+ func convertXMLToBodyCodable<T: Decodable>(_ body: HTTPBody) async throws -> T {
+ guard let coder = configuration.customCoder(for: "application/xml") else { | Please add a static let for xml on the `OpenAPIMIMEType` type, and use that here, so that we don't need to copy the raw MIME type for XML 4 times in this file. |
swift-openapi-runtime | github_2023 | others | 102 | apple | czechboy0 | @@ -88,6 +89,7 @@ internal enum RuntimeError: Error, CustomStringConvertible, LocalizedError, Pret
case .invalidBase64String(let string):
return "Invalid base64-encoded string (first 128 bytes): '\(string.prefix(128))'"
case .failedToDecodeStringConvertibleValue(let string): return "Failed to decode a value of type '\(string)'."
+ case .missingCoderForCustomContentType(let contentType): return "Missing custom coder for content type '\(contentType)'" | ```suggestion
case .missingCoderForCustomContentType(let contentType): return "Missing custom coder for content type '\(contentType)'."
``` |
swift-openapi-runtime | github_2023 | others | 102 | apple | czechboy0 | @@ -120,6 +120,30 @@ final class Test_ClientConverterExtensions: Test_Runtime {
try await XCTAssertEqualStringifiedData(body, testStructPrettyString)
XCTAssertEqual(headerFields, [.contentType: "application/json", .contentLength: "23"])
}
+
+ // | client | set | request body | XML | optional | setOptionalRequestBodyAsXML | | Reminder: Please adapt the `Converting-between-data-and-Swift-types.md` docs page with the addition of XML in your swift-openapi-generator PR, when it comes to it. |
swift-openapi-runtime | github_2023 | others | 102 | apple | czechboy0 | @@ -105,17 +123,27 @@ public struct Configuration: Sendable {
/// The generator to use when creating mutlipart bodies.
public var multipartBoundaryGenerator: any MultipartBoundaryGenerator
+ public var customCoders: [String: any CustomCoder] | I'm a bit worried about this being too generic and folks assuming it'll override the JSON coders as well (which it won't).
Could you change this to `public var xmlCoder: (any CustomCoder)?` instead? I think it's better to be explicit here. |
swift-openapi-runtime | github_2023 | others | 102 | apple | czechboy0 | @@ -96,6 +96,24 @@ extension JSONDecoder.DateDecodingStrategy {
}
}
+/// A type that allows custom content type encoding and decoding.
+public protocol CustomCoder: Sendable {
+
+ /// Encodes the given value and returns its custom encoded representation.
+ ///
+ /// - parameter value: The value to encode.
+ /// - returns: A new `Data` value containing the custom encoded data.
+ func customEncode<T: Encodable>(_ value: T) throws -> Data | Please run the `./scripts/soundness.sh` script and check it doesn't produce any warnings, I think these comments aren't entirely consistent with the rest. |
swift-openapi-runtime | github_2023 | others | 102 | apple | czechboy0 | @@ -105,17 +123,24 @@ public struct Configuration: Sendable {
/// The generator to use when creating mutlipart bodies.
public var multipartBoundaryGenerator: any MultipartBoundaryGenerator
+ /// Custom XML coder for encoding and decoding xml bodies.
+ public var xmlCoder: (any CustomCoder)?
+
/// Creates a new configuration with the specified values.
///
/// - Parameters:
/// - dateTranscoder: The transcoder to use when converting between date
/// and string values.
/// - multipartBoundaryGenerator: The generator to use when creating mutlipart bodies.
+ /// - xmlCoder: Custom XML coder for encoding and decoding xml bodies. | ```suggestion
/// - xmlCoder: Custom XML coder for encoding and decoding xml bodies. Only required when using XML body payloads.
``` |
swift-openapi-runtime | github_2023 | others | 102 | apple | czechboy0 | @@ -105,17 +123,24 @@ public struct Configuration: Sendable {
/// The generator to use when creating mutlipart bodies.
public var multipartBoundaryGenerator: any MultipartBoundaryGenerator
+ /// Custom XML coder for encoding and decoding xml bodies.
+ public var xmlCoder: (any CustomCoder)?
+
/// Creates a new configuration with the specified values.
///
/// - Parameters:
/// - dateTranscoder: The transcoder to use when converting between date
/// and string values.
/// - multipartBoundaryGenerator: The generator to use when creating mutlipart bodies.
+ /// - xmlCoder: Custom XML coder for encoding and decoding xml bodies.
public init(
dateTranscoder: any DateTranscoder = .iso8601,
- multipartBoundaryGenerator: any MultipartBoundaryGenerator = .random
+ multipartBoundaryGenerator: any MultipartBoundaryGenerator = .random,
+ xmlCoder: (any CustomCoder)? = nil | You'll also need to add a deprecated version of the 2-param initializer into `Deprecated.swift`, as adding a parameter is technically an API-breaking change, so we also need the previous one, and it'll just call back into this one. Something like:
```swift
extension Configuration {
/// Creates a new payload.
@available(*, deprecated, renamed: "init(dateTranscoder:multipartBoundaryGenerator:xmlCoder:)") @_disfavoredOverload
public init(
dateTranscoder: any DateTranscoder = .iso8601,
multipartBoundaryGenerator: any MultipartBoundaryGenerator = .random
) {
self.init(
dateTranscoder: dateTranscoder,
multipartBoundaryGenerator: multipartBoundaryGenerator,
xmlCoder: nil
)
}
}
``` |
swift-openapi-runtime | github_2023 | others | 94 | apple | simonjbeaumont | @@ -25,14 +25,45 @@ public protocol DateTranscoder: Sendable {
}
/// A transcoder for dates encoded as an ISO-8601 string (in RFC 3339 format).
-public struct ISO8601DateTranscoder: DateTranscoder {
+public struct ISO8601DateTranscoder: DateTranscoder, @unchecked Sendable {
+
+ /// The lock protecting the formatter.
+ private let lock: NSLock
+
+ /// The underlying date formatter.
+ private let locked_formatter: ISO8601DateFormatter
+
+ /// Creates a new default transcoder.
+ public init() { self.init(optionsOverride: nil) }
+
+ /// Creates a new transcoder with the provided options.
+ /// - Parameter optionsOverride: Options to override the default ones. If you provide
+ /// nil here, the default options are used.
+ public init(optionsOverride: ISO8601DateFormatter.Options?) { | Maybe if we spell this as `init(options: ISO8601DateFormatter.Options? = nil)`, the optionality and nil-default will imply a default-when-nil, which can also be documented for additional clarity. |
swift-openapi-runtime | github_2023 | others | 94 | apple | simonjbeaumont | @@ -25,14 +25,45 @@ public protocol DateTranscoder: Sendable {
}
/// A transcoder for dates encoded as an ISO-8601 string (in RFC 3339 format).
-public struct ISO8601DateTranscoder: DateTranscoder {
+public struct ISO8601DateTranscoder: DateTranscoder, @unchecked Sendable {
+
+ /// The lock protecting the formatter.
+ private let lock: NSLock
+
+ /// The underlying date formatter.
+ private let locked_formatter: ISO8601DateFormatter | Do we need to have a stored property for the formatter and consequently have to deal with the locking? Could we instead hold an `IOS8601DateFormatter.Options` and use this when we create the formatter?
Alternatively, I notice that `ISO8601DateFormatter` has [`class func string(from:timeZone:formatOptions:)`](https://developer.apple.com/documentation/foundation/iso8601dateformatter/1642834-string) so maybe we just use that and pass the options that the user provides?
|
swift-openapi-runtime | github_2023 | others | 94 | apple | simonjbeaumont | @@ -25,14 +25,45 @@ public protocol DateTranscoder: Sendable {
}
/// A transcoder for dates encoded as an ISO-8601 string (in RFC 3339 format).
-public struct ISO8601DateTranscoder: DateTranscoder {
+public struct ISO8601DateTranscoder: DateTranscoder, @unchecked Sendable {
+
+ /// The lock protecting the formatter.
+ private let lock: NSLock
+
+ /// The underlying date formatter.
+ private let locked_formatter: ISO8601DateFormatter
+
+ /// Creates a new default transcoder.
+ public init() { self.init(optionsOverride: nil) }
+
+ /// Creates a new transcoder with the provided options.
+ /// - Parameter optionsOverride: Options to override the default ones. If you provide
+ /// nil here, the default options are used.
+ public init(optionsOverride: ISO8601DateFormatter.Options?) {
+ let formatter = ISO8601DateFormatter()
+ if let optionsOverride { formatter.formatOptions = optionsOverride }
+ self.init(formatter: formatter)
+ }
+
+ /// Creates a new transcoder with the provided formatter.
+ /// - Parameter formatter: The formatter to use.
+ public init(formatter: ISO8601DateFormatter) { | If we don't need it now, let's drop it until we have a need. |
swift-openapi-runtime | github_2023 | others | 94 | apple | simonjbeaumont | @@ -25,14 +25,45 @@ public protocol DateTranscoder: Sendable {
}
/// A transcoder for dates encoded as an ISO-8601 string (in RFC 3339 format).
-public struct ISO8601DateTranscoder: DateTranscoder {
+public struct ISO8601DateTranscoder: DateTranscoder, @unchecked Sendable {
+
+ /// The lock protecting the formatter.
+ private let lock: NSLock
+
+ /// The underlying date formatter.
+ private let locked_formatter: ISO8601DateFormatter
+
+ /// Creates a new default transcoder.
+ public init() { self.init(optionsOverride: nil) }
+
+ /// Creates a new transcoder with the provided options.
+ /// - Parameter optionsOverride: Options to override the default ones. If you provide
+ /// nil here, the default options are used.
+ public init(optionsOverride: ISO8601DateFormatter.Options?) {
+ let formatter = ISO8601DateFormatter()
+ if let optionsOverride { formatter.formatOptions = optionsOverride }
+ self.init(formatter: formatter)
+ }
+
+ /// Creates a new transcoder with the provided formatter.
+ /// - Parameter formatter: The formatter to use.
+ public init(formatter: ISO8601DateFormatter) {
+ lock = NSLock()
+ locked_formatter = formatter
+ }
/// Creates and returns an ISO 8601 formatted string representation of the specified date.
- public func encode(_ date: Date) throws -> String { ISO8601DateFormatter().string(from: date) }
+ public func encode(_ date: Date) throws -> String {
+ lock.lock()
+ defer { lock.unlock() } | If we do decide to keep the formatter and still need locking can we pull in the `LockedValueBox` so we don't need to use unchecked sendable? |
swift-openapi-runtime | github_2023 | others | 94 | apple | simonjbeaumont | @@ -44,6 +75,11 @@ public struct ISO8601DateTranscoder: DateTranscoder {
extension DateTranscoder where Self == ISO8601DateTranscoder {
/// A transcoder that transcodes dates as ISO-8601–formatted string (in RFC 3339 format).
public static var iso8601: Self { ISO8601DateTranscoder() }
+
+ /// A transcoder that transcodes dates as ISO-8601–formatted string (in RFC 3339 format) with fractional seconds.
+ public static var iso8601WithFractionalSeconds: Self { | Maybe we don't have it, but if we do I think the name is clear enough. OOI, is it a problem to include fractional seconds in `.iso8601`? |
swift-openapi-runtime | github_2023 | others | 91 | apple | simonjbeaumont | @@ -122,3 +125,34 @@ extension RandomAccessCollection where Element: Equatable {
return .noMatch
}
}
+
+/// A value returned by the `longestMatchOfOneOf` method. | ```suggestion
/// A value returned by the `matchOfOneOf` method.
``` |
swift-openapi-runtime | github_2023 | others | 91 | apple | simonjbeaumont | @@ -0,0 +1,236 @@
+//===----------------------------------------------------------------------===//
+//
+// This source file is part of the SwiftOpenAPIGenerator open source project
+//
+// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors
+// Licensed under Apache License v2.0
+//
+// See LICENSE.txt for license information
+// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors
+//
+// SPDX-License-Identifier: Apache-2.0
+//
+//===----------------------------------------------------------------------===//
+
+#if canImport(Darwin)
+import class Foundation.JSONDecoder
+#else
+@preconcurrency import class Foundation.JSONDecoder
+#endif
+import protocol Foundation.LocalizedError
+import struct Foundation.Data
+
+/// A sequence that parses arbitrary byte chunks into lines using the JSON Sequence format.
+public struct JSONSequenceDeserializationSequence<Upstream: AsyncSequence & Sendable>: Sendable
+where Upstream.Element == ArraySlice<UInt8> {
+
+ /// The upstream sequence.
+ private let upstream: Upstream
+
+ /// Creates a new sequence.
+ /// - Parameter upstream: The upstream sequence of arbitrary byte chunks.
+ public init(upstream: Upstream) { self.upstream = upstream }
+}
+
+extension JSONSequenceDeserializationSequence: AsyncSequence {
+
+ /// The type of element produced by this asynchronous sequence.
+ public typealias Element = ArraySlice<UInt8>
+
+ /// An error thrown by the deserializer.
+ struct DeserializerError<UpstreamIterator: AsyncIteratorProtocol>: Swift.Error, CustomStringConvertible,
+ LocalizedError
+ where UpstreamIterator.Element == Element {
+
+ /// The underlying error emitted by the state machine.
+ let error: Iterator<UpstreamIterator>.StateMachine.ActionError
+
+ var description: String {
+ switch error {
+ case .missingInitialRS: return "Missing an initial <RS> character, the bytes might not be a JSON Sequence."
+ }
+ }
+
+ var errorDescription: String? { description }
+ }
+
+ /// The iterator of `JSONSequenceDeserializationSequence`.
+ public struct Iterator<UpstreamIterator: AsyncIteratorProtocol>: AsyncIteratorProtocol
+ where UpstreamIterator.Element == Element {
+
+ /// The upstream iterator of arbitrary byte chunks.
+ var upstream: UpstreamIterator
+
+ /// The state machine of the iterator.
+ var stateMachine: StateMachine = .init()
+
+ /// Asynchronously advances to the next element and returns it, or ends the
+ /// sequence if there is no next element.
+ public mutating func next() async throws -> ArraySlice<UInt8>? {
+ while true {
+ switch stateMachine.next() {
+ case .returnNil: return nil
+ case .emitLine(let line): return line
+ case .needsMore:
+ let value = try await upstream.next()
+ switch stateMachine.receivedValue(value) {
+ case .returnNil: return nil
+ case .emitLine(let line): return line
+ case .noop: continue
+ }
+ case .emitError(let error): throw DeserializerError(error: error)
+ case .noop: continue
+ }
+ }
+ }
+ }
+
+ /// Creates the asynchronous iterator that produces elements of this
+ /// asynchronous sequence.
+ public func makeAsyncIterator() -> Iterator<Upstream.AsyncIterator> {
+ Iterator(upstream: upstream.makeAsyncIterator())
+ }
+}
+
+extension AsyncSequence where Element == ArraySlice<UInt8> {
+
+ /// Returns another sequence that decodes each JSON Sequence event as the provided type using the provided decoder.
+ /// - Parameters:
+ /// - eventType: The type to decode the JSON event into.
+ /// - decoder: The JSON decoder to use.
+ /// - Returns: A sequence that provides the decoded JSON events.
+ public func asDecodedJSONSequence<Event: Decodable>(
+ of eventType: Event.Type = Event.self,
+ decoder: JSONDecoder = .init()
+ ) -> AsyncThrowingMapSequence<JSONSequenceDeserializationSequence<Self>, Event> {
+ JSONSequenceDeserializationSequence(upstream: self)
+ .map { line in try decoder.decode(Event.self, from: Data(line)) }
+ }
+}
+
+extension JSONSequenceDeserializationSequence.Iterator {
+
+ /// A state machine representing the JSON Lines deserializer.
+ struct StateMachine {
+
+ /// The possible states of the state machine.
+ enum State: Hashable {
+
+ /// Has not yet fully parsed the initial boundary.
+ case initial(buffer: [UInt8])
+
+ /// Is parsing a line, waiting for the end newline.
+ case parsingLine(buffer: [UInt8])
+
+ /// Finished, the terminal state.
+ case finished
+
+ /// Helper state to avoid copy-on-write copies.
+ case mutating
+ }
+
+ /// The current state of the state machine.
+ private(set) var state: State
+
+ /// Creates a new state machine.
+ init() { self.state = .initial(buffer: []) }
+
+ /// An error returned by the state machine.
+ enum ActionError {
+
+ /// The initial boundary `<RS>` was not found.
+ case missingInitialRS
+ }
+
+ /// An action returned by the `next` method.
+ enum NextAction {
+
+ /// Return nil to the caller, no more bytes.
+ case returnNil
+
+ /// Emit a full line.
+ case emitLine(ArraySlice<UInt8>)
+
+ /// Emit an error.
+ case emitError(ActionError)
+
+ /// The line is not complete yet, needs more bytes.
+ case needsMore
+
+ /// Rerun the parsing loop.
+ case noop
+ }
+
+ /// Read the next line parsed from upstream bytes.
+ /// - Returns: An action to perform.
+ mutating func next() -> NextAction {
+ switch state {
+ case .initial(var buffer):
+ guard !buffer.isEmpty else { return .needsMore }
+ guard buffer.first! == ASCII.rs else { return .emitError(.missingInitialRS) }
+ state = .mutating
+ buffer.removeFirst()
+ state = .parsingLine(buffer: buffer)
+ return .noop
+ case .parsingLine(var buffer):
+ state = .mutating
+ guard let indexOfRecordSeparator = buffer.firstIndex(of: ASCII.rs) else {
+ state = .parsingLine(buffer: buffer)
+ return .needsMore
+ } | Not a blocker, but I'm wondering if we can do better here with respect to performance. Specifically, this will call `firstIndex(of:)` every time we receive new bytes to find the record separator, which will be O(n) in the current size of the buffer and will search for the record separator through portions of the buffer that may have been searched last time.
A pathological example would be a sequence of one-byte chunks, in which case it will be quadratic in the size of the line, but it needn't be.
It can be linear if we:
1. Augment the `.parsingLine(buffer:)` state to store the current `endIndex` of the buffer before returning `.needsMore` or something similar.
2. Use this with a new utility function `firstIndex(of:from:)`, which would look for the first index from a starting index.
This comment might apply to the other sequences in this PR too.
|
swift-openapi-runtime | github_2023 | others | 91 | apple | simonjbeaumont | @@ -0,0 +1,451 @@
+//===----------------------------------------------------------------------===//
+//
+// This source file is part of the SwiftOpenAPIGenerator open source project
+//
+// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors
+// Licensed under Apache License v2.0
+//
+// See LICENSE.txt for license information
+// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors
+//
+// SPDX-License-Identifier: Apache-2.0
+//
+//===----------------------------------------------------------------------===//
+
+#if canImport(Darwin)
+import class Foundation.JSONDecoder
+#else
+@preconcurrency import class Foundation.JSONDecoder
+#endif
+import struct Foundation.Data
+
+/// A sequence that parses arbitrary byte chunks into events using the Server-sent Events format.
+///
+/// https://html.spec.whatwg.org/multipage/server-sent-events.html#server-sent-events
+public struct ServerSentEventsDeserializationSequence<Upstream: AsyncSequence & Sendable>: Sendable
+where Upstream.Element == ArraySlice<UInt8> {
+
+ /// The upstream sequence.
+ private let upstream: Upstream
+
+ /// Creates a new sequence.
+ /// - Parameter upstream: The upstream sequence of arbitrary byte chunks.
+ public init(upstream: Upstream) { self.upstream = upstream }
+}
+
+extension ServerSentEventsDeserializationSequence: AsyncSequence {
+
+ /// The type of element produced by this asynchronous sequence.
+ public typealias Element = ServerSentEvent
+
+ /// The iterator of `ServerSentEventsDeserializationSequence`.
+ public struct Iterator<UpstreamIterator: AsyncIteratorProtocol>: AsyncIteratorProtocol
+ where UpstreamIterator.Element == ArraySlice<UInt8> {
+
+ /// The upstream iterator of arbitrary byte chunks.
+ var upstream: UpstreamIterator
+
+ /// The state machine of the iterator.
+ var stateMachine: StateMachine = .init()
+
+ /// Asynchronously advances to the next element and returns it, or ends the
+ /// sequence if there is no next element.
+ public mutating func next() async throws -> ServerSentEvent? {
+ while true {
+ switch stateMachine.next() {
+ case .returnNil: return nil
+ case .emitEvent(let event): return event
+ case .noop: continue
+ case .needsMore:
+ let value = try await upstream.next()
+ switch stateMachine.receivedValue(value) {
+ case .returnNil: return nil
+ case .noop: continue
+ }
+ }
+ }
+ }
+ }
+
+ /// Creates the asynchronous iterator that produces elements of this
+ /// asynchronous sequence.
+ public func makeAsyncIterator() -> Iterator<Upstream.AsyncIterator> {
+ Iterator(upstream: upstream.makeAsyncIterator())
+ }
+}
+
+extension AsyncSequence where Element == ArraySlice<UInt8>, Self: Sendable {
+
+ /// Returns another sequence that decodes each event's data as the provided type using the provided decoder.
+ ///
+ /// Use this method if the event's `data` field is not JSON, or if you don't want to parse it using `asDecodedServerSentEventsWithJSONData`.
+ /// - Returns: A sequence that provides the events.
+ public func asDecodedServerSentEvents() -> ServerSentEventsDeserializationSequence<
+ ServerSentEventsLineDeserializationSequence<Self>
+ > { .init(upstream: ServerSentEventsLineDeserializationSequence(upstream: self)) }
+
+ /// Returns another sequence that decodes each event's data as the provided type using the provided decoder.
+ ///
+ /// Use this method if the event's `data` field is JSON.
+ /// - Parameters:
+ /// - dataType: The type to decode the JSON data into.
+ /// - decoder: The JSON decoder to use.
+ /// - Returns: A sequence that provides the events with the decoded JSON data.
+ public func asDecodedServerSentEventsWithJSONData<JSONDataType: Decodable>(
+ of dataType: JSONDataType.Type = JSONDataType.self,
+ decoder: JSONDecoder = .init()
+ ) -> AsyncThrowingMapSequence<
+ ServerSentEventsDeserializationSequence<ServerSentEventsLineDeserializationSequence<Self>>,
+ ServerSentEventWithJSONData<JSONDataType>
+ > {
+ asDecodedServerSentEvents()
+ .map { event in
+ ServerSentEventWithJSONData(
+ event: event.event,
+ data: try event.data.flatMap { stringData in
+ try decoder.decode(JSONDataType.self, from: Data(stringData.utf8))
+ },
+ id: event.id,
+ retry: event.retry
+ )
+ }
+ }
+}
+
+extension ServerSentEventsDeserializationSequence.Iterator {
+
+ /// A state machine representing the Server-sent Events deserializer.
+ struct StateMachine {
+
+ /// The possible states of the state machine.
+ enum State: Hashable {
+
+ /// Accumulating an event, which hasn't been emitted yet.
+ case accumulatingEvent(ServerSentEvent, buffer: [ArraySlice<UInt8>])
+
+ /// Finished, the terminal state.
+ case finished
+
+ /// Helper state to avoid copy-on-write copies.
+ case mutating
+ }
+
+ /// The current state of the state machine.
+ private(set) var state: State
+
+ /// Creates a new state machine.
+ init() { self.state = .accumulatingEvent(.init(), buffer: []) }
+
+ /// An action returned by the `next` method.
+ enum NextAction {
+
+ /// Return nil to the caller, no more bytes.
+ case returnNil
+
+ /// Emit a completed event.
+ case emitEvent(ServerSentEvent)
+
+ /// The line is not complete yet, needs more bytes.
+ case needsMore
+
+ /// Rerun the parsing loop.
+ case noop
+ }
+
+ /// Read the next line parsed from upstream bytes.
+ /// - Returns: An action to perform.
+ mutating func next() -> NextAction {
+ switch state {
+ case .accumulatingEvent(var event, var buffer):
+ guard let line = buffer.first else { return .needsMore }
+ state = .mutating
+ buffer.removeFirst()
+ if line.isEmpty {
+ // Dispatch the accumulated event.
+ state = .accumulatingEvent(.init(), buffer: buffer)
+ // If the last character of data is a newline, strip it.
+ if event.data?.hasSuffix("\n") ?? false { event.data?.removeLast() }
+ return .emitEvent(event)
+ }
+ if line.first! == ASCII.colon {
+ // A comment, skip this line.
+ state = .accumulatingEvent(event, buffer: buffer)
+ return .noop
+ }
+ // Parse the field name and value.
+ let field: String
+ let value: String?
+ if let indexOfFirstColon = line.firstIndex(of: ASCII.colon) {
+ field = String(decoding: line[..<indexOfFirstColon], as: UTF8.self)
+ let valueBytes = line[line.index(after: indexOfFirstColon)...]
+ let resolvedValueBytes: ArraySlice<UInt8>
+ if valueBytes.isEmpty {
+ resolvedValueBytes = []
+ } else if valueBytes.first! == ASCII.space {
+ resolvedValueBytes = valueBytes.dropFirst()
+ } else {
+ resolvedValueBytes = valueBytes
+ }
+ value = String(decoding: resolvedValueBytes, as: UTF8.self)
+ } else {
+ field = String(decoding: line, as: UTF8.self)
+ value = nil
+ }
+ guard let value else {
+ // An unknown type of event, skip.
+ state = .accumulatingEvent(event, buffer: buffer)
+ return .noop
+ }
+ // Process the field.
+ switch field {
+ case "event": event.event = value
+ case "data":
+ var data = event.data ?? ""
+ data.append(value)
+ data.append("\n")
+ event.data = data
+ case "id": event.id = value | Spec says:
> If the field value does not contain U+0000 NULL, then set the last event ID buffer to the field value. Otherwise, ignore the field.
Are we relying on earlier logic / string parsing for this? |
swift-openapi-runtime | github_2023 | others | 91 | apple | simonjbeaumont | @@ -0,0 +1,451 @@
+//===----------------------------------------------------------------------===//
+//
+// This source file is part of the SwiftOpenAPIGenerator open source project
+//
+// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors
+// Licensed under Apache License v2.0
+//
+// See LICENSE.txt for license information
+// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors
+//
+// SPDX-License-Identifier: Apache-2.0
+//
+//===----------------------------------------------------------------------===//
+
+#if canImport(Darwin)
+import class Foundation.JSONDecoder
+#else
+@preconcurrency import class Foundation.JSONDecoder
+#endif
+import struct Foundation.Data
+
+/// A sequence that parses arbitrary byte chunks into events using the Server-sent Events format.
+///
+/// https://html.spec.whatwg.org/multipage/server-sent-events.html#server-sent-events
+public struct ServerSentEventsDeserializationSequence<Upstream: AsyncSequence & Sendable>: Sendable
+where Upstream.Element == ArraySlice<UInt8> {
+
+ /// The upstream sequence.
+ private let upstream: Upstream
+
+ /// Creates a new sequence.
+ /// - Parameter upstream: The upstream sequence of arbitrary byte chunks.
+ public init(upstream: Upstream) { self.upstream = upstream }
+}
+
+extension ServerSentEventsDeserializationSequence: AsyncSequence {
+
+ /// The type of element produced by this asynchronous sequence.
+ public typealias Element = ServerSentEvent
+
+ /// The iterator of `ServerSentEventsDeserializationSequence`.
+ public struct Iterator<UpstreamIterator: AsyncIteratorProtocol>: AsyncIteratorProtocol
+ where UpstreamIterator.Element == ArraySlice<UInt8> {
+
+ /// The upstream iterator of arbitrary byte chunks.
+ var upstream: UpstreamIterator
+
+ /// The state machine of the iterator.
+ var stateMachine: StateMachine = .init()
+
+ /// Asynchronously advances to the next element and returns it, or ends the
+ /// sequence if there is no next element.
+ public mutating func next() async throws -> ServerSentEvent? {
+ while true {
+ switch stateMachine.next() {
+ case .returnNil: return nil
+ case .emitEvent(let event): return event
+ case .noop: continue
+ case .needsMore:
+ let value = try await upstream.next()
+ switch stateMachine.receivedValue(value) {
+ case .returnNil: return nil
+ case .noop: continue
+ }
+ }
+ }
+ }
+ }
+
+ /// Creates the asynchronous iterator that produces elements of this
+ /// asynchronous sequence.
+ public func makeAsyncIterator() -> Iterator<Upstream.AsyncIterator> {
+ Iterator(upstream: upstream.makeAsyncIterator())
+ }
+}
+
+extension AsyncSequence where Element == ArraySlice<UInt8>, Self: Sendable {
+
+ /// Returns another sequence that decodes each event's data as the provided type using the provided decoder.
+ ///
+ /// Use this method if the event's `data` field is not JSON, or if you don't want to parse it using `asDecodedServerSentEventsWithJSONData`.
+ /// - Returns: A sequence that provides the events.
+ public func asDecodedServerSentEvents() -> ServerSentEventsDeserializationSequence<
+ ServerSentEventsLineDeserializationSequence<Self>
+ > { .init(upstream: ServerSentEventsLineDeserializationSequence(upstream: self)) }
+
+ /// Returns another sequence that decodes each event's data as the provided type using the provided decoder.
+ ///
+ /// Use this method if the event's `data` field is JSON.
+ /// - Parameters:
+ /// - dataType: The type to decode the JSON data into.
+ /// - decoder: The JSON decoder to use.
+ /// - Returns: A sequence that provides the events with the decoded JSON data.
+ public func asDecodedServerSentEventsWithJSONData<JSONDataType: Decodable>(
+ of dataType: JSONDataType.Type = JSONDataType.self,
+ decoder: JSONDecoder = .init()
+ ) -> AsyncThrowingMapSequence<
+ ServerSentEventsDeserializationSequence<ServerSentEventsLineDeserializationSequence<Self>>,
+ ServerSentEventWithJSONData<JSONDataType>
+ > {
+ asDecodedServerSentEvents()
+ .map { event in
+ ServerSentEventWithJSONData(
+ event: event.event,
+ data: try event.data.flatMap { stringData in
+ try decoder.decode(JSONDataType.self, from: Data(stringData.utf8))
+ },
+ id: event.id,
+ retry: event.retry
+ )
+ }
+ }
+}
+
+extension ServerSentEventsDeserializationSequence.Iterator {
+
+ /// A state machine representing the Server-sent Events deserializer.
+ struct StateMachine {
+
+ /// The possible states of the state machine.
+ enum State: Hashable {
+
+ /// Accumulating an event, which hasn't been emitted yet.
+ case accumulatingEvent(ServerSentEvent, buffer: [ArraySlice<UInt8>])
+
+ /// Finished, the terminal state.
+ case finished
+
+ /// Helper state to avoid copy-on-write copies.
+ case mutating
+ }
+
+ /// The current state of the state machine.
+ private(set) var state: State
+
+ /// Creates a new state machine.
+ init() { self.state = .accumulatingEvent(.init(), buffer: []) }
+
+ /// An action returned by the `next` method.
+ enum NextAction {
+
+ /// Return nil to the caller, no more bytes.
+ case returnNil
+
+ /// Emit a completed event.
+ case emitEvent(ServerSentEvent)
+
+ /// The line is not complete yet, needs more bytes.
+ case needsMore
+
+ /// Rerun the parsing loop.
+ case noop
+ }
+
+ /// Read the next line parsed from upstream bytes.
+ /// - Returns: An action to perform.
+ mutating func next() -> NextAction {
+ switch state {
+ case .accumulatingEvent(var event, var buffer):
+ guard let line = buffer.first else { return .needsMore }
+ state = .mutating
+ buffer.removeFirst()
+ if line.isEmpty {
+ // Dispatch the accumulated event.
+ state = .accumulatingEvent(.init(), buffer: buffer)
+ // If the last character of data is a newline, strip it.
+ if event.data?.hasSuffix("\n") ?? false { event.data?.removeLast() }
+ return .emitEvent(event)
+ }
+ if line.first! == ASCII.colon {
+ // A comment, skip this line.
+ state = .accumulatingEvent(event, buffer: buffer)
+ return .noop
+ }
+ // Parse the field name and value.
+ let field: String
+ let value: String?
+ if let indexOfFirstColon = line.firstIndex(of: ASCII.colon) {
+ field = String(decoding: line[..<indexOfFirstColon], as: UTF8.self)
+ let valueBytes = line[line.index(after: indexOfFirstColon)...]
+ let resolvedValueBytes: ArraySlice<UInt8>
+ if valueBytes.isEmpty {
+ resolvedValueBytes = []
+ } else if valueBytes.first! == ASCII.space {
+ resolvedValueBytes = valueBytes.dropFirst()
+ } else {
+ resolvedValueBytes = valueBytes
+ }
+ value = String(decoding: resolvedValueBytes, as: UTF8.self)
+ } else {
+ field = String(decoding: line, as: UTF8.self)
+ value = nil
+ }
+ guard let value else {
+ // An unknown type of event, skip.
+ state = .accumulatingEvent(event, buffer: buffer)
+ return .noop
+ }
+ // Process the field.
+ switch field {
+ case "event": event.event = value
+ case "data":
+ var data = event.data ?? ""
+ data.append(value)
+ data.append("\n")
+ event.data = data
+ case "id": event.id = value
+ case "retry":
+ if let retry = Int64(value) {
+ event.retry = retry
+ } else {
+ // Skip this line.
+ fallthrough
+ }
+ default:
+ // An unknown or invalid field, skip.
+ state = .accumulatingEvent(event, buffer: buffer)
+ return .noop
+ }
+ // Processed the field, continue.
+ state = .accumulatingEvent(event, buffer: buffer)
+ return .noop
+ case .finished: return .returnNil
+ case .mutating: preconditionFailure("Invalid state")
+ }
+ }
+
+ /// An action returned by the `receivedValue` method.
+ enum ReceivedValueAction {
+
+ /// Return nil to the caller, no more lines.
+ case returnNil
+
+ /// No action, rerun the parsing loop.
+ case noop
+ }
+
+ /// Ingest the provided bytes.
+ /// - Parameter value: A new byte chunk. If `nil`, then the source of bytes is finished.
+ /// - Returns: An action to perform.
+ mutating func receivedValue(_ value: ArraySlice<UInt8>?) -> ReceivedValueAction {
+ switch state {
+ case .accumulatingEvent(let event, var buffer):
+ if let value {
+ state = .mutating
+ buffer.append(value)
+ state = .accumulatingEvent(event, buffer: buffer)
+ return .noop
+ } else {
+ // If no value is received, drop the existing event on the floor.
+ // The specification explicitly states this.
+ // > Once the end of the file is reached, any pending data must be discarded.
+ // > (If the file ends in the middle of an event, before the final empty line,
+ // > the incomplete event is not dispatched.)
+ // Source: https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation
+ state = .finished
+ return .returnNil
+ }
+ case .finished, .mutating: preconditionFailure("Invalid state")
+ }
+ }
+ }
+}
+
+/// A sequence that parses arbitrary byte chunks into lines using the Server-sent Events format.
+public struct ServerSentEventsLineDeserializationSequence<Upstream: AsyncSequence & Sendable>: Sendable
+where Upstream.Element == ArraySlice<UInt8> {
+
+ /// The upstream sequence.
+ private let upstream: Upstream
+
+ /// Creates a new sequence.
+ /// - Parameter upstream: The upstream sequence of arbitrary byte chunks.
+ public init(upstream: Upstream) { self.upstream = upstream }
+}
+
+extension ServerSentEventsLineDeserializationSequence: AsyncSequence {
+
+ /// The type of element produced by this asynchronous sequence.
+ public typealias Element = ArraySlice<UInt8>
+
+ /// The iterator of `ServerSentEventsLineDeserializationSequence`.
+ public struct Iterator<UpstreamIterator: AsyncIteratorProtocol>: AsyncIteratorProtocol
+ where UpstreamIterator.Element == Element {
+
+ /// The upstream iterator of arbitrary byte chunks.
+ var upstream: UpstreamIterator
+
+ /// The state machine of the iterator.
+ var stateMachine: StateMachine = .init()
+
+ /// Asynchronously advances to the next element and returns it, or ends the
+ /// sequence if there is no next element.
+ public mutating func next() async throws -> ArraySlice<UInt8>? {
+ while true {
+ switch stateMachine.next() {
+ case .returnNil: return nil
+ case .emitLine(let line): return line
+ case .noop: continue
+ case .needsMore:
+ let value = try await upstream.next()
+ switch stateMachine.receivedValue(value) {
+ case .returnNil: return nil
+ case .emitLine(let line): return line
+ case .noop: continue
+ }
+ }
+ }
+ }
+ }
+
+ /// Creates the asynchronous iterator that produces elements of this
+ /// asynchronous sequence.
+ public func makeAsyncIterator() -> Iterator<Upstream.AsyncIterator> {
+ Iterator(upstream: upstream.makeAsyncIterator())
+ }
+}
+
+extension ServerSentEventsLineDeserializationSequence.Iterator {
+
+ /// A state machine for parsing lines in Server-Sent Events.
+ ///
+ /// https://html.spec.whatwg.org/multipage/server-sent-events.html#parsing-an-event-stream
+ ///
+ /// This is not trivial to do with a streaming parser, as the end of line can be:
+ /// - LF
+ /// - CR
+ /// - CRLF
+ ///
+ /// So when we get CR, but have no more data, we want to be able to emit the previous line,
+ /// however we need to discard a LF if one comes. | I think that we might be over reaching here and we can simplify even if it means delays. I.e. we can wait for the LF before emitting. It's covered explicitly by the spec:
> Since connections established to remote servers for such resources are expected to be long-lived, UAs should ensure that appropriate buffering is used. In particular, while line buffering with lines are defined to end with a single U+000A LINE FEED (LF) character is safe, block buffering or line buffering with different expected line endings can cause delays in event dispatch.
I read this as: if we can simplify here, we should. It's on the user to use good line endings. |
swift-openapi-runtime | github_2023 | others | 90 | apple | simonjbeaumont | @@ -15,3 +15,10 @@ import Foundation
import HTTPTypes
// MARK: - Functionality to be removed in the future
+
+extension UndocumentedPayload {
+ /// Creates a new payload.
+ @available(*, deprecated, renamed: "init(headerFields:body:)") @_disfavoredOverload public init() {
+ self.init(headerFields: [:], body: nil)
+ }
+} | Do we need to carry this forever now?
Why do we need it, given the new `init(headerFields:body:)` has default parameters?
Can't we do this differently by having the new `init(headerFields:body:)` _not_ have default parameters and just change the implementation of `init()` to call it with the defaults, given that we already have `init()` in the API?
Or, isn't it just enough to have `_disfavoredOverload` on the old `init()`?
All these questions are really just: can we avoid having a deprecated symbol here?
|
swift-openapi-runtime | github_2023 | others | 88 | apple | simonjbeaumont | @@ -68,15 +68,29 @@ Please report any issues related to this library in the [swift-openapi-generator
- ``Configuration``
- ``DateTranscoder``
- ``ISO8601DateTranscoder``
+- ``MultipartBoundaryGenerator``
+- ``RandomMultipartBoundaryGenerator``
+- ``ConstantMultipartBoundaryGenerator``
+- ``IterationBehavior``
+
+### Content types
+- ``HTTPBody``
+- ``Base64EncodedData``
+- ``MultipartBody``
+- ``MultipartRawPart``
+- ``MultipartPart``
+- ``MultipartDynamicallyNamedPart``
### Errors
- ``ClientError``
- ``ServerError``
- ``UndocumentedPayload``
### HTTP Currency Types
-- ``HTTPBody`` | IMO I'd keep HTTPBody here. |
swift-openapi-runtime | github_2023 | others | 77 | apple | simonjbeaumont | @@ -122,24 +122,16 @@ public final class HTTPBody: @unchecked Sendable {
public typealias ByteChunk = ArraySlice<UInt8>
/// Describes how many times the provided sequence can be iterated.
- public enum IterationBehavior: Sendable {
-
- /// The input sequence can only be iterated once.
- ///
- /// If a retry or a redirect is encountered, fail the call with
- /// a descriptive error.
- case single
-
- /// The input sequence can be iterated multiple times.
- ///
- /// Supports retries and redirects, as a new iterator is created each
- /// time.
- case multiple
- }
-
- /// The body's iteration behavior, which controls how many times
+ @available(
+ *,
+ deprecated,
+ renamed: "IterationBehavior",
+ message: "Use the top level IterationBehavior directly instead of HTTPBody.IterationBehavior."
+ ) public typealias IterationBehavior = OpenAPIRuntime.IterationBehavior | Can we move this to Deprecated.swift so it doesn't get missed in the 1.0.0 sweep? |
swift-openapi-runtime | github_2023 | others | 77 | apple | simonjbeaumont | @@ -0,0 +1,75 @@
+//===----------------------------------------------------------------------===//
+//
+// This source file is part of the SwiftOpenAPIGenerator open source project
+//
+// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors
+// Licensed under Apache License v2.0
+//
+// See LICENSE.txt for license information
+// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors
+//
+// SPDX-License-Identifier: Apache-2.0
+//
+//===----------------------------------------------------------------------===//
+
+/// A generator of a new boundary string used by multipart messages to separate parts.
+public protocol MultipartBoundaryGenerator: Sendable {
+
+ /// Generates a boundary string for a multipart message.
+ /// - Returns: A boundary string.
+ func makeBoundary() -> String
+}
+
+extension MultipartBoundaryGenerator where Self == ConstantMultipartBoundaryGenerator {
+
+ /// A generator that always returns the same boundary string.
+ public static var constant: Self { ConstantMultipartBoundaryGenerator() }
+}
+
+extension MultipartBoundaryGenerator where Self == RandomMultipartBoundaryGenerator {
+
+ /// A generator that produces a random boundary every time.
+ public static var random: Self { RandomMultipartBoundaryGenerator() }
+}
+
+/// A generator that always returns the same constant boundary string.
+public struct ConstantMultipartBoundaryGenerator: MultipartBoundaryGenerator {
+
+ /// The boundary string to return.
+ public let boundary: String
+ /// Creates a new generator.
+ /// - Parameter boundary: The boundary string to return every time.
+ public init(boundary: String = "__X_SWIFT_OPENAPI_GENERATOR_BOUNDARY__") { self.boundary = boundary }
+
+ /// Generates a boundary string for a multipart message.
+ /// - Returns: A boundary string.
+ public func makeBoundary() -> String { boundary }
+}
+
+/// A generator that returns a boundary containg a constant prefix and a random suffix.
+public struct RandomMultipartBoundaryGenerator: MultipartBoundaryGenerator {
+
+ /// The constant prefix of each boundary.
+ public let boundaryPrefix: String
+ /// The length, in bytes, of the random boundary suffix.
+ public let randomNumberSuffixLenght: Int
+
+ /// The options for the random bytes suffix.
+ private let values: [UInt8] = Array("0123456789".utf8)
+
+ /// Create a new generator.
+ /// - Parameters:
+ /// - boundaryPrefix: The constant prefix of each boundary.
+ /// - randomNumberSuffixLenght: The length, in bytes, of the random boundary suffix.
+ public init(boundaryPrefix: String = "__X_SWIFT_OPENAPI_", randomNumberSuffixLenght: Int = 20) {
+ self.boundaryPrefix = boundaryPrefix
+ self.randomNumberSuffixLenght = randomNumberSuffixLenght
+ }
+ /// Generates a boundary string for a multipart message.
+ /// - Returns: A boundary string.
+ public func makeBoundary() -> String {
+ var randomSuffix = [UInt8](repeating: 0, count: randomNumberSuffixLenght)
+ for i in randomSuffix.startIndex..<randomSuffix.endIndex { randomSuffix[i] = values.randomElement()! }
+ return boundaryPrefix.appending(String(decoding: randomSuffix, as: UTF8.self))
+ }
+} | Some typos.
```suggestion
/// The length, in bytes, of the random boundary suffix.
public let randomNumberSuffixLength: Int
/// The options for the random bytes suffix.
private let values: [UInt8] = Array("0123456789".utf8)
/// Create a new generator.
/// - Parameters:
/// - boundaryPrefix: The constant prefix of each boundary.
/// - randomNumberSuffixLength: The length, in bytes, of the random boundary suffix.
public init(boundaryPrefix: String = "__X_SWIFT_OPENAPI_", randomNumberSuffixLenght: Int = 20) {
self.boundaryPrefix = boundaryPrefix
self.randomNumberSuffixLength = randomNumberSuffixLength
}
/// Generates a boundary string for a multipart message.
/// - Returns: A boundary string.
public func makeBoundary() -> String {
var randomSuffix = [UInt8](repeating: 0, count: randomNumberSuffixLength)
for i in randomSuffix.startIndex..<randomSuffix.endIndex { randomSuffix[i] = values.randomElement()! }
return boundaryPrefix.appending(String(decoding: randomSuffix, as: UTF8.self))
}
}
``` |
swift-openapi-runtime | github_2023 | others | 77 | apple | simonjbeaumont | @@ -0,0 +1,36 @@
+//===----------------------------------------------------------------------===//
+//
+// This source file is part of the SwiftOpenAPIGenerator open source project
+//
+// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors
+// Licensed under Apache License v2.0
+//
+// See LICENSE.txt for license information
+// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors
+//
+// SPDX-License-Identifier: Apache-2.0
+//
+//===----------------------------------------------------------------------===//
+import XCTest
+@_spi(Generated) @testable import OpenAPIRuntime
+import Foundation
+
+final class Test_MultipartBoundaryGenerator: Test_Runtime {
+
+ func testConstant() throws {
+ let generator = ConstantMultipartBoundaryGenerator(boundary: "__abcd__")
+ let firstBoundary = generator.makeBoundary()
+ let secondBoundary = generator.makeBoundary()
+ XCTAssertEqual(firstBoundary, "__abcd__")
+ XCTAssertEqual(secondBoundary, "__abcd__")
+ }
+
+ func testRandom() throws {
+ let generator = RandomMultipartBoundaryGenerator(boundaryPrefix: "__abcd__", randomNumberSuffixLenght: 8) | ```suggestion
let generator = RandomMultipartBoundaryGenerator(boundaryPrefix: "__abcd__", randomNumberSuffixLength: 8)
``` |
swift-openapi-runtime | github_2023 | others | 71 | apple | czechboy0 | @@ -56,7 +56,13 @@ public struct Base64EncodedData: Sendable, Hashable {
/// Initializes an instance of ``Base64EncodedData`` wrapping the provided slice of bytes.
/// - Parameter data: The underlying bytes to wrap.
+ @available(*, deprecated, renamed: "init", message: "Use the init(_ data: ArraySlice<UInt8>) instead.")
+ | ```suggestion
@available(*, deprecated, renamed: "init(_:)")
``` |
swift-openapi-runtime | github_2023 | others | 71 | apple | czechboy0 | @@ -56,7 +56,13 @@ public struct Base64EncodedData: Sendable, Hashable {
/// Initializes an instance of ``Base64EncodedData`` wrapping the provided slice of bytes.
/// - Parameter data: The underlying bytes to wrap.
+ @available(*, deprecated, renamed: "init", message: "Use the init(_ data: ArraySlice<UInt8>) instead.")
+
public init(data: ArraySlice<UInt8>) { self.data = data }
+
+ /// Initializes an instance of ``Base64EncodedData`` wrapping the provided slice of bytes.
+ /// - Parameter data: The underlying bytes to wrap.
+ public init(_ data: ArraySlice<UInt8>) { self.data = data } | ```suggestion
public init(_ data: ArraySlice<UInt8>) { self.data = data }
/// Initializes an instance of ``Base64EncodedData`` wrapping the provided sequence of bytes.
/// - Parameter data: The underlying bytes to wrap.
public init(_ data: some Sequence<UInt8>) { self.init(ArraySlice(data)) }
```
With this, adopters can easily also pass `[UInt8]`, `ByteBuffer.readableBytesView`, and `Data` itself – without an explicit wrapping in `ArraySlice`. |
swift-openapi-runtime | github_2023 | others | 71 | apple | czechboy0 | @@ -74,7 +80,7 @@ extension Base64EncodedData: Codable {
guard let data = Data(base64Encoded: base64EncodedString, options: options) else {
throw RuntimeError.invalidBase64String(base64EncodedString)
}
- self.init(data: ArraySlice(data))
+ self.init(ArraySlice(data)) | With the change above, this should work by passing `Data` directly.
```suggestion
self.init(data)
``` |
swift-openapi-runtime | github_2023 | others | 71 | apple | czechboy0 | @@ -241,14 +241,14 @@ final class Test_OpenAPIValue: Test_Runtime {
}
func testEncoding_base64_success() throws {
- let encodedData = Base64EncodedData(data: ArraySlice(testStructData))
+ let encodedData = Base64EncodedData(ArraySlice(testStructData)) | ```suggestion
let encodedData = Base64EncodedData(testStructData)
``` |
swift-openapi-runtime | github_2023 | others | 71 | apple | czechboy0 | @@ -241,14 +241,14 @@ final class Test_OpenAPIValue: Test_Runtime {
}
func testEncoding_base64_success() throws {
- let encodedData = Base64EncodedData(data: ArraySlice(testStructData))
+ let encodedData = Base64EncodedData(ArraySlice(testStructData))
let JSONEncoded = try JSONEncoder().encode(encodedData)
XCTAssertEqual(String(data: JSONEncoded, encoding: .utf8)!, testStructBase64EncodedString)
}
func testDecoding_base64_success() throws {
- let encodedData = Base64EncodedData(data: ArraySlice(testStructData))
+ let encodedData = Base64EncodedData(ArraySlice(testStructData)) | ```suggestion
let encodedData = Base64EncodedData(testStructData)
``` |
swift-openapi-runtime | github_2023 | others | 71 | apple | czechboy0 | @@ -257,7 +257,7 @@ final class Test_OpenAPIValue: Test_Runtime {
}
func testEncodingDecodingRoundtrip_base64_success() throws {
- let encodedData = Base64EncodedData(data: ArraySlice(testStructData))
+ let encodedData = Base64EncodedData(ArraySlice(testStructData)) | ```suggestion
let encodedData = Base64EncodedData(testStructData)
``` |
swift-openapi-runtime | github_2023 | others | 71 | apple | czechboy0 | @@ -56,7 +56,13 @@ public struct Base64EncodedData: Sendable, Hashable {
/// Initializes an instance of ``Base64EncodedData`` wrapping the provided slice of bytes.
/// - Parameter data: The underlying bytes to wrap.
+ @available(*, deprecated, renamed: "init", message: "Use the init(_ data: ArraySlice<UInt8>) instead.")
+
public init(data: ArraySlice<UInt8>) { self.data = data }
+
+ /// Initializes an instance of ``Base64EncodedData`` wrapping the provided slice of bytes.
+ /// - Parameter data: The underlying bytes to wrap.
+ public init(_ data: ArraySlice<UInt8>) { self.data = data }
}
| While we're at it, let's also add an array literal expressible conformances for byte arrays.
This means you can then do `let value: Base64EncodedData = [0xa, 0xd]`.
```suggestion
extension Base64EncodedData: ExpressibleByArrayLiteral {
init(arrayLiteral elements: UInt8...) {
self.init(elements)
}
}
``` |
swift-openapi-runtime | github_2023 | others | 71 | apple | czechboy0 | @@ -56,7 +56,23 @@ public struct Base64EncodedData: Sendable, Hashable {
/// Initializes an instance of ``Base64EncodedData`` wrapping the provided slice of bytes.
/// - Parameter data: The underlying bytes to wrap.
+ @available(*, deprecated, renamed: "init(_:)")
+ | ```suggestion
``` |
swift-openapi-runtime | github_2023 | others | 82 | apple | simonjbeaumont | @@ -19,7 +19,7 @@ Add the package dependency in your `Package.swift`:
```swift
.package(
url: "https://github.com/apple/swift-openapi-runtime",
- .upToNextMinor(from: "0.3.0")
+ exact: "1.0.0-alpha.1" | Um, not sure what this is, but looks like we got some non-printable thing in here. |
swift-openapi-runtime | github_2023 | others | 74 | apple | simonjbeaumont | @@ -0,0 +1,380 @@
+//===----------------------------------------------------------------------===//
+//
+// This source file is part of the SwiftOpenAPIGenerator open source project
+//
+// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors
+// Licensed under Apache License v2.0
+//
+// See LICENSE.txt for license information
+// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors
+//
+// SPDX-License-Identifier: Apache-2.0
+//
+//===----------------------------------------------------------------------===//
+
+import HTTPTypes
+import Foundation
+
+/// A sequence that parses raw multipart parts from multipart frames.
+struct MultipartFramesToRawPartsSequence<Upstream: AsyncSequence & Sendable>: Sendable
+where Upstream.Element == MultipartFrame {
+
+ /// The source of multipart frames.
+ var upstream: Upstream
+}
+
+extension MultipartFramesToRawPartsSequence: AsyncSequence {
+
+ /// The type of element produced by this asynchronous sequence.
+ typealias Element = MultipartRawPart
+
+ /// Creates the asynchronous iterator that produces elements of this
+ /// asynchronous sequence.
+ ///
+ /// - Returns: An instance of the `AsyncIterator` type used to produce
+ /// elements of the asynchronous sequence.
+ func makeAsyncIterator() -> Iterator { Iterator(makeUpstreamIterator: { upstream.makeAsyncIterator() }) }
+
+ /// An iterator that pulls frames from the upstream iterator and provides
+ /// raw multipart parts.
+ struct Iterator: AsyncIteratorProtocol {
+
+ /// The underlying shared iterator.
+ var shared: SharedIterator
+
+ /// The closure invoked to fetch the next byte chunk of the part's body.
+ var bodyClosure: @Sendable () async throws -> ArraySlice<UInt8>?
+
+ /// Creates a new iterator.
+ /// - Parameter makeUpstreamIterator: A closure that creates the upstream source of frames.
+ init(makeUpstreamIterator: @Sendable () -> Upstream.AsyncIterator) {
+ let shared = SharedIterator(makeUpstreamIterator: makeUpstreamIterator)
+ self.shared = shared
+ self.bodyClosure = { try await shared.nextFromBodySubsequence() }
+ }
+
+ /// Asynchronously advances to the next element and returns it, or ends the
+ /// sequence if there is no next element.
+ ///
+ /// - Returns: The next element, if it exists, or `nil` to signal the end of
+ /// the sequence.
+ mutating func next() async throws -> Element? {
+ try await shared.nextFromPartSequence(bodyClosure: bodyClosure)
+ }
+ }
+}
+
+extension HTTPBody {
+
+ /// Creates a new body from the provided header fields and body closure.
+ /// - Parameters:
+ /// - headerFields: The header fields to inspect for a `content-length` header.
+ /// - bodyClosure: A closure invoked to fetch the next byte chunk of the body.
+ fileprivate convenience init(
+ headerFields: HTTPFields,
+ bodyClosure: @escaping @Sendable () async throws -> ArraySlice<UInt8>?
+ ) {
+ let stream = AsyncThrowingStream(unfolding: bodyClosure)
+ let length: HTTPBody.Length
+ if let contentLengthString = headerFields[.contentLength], let contentLength = Int(contentLengthString) {
+ length = .known(contentLength)
+ } else {
+ length = .unknown
+ }
+ self.init(stream, length: length)
+ }
+}
+
+extension MultipartFramesToRawPartsSequence {
+
+ /// A state machine representing the frame to raw part parser.
+ struct StateMachine {
+
+ /// The possible states of the state machine.
+ enum State: Hashable {
+
+ /// Has not started parsing any parts yet.
+ case initial
+
+ /// Waiting to send header fields to start a new part.
+ ///
+ /// Associated value is optional headers.
+ /// If they're non-nil, they arrived already, so just send them right away.
+ /// If they're nil, you need to fetch the next frame to get them.
+ case waitingToSendHeaders(HTTPFields?)
+
+ /// In the process of streaming the byte chunks of a part body.
+ case streamingBody
+
+ /// Finished, the terminal state.
+ case finished
+ }
+
+ /// The current state of the state machine.
+ private(set) var state: State
+
+ /// Creates a new state machine.
+ init() { self.state = .initial }
+
+ /// An error returned by the state machine.
+ enum ActionError: Hashable {
+
+ /// The outer, raw part sequence called next before the current part's body was fully consumed.
+ ///
+ /// This is a usage error by the consumer of the sequence.
+ case partSequenceNextCalledBeforeBodyWasConsumed
+
+ /// The first frame received was a body chunk instead of header fields, which is invalid.
+ ///
+ /// This indicates an issue in the source of frames.
+ case receivedBodyChunkInInitial
+
+ /// Received a body chunk when waiting for header fields, which is invalid.
+ ///
+ /// This indicates an issue in the source of frames.
+ case receivedBodyChunkWhenWaitingForHeaders
+
+ /// Received another frame before having had a chance to send out header fields, this is an error caused
+ /// by the driver of the state machine.
+ case receivedFrameWhenAlreadyHasUnsentHeaders
+ }
+
+ /// An action returned by the `nextFromPartSequence` method.
+ enum NextFromPartSequenceAction: Hashable {
+
+ /// Return nil to the caller, no more parts.
+ case returnNil
+
+ /// Fetch the next frame.
+ case fetchFrame
+
+ /// Throw the provided error.
+ case emitError(ActionError)
+
+ /// Emit a part with the provided header fields.
+ case emitPart(HTTPFields)
+ }
+
+ /// Read the next part from the upstream frames.
+ /// - Returns: An action to perform.
+ mutating func nextFromPartSequence() -> NextFromPartSequenceAction {
+ switch state {
+ case .initial:
+ state = .waitingToSendHeaders(nil)
+ return .fetchFrame
+ case .waitingToSendHeaders(.some(let headers)):
+ state = .streamingBody
+ return .emitPart(headers)
+ case .waitingToSendHeaders(.none), .streamingBody:
+ state = .finished
+ return .emitError(.partSequenceNextCalledBeforeBodyWasConsumed)
+ case .finished: return .returnNil
+ }
+ }
+
+ /// An action returned by the `partReceivedFrame` method.
+ enum PartReceivedFrameAction: Hashable {
+
+ /// Return nil to the caller, no more parts.
+ case returnNil
+
+ /// Throw the provided error.
+ case emitError(ActionError)
+
+ /// Emit a part with the provided header fields.
+ case emitPart(HTTPFields)
+ }
+
+ /// Ingest the provided frame, requested by the part sequence.
+ /// - Parameter frame: A new frame. If `nil`, then the source of frames is finished.
+ /// - Returns: An action to perform.
+ mutating func partReceivedFrame(_ frame: MultipartFrame?) -> PartReceivedFrameAction {
+ switch state {
+ case .initial: preconditionFailure("Haven't asked for a part chunk, how did we receive one?")
+ case .waitingToSendHeaders(.some):
+ state = .finished
+ return .emitError(.receivedFrameWhenAlreadyHasUnsentHeaders)
+ case .waitingToSendHeaders(.none):
+ if let frame {
+ switch frame {
+ case .headerFields(let headers):
+ state = .streamingBody
+ return .emitPart(headers)
+ case .bodyChunk:
+ state = .finished
+ return .emitError(.receivedBodyChunkWhenWaitingForHeaders)
+ }
+ } else {
+ state = .finished
+ return .returnNil
+ }
+ case .streamingBody:
+ state = .finished
+ return .emitError(.partSequenceNextCalledBeforeBodyWasConsumed)
+ case .finished: return .returnNil
+ }
+ }
+
+ /// An action returned by the `nextFromBodySubsequence` method.
+ enum NextFromBodySubsequenceAction: Hashable {
+
+ /// Return nil to the caller, no more byte chunks.
+ case returnNil
+
+ /// Fetch the next frame.
+ case fetchFrame
+
+ /// Throw the provided error.
+ case emitError(ActionError)
+ }
+
+ /// Read the next byte chunk requested by the current part's body sequence.
+ /// - Returns: An action to perform.
+ mutating func nextFromBodySubsequence() -> NextFromBodySubsequenceAction {
+ switch state {
+ case .initial:
+ state = .finished
+ return .emitError(.receivedBodyChunkInInitial)
+ case .waitingToSendHeaders:
+ state = .finished
+ return .emitError(.receivedBodyChunkWhenWaitingForHeaders)
+ case .streamingBody: return .fetchFrame
+ case .finished: return .returnNil
+ }
+ }
+
+ /// An action returned by the `bodyReceivedFrame` method.
+ enum BodyReceivedFrameAction: Hashable {
+
+ /// Return nil to the caller, no more byte chunks.
+ case returnNil
+
+ /// Return the provided byte chunk.
+ case returnChunk(ArraySlice<UInt8>)
+
+ /// Throw the provided error.
+ case emitError(ActionError)
+ }
+
+ /// Ingest the provided frame, requested by the body sequence.
+ /// - Parameter frame: A new frame. If `nil`, then the source of frames is finished.
+ /// - Returns: An action to perform.
+ mutating func bodyReceivedFrame(_ frame: MultipartFrame?) -> BodyReceivedFrameAction {
+ switch state {
+ case .initial: preconditionFailure("Haven't asked for a frame, how did we receive one?")
+ case .waitingToSendHeaders:
+ state = .finished
+ return .emitError(.receivedBodyChunkWhenWaitingForHeaders)
+ case .streamingBody:
+ if let frame {
+ switch frame {
+ case .headerFields(let headers):
+ state = .waitingToSendHeaders(headers)
+ return .returnNil
+ case .bodyChunk(let bodyChunk): return .returnChunk(bodyChunk)
+ }
+ } else {
+ state = .finished
+ return .returnNil
+ }
+ case .finished: return .returnNil
+ }
+ }
+ }
+}
+
+extension MultipartFramesToRawPartsSequence {
+
+ /// A type-safe iterator shared by the outer part sequence iterator and an inner body sequence iterator.
+ ///
+ /// It enforces that when a new part is emitted by the outer sequence, that the new part's body is then fully
+ /// consumed before the outer sequence is asked for the next part.
+ ///
+ /// This is required as the source of bytes is a single stream, so without the current part's body being consumed,
+ /// we can't move on to the next part.
+ actor SharedIterator {
+
+ /// The upstream source of frames.
+ private var upstream: Upstream.AsyncIterator
+
+ /// The underlying state machine.
+ private var stateMachine: StateMachine
+
+ /// Creates a new iterator.
+ /// - Parameter makeUpstreamIterator: A closure that creates the upstream source of frames.
+ init(makeUpstreamIterator: @Sendable () -> Upstream.AsyncIterator) {
+ let upstream = makeUpstreamIterator()
+ self.upstream = upstream
+ self.stateMachine = .init()
+ }
+
+ /// An error thrown by the shared iterator.
+ struct IteratorError: Swift.Error, CustomStringConvertible, LocalizedError {
+
+ /// The underlying error emitted by the state machine.
+ let error: StateMachine.ActionError
+
+ var description: String {
+ switch error {
+ case .partSequenceNextCalledBeforeBodyWasConsumed:
+ return
+ "The outer part sequence was asked for the next element before the current part's inner body sequence was fully consumed."
+ case .receivedBodyChunkInInitial:
+ return
+ "Received a body chunk from the upstream sequence as the first element, instead of header fields."
+ case .receivedBodyChunkWhenWaitingForHeaders:
+ return "Received a body chunk from the upstream sequence when expecting header fields."
+ case .receivedFrameWhenAlreadyHasUnsentHeaders:
+ return "Received another frame before the current frame with header fields was written out."
+ }
+ }
+
+ var errorDescription: String? { description }
+ }
+
+ /// Request the next element from the outer part sequence.
+ /// - Parameter bodyClosure: The closure invoked to fetch the next byte chunk of the part's body.
+ /// - Returns: The next element, or `nil` if finished.
+ /// - Throws: When a parsing error is encountered.
+ func nextFromPartSequence(bodyClosure: @escaping @Sendable () async throws -> ArraySlice<UInt8>?) async throws
+ -> Element?
+ {
+ switch stateMachine.nextFromPartSequence() {
+ case .returnNil: return nil
+ case .fetchFrame:
+ var upstream = upstream
+ let frame = try await upstream.next()
+ self.upstream = upstream | This dance seems odd. Because of it being an `actor`? |
swift-openapi-runtime | github_2023 | others | 73 | apple | simonjbeaumont | @@ -0,0 +1,71 @@
+//===----------------------------------------------------------------------===//
+//
+// This source file is part of the SwiftOpenAPIGenerator open source project
+//
+// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors
+// Licensed under Apache License v2.0
+//
+// See LICENSE.txt for license information
+// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors
+//
+// SPDX-License-Identifier: Apache-2.0
+//
+//===----------------------------------------------------------------------===//
+
+import HTTPTypes
+
+/// A sequence that serializes multipart frames into bytes.
+struct MultipartFramesToBytesSequence<Upstream: AsyncSequence & Sendable>: Sendable
+where Upstream.Element == MultipartFrame {
+
+ /// The source of multipart frames.
+ var upstream: Upstream
+
+ /// The boundary string used to separate multipart parts.
+ var boundary: String
+}
+
+extension MultipartFramesToBytesSequence: AsyncSequence {
+
+ /// The type of element produced by this asynchronous sequence.
+ typealias Element = ArraySlice<UInt8> | How do you feel about making use of the byte chunk here.
```suggestion
typealias Element = HTTPBody.ByteChunk
``` |
swift-openapi-runtime | github_2023 | others | 73 | apple | simonjbeaumont | @@ -0,0 +1,260 @@
+//===----------------------------------------------------------------------===//
+//
+// This source file is part of the SwiftOpenAPIGenerator open source project
+//
+// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors
+// Licensed under Apache License v2.0
+//
+// See LICENSE.txt for license information
+// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors
+//
+// SPDX-License-Identifier: Apache-2.0
+//
+//===----------------------------------------------------------------------===//
+
+import Foundation
+import HTTPTypes
+
+/// A serializer of multipart frames into bytes.
+struct MultipartSerializer {
+
+ /// The boundary that separates parts.
+ private let boundary: ArraySlice<UInt8>
+
+ /// The underlying state machine.
+ private var stateMachine: StateMachine
+
+ /// The buffer of bytes ready to be written out.
+ private var outBuffer: [UInt8]
+
+ /// Creates a new serializer.
+ /// - Parameter boundary: The boundary that separates parts.
+ init(boundary: String) {
+ self.boundary = ArraySlice(boundary.utf8)
+ self.stateMachine = .init()
+ self.outBuffer = []
+ }
+ /// Requests the next byte chunk.
+ /// - Parameter fetchFrame: A closure that is called when the serializer is ready to serialize the next frame.
+ /// - Returns: A byte chunk.
+ /// - Throws: When a serialization error is encountered.
+ mutating func next(_ fetchFrame: () async throws -> MultipartFrame?) async throws -> ArraySlice<UInt8>? {
+
+ func flushedBytes() -> ArraySlice<UInt8> {
+ let outChunk = ArraySlice(outBuffer)
+ outBuffer.removeAll(keepingCapacity: true)
+ return outChunk
+ }
+
+ while true {
+ switch stateMachine.next() {
+ case .returnNil: return nil
+ case .emitStart:
+ emitStart()
+ return flushedBytes()
+ case .needsMore:
+ let frame = try await fetchFrame()
+ switch stateMachine.receivedFrame(frame) {
+ case .returnNil: return nil
+ case .emitEvents(let events):
+ for event in events {
+ switch event {
+ case .headerFields(let headerFields): emitHeaders(headerFields)
+ case .bodyChunk(let chunk): emitBodyChunk(chunk)
+ case .endOfPart: emitEndOfPart()
+ case .start: emitStart()
+ case .end: emitEnd()
+ }
+ }
+ return flushedBytes()
+ case .emitError(let error): throw SerializerError(error: error)
+ }
+ }
+ }
+ }
+}
+
+extension MultipartSerializer {
+
+ /// An error thrown by the serializer.
+ struct SerializerError: Swift.Error, CustomStringConvertible, LocalizedError {
+
+ /// The underlying error emitted by the state machine.
+ var error: StateMachine.ActionError
+
+ var description: String {
+ switch error {
+ case .noHeaderFieldsAtStart: return "No header fields found at the start of the multipart body."
+ }
+ }
+
+ var errorDescription: String? { description }
+ }
+}
+
+extension MultipartSerializer {
+
+ /// Writes the provided header fields into the buffer.
+ /// - Parameter headerFields: The header fields to serialize.
+ private mutating func emitHeaders(_ headerFields: HTTPFields) {
+ outBuffer.append(contentsOf: ASCII.crlf)
+ let sortedHeaders = headerFields.sorted { a, b in a.name.canonicalName < b.name.canonicalName }
+ for headerField in sortedHeaders {
+ outBuffer.append(contentsOf: headerField.name.canonicalName.utf8)
+ outBuffer.append(contentsOf: ASCII.colonSpace)
+ outBuffer.append(contentsOf: headerField.value.utf8)
+ outBuffer.append(contentsOf: ASCII.crlf)
+ }
+ outBuffer.append(contentsOf: ASCII.crlf)
+ }
+
+ /// Writes the part body chunk into the buffer.
+ /// - Parameter bodyChunk: The body chunk to write.
+ private mutating func emitBodyChunk(_ bodyChunk: ArraySlice<UInt8>) { outBuffer.append(contentsOf: bodyChunk) }
+
+ /// Writes an end of part boundary into the buffer.
+ private mutating func emitEndOfPart() {
+ outBuffer.append(contentsOf: ASCII.crlf)
+ outBuffer.append(contentsOf: ASCII.dashes)
+ outBuffer.append(contentsOf: boundary)
+ }
+
+ /// Writes the start boundary into the buffer.
+ private mutating func emitStart() {
+ outBuffer.append(contentsOf: ASCII.dashes)
+ outBuffer.append(contentsOf: boundary)
+ }
+
+ /// Writes the end double dash to the buffer.
+ private mutating func emitEnd() {
+ outBuffer.append(contentsOf: ASCII.dashes)
+ outBuffer.append(contentsOf: ASCII.crlf)
+ outBuffer.append(contentsOf: ASCII.crlf)
+ }
+}
+
+extension MultipartSerializer {
+
+ /// A state machine representing the multipart frame serializer.
+ struct StateMachine {
+
+ /// The possible states of the state machine.
+ enum State: Hashable {
+
+ /// Has not yet written any bytes.
+ case initial
+
+ /// Emitted start, but no frames yet.
+ case startedNothingEmittedYet | Needs a better name since the comment suggests emitted _something_ (cf. nothing); specifically the start.
For symmetry with the others, why not, simply `emittedStart`? |
swift-openapi-runtime | github_2023 | others | 70 | apple | MahdiBM | @@ -1,5 +1,9 @@
# Swift OpenAPI Generator Runtime
+[](https://swiftpackageindex.com/apple/swift-openapi-runtime/documentation) | Would you want to add the SSWG badge too perhaps, or have you already thought about it?
With an `img` tag it would look like so:
```
<img src="https://user-images.githubusercontent.com/54685446/201329617-9fd91ab0-35c2-42c2-8963-47b68c6a490a.png" alt="SSWG sandbox">
``` |
swift-openapi-runtime | github_2023 | others | 72 | apple | simonjbeaumont | @@ -0,0 +1,121 @@
+//===----------------------------------------------------------------------===//
+//
+// This source file is part of the SwiftOpenAPIGenerator open source project
+//
+// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors
+// Licensed under Apache License v2.0
+//
+// See LICENSE.txt for license information
+// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors
+//
+// SPDX-License-Identifier: Apache-2.0
+//
+//===----------------------------------------------------------------------===//
+
+/// A namespace of utilities for byte parsers and serializers.
+enum ASCII {
+
+ /// The dash `-` character.
+ static let dash: UInt8 = 0x2d
+
+ /// The carriage return `<CR>` character.
+ static let cr: UInt8 = 0x0d
+
+ /// The line feed `<LF>` character.
+ static let lf: UInt8 = 0x0a
+
+ /// The colon `:` character.
+ static let colon: UInt8 = 0x3a
+
+ /// The space ` ` character.
+ static let space: UInt8 = 0x20
+
+ /// The horizontal tab `<TAB>` character.
+ static let tab: UInt8 = 0x20 | ```suggestion
static let tab: UInt8 = 0x09
``` |
swift-openapi-runtime | github_2023 | others | 72 | apple | simonjbeaumont | @@ -0,0 +1,342 @@
+//===----------------------------------------------------------------------===//
+//
+// This source file is part of the SwiftOpenAPIGenerator open source project
+//
+// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors
+// Licensed under Apache License v2.0
+//
+// See LICENSE.txt for license information
+// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors
+//
+// SPDX-License-Identifier: Apache-2.0
+//
+//===----------------------------------------------------------------------===//
+
+import Foundation
+import HTTPTypes
+
+/// A parser of mutlipart frames from bytes.
+struct MultipartParser {
+
+ /// The underlying state machine.
+ private var stateMachine: StateMachine
+ /// Creates a new parser.
+ /// - Parameter boundary: The boundary that separates parts.
+ init(boundary: String) { self.stateMachine = .init(boundary: boundary) }
+ /// Parses the next frame.
+ /// - Parameter fetchChunk: A closure that is called when the parser
+ /// needs more bytes to parse the next frame.
+ /// - Returns: A parsed frame, or nil at the end of the message.
+ /// - Throws: When a parsing error is encountered.
+ mutating func next(_ fetchChunk: () async throws -> ArraySlice<UInt8>?) async throws -> MultipartFrame? {
+ while true {
+ switch stateMachine.readNextPart() {
+ case .none: continue
+ case .emitError(let actionError): throw ParserError(error: actionError)
+ case .returnNil: return nil
+ case .emitHeaderFields(let httpFields): return .headerFields(httpFields)
+ case .emitBodyChunk(let bodyChunk): return .bodyChunk(bodyChunk)
+ case .needsMore:
+ let chunk = try await fetchChunk()
+ switch stateMachine.receivedChunk(chunk) {
+ case .none: continue
+ case .returnNil: return nil
+ case .emitError(let actionError): throw ParserError(error: actionError)
+ }
+ }
+ }
+ }
+}
+extension MultipartParser {
+ /// An error thrown by the parser.
+ struct ParserError: Swift.Error, CustomStringConvertible, LocalizedError {
+
+ /// The underlying error emitted by the state machine.
+ let error: MultipartParser.StateMachine.ActionError
+
+ var description: String {
+ switch error {
+ case .invalidInitialBoundary: return "Invalid initial boundary."
+ case .invalidCRLFAtStartOfHeaderField: return "Invalid CRLF at the start of a header field."
+ case .missingColonAfterHeaderName: return "Missing colon after header field name."
+ case .invalidCharactersInHeaderFieldName: return "Invalid characters in a header field name."
+ case .incompleteMultipartMessage: return "Incomplete multipart message."
+ case .receivedChunkWhenFinished: return "Received a chunk after being finished."
+ }
+ }
+
+ var errorDescription: String? { description }
+ }
+}
+
+extension MultipartParser {
+
+ /// A state machine representing the byte to multipart frame parser.
+ struct StateMachine {
+ /// The possible states of the state machine.
+ enum State: Hashable {
+
+ /// Has not yet fully parsed the initial boundary.
+ case parsingInitialBoundary([UInt8])
+
+ /// A substate when parsing a part.
+ enum PartState: Hashable {
+
+ /// Accumulating part headers.
+ case parsingHeaderFields(HTTPFields)
+
+ /// Forwarding body chunks.
+ case parsingBody
+ }
+
+ /// Is parsing a part.
+ case parsingPart([UInt8], PartState)
+
+ /// Finished, the terminal state.
+ case finished
+
+ /// Helper state to avoid copy-on-write copies.
+ case mutating
+ }
+
+ /// The current state of the state machine.
+ private(set) var state: State
+
+ /// The bytes of the boundary.
+ private let boundary: ArraySlice<UInt8>
+
+ /// The bytes of the boundary with the double dash prepended.
+ private let dashDashBoundary: ArraySlice<UInt8>
+
+ /// The bytes of the boundary prepended by CRLF + double dash.
+ private let crlfDashDashBoundary: ArraySlice<UInt8>
+ /// Creates a new state machine.
+ /// - Parameter boundary: The boundary used to separate parts.
+ init(boundary: String) {
+ self.state = .parsingInitialBoundary([])
+ self.boundary = ArraySlice(boundary.utf8)
+ self.dashDashBoundary = ASCII.dashes + self.boundary
+ self.crlfDashDashBoundary = ASCII.crlf + dashDashBoundary
+ }
+ /// An error returned by the state machine.
+ enum ActionError: Hashable {
+
+ /// The initial boundary is malformed.
+ case invalidInitialBoundary
+
+ /// The expected CRLF at the start of a header is missing.
+ case invalidCRLFAtStartOfHeaderField
+
+ /// A header field name contains an invalid character.
+ case invalidCharactersInHeaderFieldName
+
+ /// The header field name is not followed by a colon.
+ case missingColonAfterHeaderName
+
+ /// More bytes were received after completion.
+ case receivedChunkWhenFinished
+
+ /// Ran out of bytes without the message being complete.
+ case incompleteMultipartMessage
+ }
+ /// An action returned by the `readNextPart` method.
+ enum ReadNextPartAction: Hashable {
+
+ /// No action, call `readNextPart` again.
+ case none
+
+ /// Throw the provided error.
+ case emitError(ActionError)
+
+ /// Return nil to the caller, no more frames.
+ case returnNil
+
+ /// Emit a frame with the provided header fields.
+ case emitHeaderFields(HTTPFields)
+
+ /// Emit a frame with the provided part body chunk.
+ case emitBodyChunk(ArraySlice<UInt8>)
+
+ /// Needs more bytes to parse the next frame.
+ case needsMore
+ }
+ /// Read the next part from the accumulated bytes.
+ /// - Returns: An action to perform.
+ mutating func readNextPart() -> ReadNextPartAction {
+ switch state {
+ case .mutating: preconditionFailure("Invalid state: \(state)")
+ case .finished: return .returnNil
+ case .parsingInitialBoundary(var buffer):
+ state = .mutating
+ // These first bytes must be the boundary already, otherwise this is a malformed multipart body.
+ switch buffer.firstIndexAfterElements(dashDashBoundary) {
+ case .index(let index):
+ buffer.removeSubrange(buffer.startIndex..<index)
+ state = .parsingPart(buffer, .parsingHeaderFields(.init()))
+ return .none
+ case .reachedEndOfSelf:
+ state = .parsingInitialBoundary(buffer)
+ return .needsMore
+ case .mismatchedCharacter:
+ state = .finished
+ return .emitError(.invalidInitialBoundary)
+ }
+ case .parsingPart(var buffer, let partState):
+ state = .mutating
+ switch partState {
+ case .parsingHeaderFields(var headerFields):
+ // Either we find `--` in which case there are no more parts and we're finished, or something else
+ // and we start parsing headers.
+ switch buffer.firstIndexAfterElements(ASCII.dashes) {
+ case .index(let index):
+ state = .finished
+ buffer.removeSubrange(..<index)
+ return .returnNil
+ case .reachedEndOfSelf:
+ state = .parsingPart(buffer, .parsingHeaderFields(headerFields))
+ return .needsMore
+ case .mismatchedCharacter: break
+ }
+ // Consume CRLF
+ let indexAfterFirstCRLF: [UInt8].Index
+ switch buffer.firstIndexAfterElements(ASCII.crlf) {
+ case .index(let index): indexAfterFirstCRLF = index
+ case .reachedEndOfSelf:
+ state = .parsingPart(buffer, .parsingHeaderFields(headerFields))
+ return .needsMore
+ case .mismatchedCharacter:
+ state = .finished
+ return .emitError(.invalidCRLFAtStartOfHeaderField)
+ }
+ // If CRLF is here, this is the end of header fields section.
+ switch buffer[indexAfterFirstCRLF...].firstIndexAfterElements(ASCII.crlf) {
+ case .index(let index):
+ buffer.removeSubrange(buffer.startIndex..<index)
+ state = .parsingPart(buffer, .parsingBody)
+ return .emitHeaderFields(headerFields)
+ case .reachedEndOfSelf:
+ state = .parsingPart(buffer, .parsingHeaderFields(headerFields))
+ return .needsMore
+ case .mismatchedCharacter: break
+ }
+ let startHeaderNameIndex = indexAfterFirstCRLF
+ guard
+ let endHeaderNameIndex = buffer[startHeaderNameIndex...]
+ .firstIndex(where: { !ASCII.isValidHeaderFieldNameByte($0) })
+ else {
+ // No index matched yet, we need more data.
+ state = .parsingPart(buffer, .parsingHeaderFields(headerFields))
+ return .needsMore
+ }
+ let startHeaderValueWithWhitespaceIndex: [UInt8].Index
+ // Check that what follows is a colon, otherwise this is a malformed header field line.
+ // Source: RFC 7230, section 3.2.4.
+ switch buffer[endHeaderNameIndex...].firstIndexAfterElements([ASCII.colon]) { | ~I assume this is a check for `No whitespace is allowed between the header field-name and colon.`, however, this just finds the first index after the next colon and if it finds one, then it sets that as the start of the header value. FWICT it only returns `.emitError(.missingColonAfterHeaderName)` if there is no colon.~
I wrote all of that with a false assumption of what `firstIndexAfterElements` does, which, I think could do with renaming. From the name alone, I assumed it would return the first index after the elements if they exist anywhere in the remaining sequence, not just at the start. |
swift-openapi-runtime | github_2023 | others | 66 | apple | simonjbeaumont | @@ -70,17 +98,49 @@ extension DecodingError {
/// occurred.
/// - codingPath: The coding path to the decoder that attempted to decode
/// the type.
+ /// - errors: The errors encountered when decoding individual cases.
/// - Throws: An error of type `DecodingError.failedToDecodeAnySchema` if none of the child schemas were successfully decoded.
+ @_spi(Generated)
public static func verifyAtLeastOneSchemaIsNotNil(
_ values: [Any?],
type: Any.Type,
- codingPath: [any CodingKey]
+ codingPath: [any CodingKey],
+ errors: [any Error]
) throws {
guard values.contains(where: { $0 != nil }) else {
throw DecodingError.failedToDecodeAnySchema(
type: type,
- codingPath: codingPath
+ codingPath: codingPath,
+ errors: errors
)
}
}
}
+
+/// A wrapper of multiple errors, for example collected during a parallelized
+/// operation from the individual subtasks.
+struct MultiError: Swift.Error, LocalizedError, CustomStringConvertible { | Should this be `@_spi`? |
swift-openapi-runtime | github_2023 | others | 66 | apple | simonjbeaumont | @@ -189,7 +189,7 @@ extension Encoder {
}
/// A freeform String coding key for decoding undocumented values.
-private struct StringKey: CodingKey, Hashable, Comparable {
+struct StringKey: CodingKey, Hashable, Comparable { | Should this be `@_spi`? |
swift-openapi-runtime | github_2023 | others | 65 | apple | gjcairo | @@ -187,3 +187,115 @@ extension OpenAPIMIMEType: LosslessStringConvertible {
.joined(separator: "; ")
}
}
+
+// MARK: - Internals
+
+extension OpenAPIMIMEType {
+
+ /// The result of a match evaluation between two MIME types.
+ enum Match: Hashable {
+
+ /// The reason why two types are incompatible.
+ enum IncompatibilityReason: Hashable {
+
+ /// The types don't match.
+ case type
+
+ /// The subtypes don't match.
+ case subtype
+
+ /// The parameter of the provided name is missing or doesn't match.
+ case parameter(name: String)
+ }
+
+ /// The types are incompatible for the provided reason.
+ case incompatible(IncompatibilityReason)
+
+ /// The types match based on a full wildcard `*/*`.
+ case wildcard
+
+ /// The types match based on a subtype wildcard, such as `image/*`.
+ case subtypeWildcard
+
+ /// The types match across the type, subtype, and the provided number
+ /// of parameters.
+ case typeAndSubtype(matchedParameterCount: Int)
+
+ /// A numeric representation of the quality of the match, the higher
+ /// the closer the types are.
+ var score: Int {
+ switch self {
+ case .incompatible:
+ return 0
+ case .wildcard:
+ return 1
+ case .subtypeWildcard:
+ return 2
+ case .typeAndSubtype(let matchedParameterCount):
+ return 3 + matchedParameterCount
+ }
+ }
+ }
+
+ /// Computes whether two MIME types match.
+ /// - Parameters:
+ /// - receivedType: The type component of the received MIME type.
+ /// - receivedSubtype: The subtype component of the received MIME type.
+ /// - receivedParameters: The parameters of the received MIME type.
+ /// - option: The MIME type to match against.
+ /// - Returns: The match result.
+ static func evaluate(
+ receivedType: String,
+ receivedSubtype: String,
+ receivedParameters: [String: String],
+ against option: OpenAPIMIMEType
+ ) -> Match {
+ switch option.kind {
+ case .any:
+ return .wildcard
+ case .anySubtype(let expectedType):
+ guard receivedType.lowercased() == expectedType.lowercased() else {
+ return .incompatible(.type)
+ }
+ return .subtypeWildcard
+ case .concrete(let expectedType, let expectedSubtype):
+ guard
+ receivedType.lowercased() == expectedType.lowercased()
+ && receivedSubtype.lowercased() == expectedSubtype.lowercased()
+ else {
+ return .incompatible(.subtype)
+ }
+
+ // A full concrete match, so also check parameters.
+ // The rule is:
+ // 1. If a received parameter is not found in the option,
+ // that's okay and gets ignored.
+ // 2. If an option parameter is not received, this is an
+ // incompatible content type match.
+ // This means we can just iterate over option parameters and
+ // check them against the received parameters, but we can
+ // ignore any received parameters that didn't appear in the
+ // option parameters.
+
+ // According to RFC 2045: https://www.rfc-editor.org/rfc/rfc2045#section-5.1
+ // "Type, subtype, and parameter names are case-insensitive."
+ // Inferred: Parameter values are be case-sensitive. | ```suggestion
// Inferred: Parameter values are case-sensitive.
``` |
swift-openapi-runtime | github_2023 | others | 65 | apple | gjcairo | @@ -29,45 +29,52 @@ extension Converter {
return OpenAPIMIMEType(rawValue)
}
- /// Checks whether a concrete content type matches an expected content type.
- ///
- /// The concrete content type can contain parameters, such as `charset`, but
- /// they are ignored in the equality comparison.
- ///
- /// The expected content type can contain wildcards, such as */* and text/*.
+ /// Chooses the most appropriate content type for the provided received
+ /// content type and a list of options.
/// - Parameters:
- /// - received: The concrete content type to validate against the other.
- /// - expectedRaw: The expected content type, can contain wildcards.
- /// - Throws: A `RuntimeError` when `expectedRaw` is not a valid content type.
- /// - Returns: A Boolean value representing whether the concrete content
- /// type matches the expected one.
- public func isMatchingContentType(received: OpenAPIMIMEType?, expectedRaw: String) throws -> Bool {
- guard let received else {
- return false
+ /// - received: The received content type.
+ /// - options: The options to match against.
+ /// - Returns: The most appropriate option.
+ /// - Throws: If none of the options match the received content type.
+ /// - Precondition: `options` must not be empty.
+ public func bestContentType(
+ received: OpenAPIMIMEType?,
+ options: [String]
+ ) throws -> String {
+ precondition(!options.isEmpty, "bestContentType options must not be empty.")
+ guard
+ let received,
+ case let .concrete(type: receivedType, subtype: receivedSubtype) = received.kind
+ else {
+ // If none received or if we received a wildcard, use the first one.
+ // This behavior isn't well defined by the OpenAPI specification.
+ // Note: We treat a partial wildcard, like `image/*` as a full
+ // wildcard `*/*`, but that's okay because for a concrete received
+ // content type the behavior of a wildcard is not clearly defined
+ // either.
+ return options[0]
}
- guard case let .concrete(type: receivedType, subtype: receivedSubtype) = received.kind else {
- return false
+ let evaluatedOptions = try options.map { stringOption in
+ guard let parsedOption = OpenAPIMIMEType(stringOption) else {
+ throw RuntimeError.invalidExpectedContentType(stringOption)
+ }
+ let match = OpenAPIMIMEType.evaluate(
+ receivedType: receivedType,
+ receivedSubtype: receivedSubtype,
+ receivedParameters: received.parameters,
+ against: parsedOption
+ )
+ return (contentType: stringOption, match: match)
}
- guard let expectedContentType = OpenAPIMIMEType(expectedRaw) else {
- throw RuntimeError.invalidExpectedContentType(expectedRaw)
+ let sortedOptions = evaluatedOptions.sorted { a, b in | This may be a needless optimisation, but we could use `Array/max(by:)` ([docs](https://developer.apple.com/documentation/swift/array/max(by:))) instead of sorting, since we're only getting the first option anyways. |
swift-openapi-runtime | github_2023 | others | 65 | apple | gjcairo | @@ -54,6 +55,153 @@ final class Test_CommonConverterExtensions: Test_Runtime {
}
}
+ func testBestContentType() throws {
+ func testCase(
+ received: String?,
+ options: [String],
+ expected expectedChoice: String,
+ file: StaticString = #file,
+ line: UInt = #line
+ ) throws {
+ let choice = try converter.bestContentType(
+ received: received.map { .init($0)! },
+ options: options
+ )
+ XCTAssertEqual(choice, expectedChoice, file: file, line: line)
+ }
+
+ try testCase(
+ received: nil,
+ options: [
+ "application/json",
+ "*/*",
+ ],
+ expected: "application/json"
+ )
+ try testCase(
+ received: "*/*",
+ options: [
+ "application/json",
+ "*/*",
+ ],
+ expected: "application/json"
+ )
+ try testCase(
+ received: "application/*",
+ options: [
+ "application/json",
+ "*/*",
+ ],
+ expected: "application/json"
+ )
+ XCTAssertThrowsError(
+ try testCase(
+ received: "application/json",
+ options: [
+ "whoops"
+ ],
+ expected: "application/json" | Small nit but maybe pass an empty string/nil when we expect errors to be thrown instead, for clarity? |
swift-openapi-runtime | github_2023 | others | 63 | apple | glbrntt | @@ -90,76 +90,116 @@ import Foundation
serializer: @Sendable (OperationInput) throws -> (HTTPRequest, HTTPBody?),
deserializer: @Sendable (HTTPResponse, HTTPBody?) async throws -> OperationOutput
) async throws -> OperationOutput where OperationInput: Sendable, OperationOutput: Sendable {
- @Sendable
- func wrappingErrors<R>(
+ @Sendable func wrappingErrors<R>( | Is this a result of changing formatting options or just a manual fix up? |
swift-openapi-runtime | github_2023 | others | 63 | apple | glbrntt | @@ -64,6 +64,10 @@ public struct ClientError: Error {
/// Will be nil if the error resulted before the response was received.
public var responseBody: HTTPBody?
+ /// A user-facing description of what caused the underlying error
+ /// to be thrown.
+ public var causeDescription: String | Why use a `causeDescription` over wrapping the actual underlying cause in another error which represents the cause description?
For example, with the middleware case, I can imagine something like:
```swift
struct MiddlewareError: Error {
var middlewareType: String
var underlyingError: any Error
var description: String {
"Middleware of type '(middlewareType)' threw ..."
}
}
``` |
swift-openapi-runtime | github_2023 | others | 64 | apple | glbrntt | @@ -0,0 +1,77 @@
+//===----------------------------------------------------------------------===//
+//
+// This source file is part of the SwiftOpenAPIGenerator open source project
+//
+// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors
+// Licensed under Apache License v2.0
+//
+// See LICENSE.txt for license information
+// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors
+//
+// SPDX-License-Identifier: Apache-2.0
+//
+//===----------------------------------------------------------------------===//
+
+import Foundation
+
+extension URL {
+ /// Returns a validated server URL created from the URL template, or
+ /// throws an error.
+ /// - Parameter
+ /// - string: A URL string.
+ /// - variables: A map of variable values to substitute into the URL
+ /// template.
+ /// - Throws: If the provided string doesn't convert to URL.
+ @_spi(Generated)
+ public init(
+ validatingOpenAPIServerURL string: String,
+ variables: [ServerVariable]
+ ) throws {
+ var urlString = string
+ for variable in variables {
+ let name = variable.name
+ let value = variable.value
+ if let allowedValues = variable.allowedValues {
+ guard allowedValues.contains(value) else {
+ throw RuntimeError.invalidServerVariableValue(
+ name: name,
+ value: value,
+ allowedValues: allowedValues
+ )
+ }
+ }
+ urlString = urlString.replacingOccurrences(of: "{\(name)}", with: value)
+ }
+ guard let url = Self(string: urlString) else {
+ throw RuntimeError.invalidServerURL(urlString)
+ }
+ self = url
+ }
+}
+
+/// A variable of a server URL template in the OpenAPI document.
+@_spi(Generated)
+public struct ServerVariable { | `Sendable` and `Hashable`? |
swift-openapi-runtime | github_2023 | others | 62 | apple | glbrntt | @@ -35,6 +41,13 @@ for SCRIPT_PATH in "${SCRIPT_PATHS[@]}"; do
fi
done
+log "Running swift-format..."
+bash ${CURRENT_SCRIPT_DIR}/run-swift-format.sh $FIX_FORMAT > /dev/null | ```suggestion
bash "${CURRENT_SCRIPT_DIR}"/run-swift-format.sh $FIX_FORMAT > /dev/null
``` |
swift-openapi-runtime | github_2023 | others | 60 | apple | czechboy0 | @@ -45,6 +45,7 @@ extension ParameterStyle {
/// Returns the default value of the explode field for the given style
/// - Parameter style: The parameter style.
+ /// - Returns: Bool - True if the style is form, otherwise false | ```suggestion
/// - Returns: `true` if the style is form, otherwise `false`.
``` |
swift-openapi-runtime | github_2023 | others | 60 | apple | czechboy0 | @@ -12,7 +12,7 @@
//
//===----------------------------------------------------------------------===//
import XCTest
-@_spi(Generated)@testable import OpenAPIRuntime
+@_spi(Generated) @testable import OpenAPIRuntime | I think this is because you're using 5.9 swift-format locally, please revert to 5.8 for now, we'll be upgrading to 5.9 swift-format in a dedicated PR in all 4 repos, plus we'll have to bump CI etc. |
swift-openapi-runtime | github_2023 | others | 60 | apple | czechboy0 | @@ -18,6 +18,7 @@ import HTTPTypes
class Test_Runtime: XCTestCase {
+ /// setUp tests | You can remove this as well |
swift-openapi-runtime | github_2023 | others | 58 | apple | dnadoba | @@ -0,0 +1,190 @@
+//===----------------------------------------------------------------------===//
+//
+// This source file is part of the SwiftOpenAPIGenerator open source project
+//
+// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors
+// Licensed under Apache License v2.0
+//
+// See LICENSE.txt for license information
+// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors
+//
+// SPDX-License-Identifier: Apache-2.0
+//
+//===----------------------------------------------------------------------===//
+
+/// A reference type that wraps a value and enforces copy-on-write semantics.
+///
+/// It also enables recursive types by introducing a "box" into the cycle, which
+/// allows the owning type to have a finite size.
+@_spi(Generated)
+public final class CopyOnWriteBox<Wrapped> {
+
+ /// The stored value.
+ private var value: Wrapped
+
+ /// Creates a new box.
+ /// - Parameter value: The value to store in the box.
+ public init(value: Wrapped) {
+ self.value = value
+ }
+
+ /// Returns a copy of the stored value.
+ public func read() -> Wrapped {
+ value
+ }
+
+ /// Provides read-write access to the stored value and enforces
+ /// copy-on-write semantics.
+ /// - Parameters:
+ /// - box: A reference to the existing box, into which a new reference
+ /// might get written if a copy had to be made.
+ /// - modify: The closure that modifies the value.
+ public static func write(
+ to box: inout CopyOnWriteBox<Wrapped>,
+ using modify: (inout Wrapped) -> Void
+ ) {
+ let resolvedBox: CopyOnWriteBox<Wrapped>
+ if isKnownUniquelyReferenced(&box) {
+ resolvedBox = box
+ } else {
+ resolvedBox = Self(value: box.value)
+ box = resolvedBox
+ }
+ modify(&resolvedBox.value)
+ }
+}
+
+extension CopyOnWriteBox: Encodable where Wrapped: Encodable {
+
+ /// Encodes this value into the given encoder.
+ ///
+ /// If the value fails to encode anything, `encoder` will encode an empty
+ /// keyed container in its place.
+ ///
+ /// This function throws an error if any values are invalid for the given
+ /// encoder's format.
+ ///
+ /// - Parameter encoder: The encoder to write data to.
+ /// - Throws: On an encoding error.
+ public func encode(to encoder: any Encoder) throws {
+ try value.encode(to: encoder)
+ }
+}
+
+extension CopyOnWriteBox: Decodable where Wrapped: Decodable {
+
+ /// Creates a new instance by decoding from the given decoder.
+ ///
+ /// This initializer throws an error if reading from the decoder fails, or
+ /// if the data read is corrupted or otherwise invalid.
+ ///
+ /// - Parameter decoder: The decoder to read data from.
+ /// - Throws: On a decoding error.
+ public convenience init(from decoder: any Decoder) throws {
+ let value = try Wrapped(from: decoder)
+ self.init(value: value)
+ }
+}
+
+extension CopyOnWriteBox: Equatable where Wrapped: Equatable {
+
+ /// Returns a Boolean value indicating whether two values are equal.
+ ///
+ /// Equality is the inverse of inequality. For any values `a` and `b`,
+ /// `a == b` implies that `a != b` is `false`.
+ ///
+ /// - Parameters:
+ /// - lhs: A value to compare.
+ /// - rhs: Another value to compare.
+ /// - Returns: A Boolean value indicating whether the values are equal.
+ public static func == ( | Do we really want to copy & paste the documentation for these? It seems DocC doesn't currently auto inherit the documentation but this is more of a tooling problem. |
swift-openapi-runtime | github_2023 | others | 58 | apple | dnadoba | @@ -0,0 +1,190 @@
+//===----------------------------------------------------------------------===//
+//
+// This source file is part of the SwiftOpenAPIGenerator open source project
+//
+// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors
+// Licensed under Apache License v2.0
+//
+// See LICENSE.txt for license information
+// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors
+//
+// SPDX-License-Identifier: Apache-2.0
+//
+//===----------------------------------------------------------------------===//
+
+/// A reference type that wraps a value and enforces copy-on-write semantics.
+///
+/// It also enables recursive types by introducing a "box" into the cycle, which
+/// allows the owning type to have a finite size.
+@_spi(Generated)
+public final class CopyOnWriteBox<Wrapped> {
+
+ /// The stored value.
+ private var value: Wrapped
+
+ /// Creates a new box.
+ /// - Parameter value: The value to store in the box.
+ public init(value: Wrapped) {
+ self.value = value
+ }
+
+ /// Returns a copy of the stored value.
+ public func read() -> Wrapped {
+ value
+ }
+
+ /// Provides read-write access to the stored value and enforces
+ /// copy-on-write semantics.
+ /// - Parameters:
+ /// - box: A reference to the existing box, into which a new reference
+ /// might get written if a copy had to be made.
+ /// - modify: The closure that modifies the value.
+ public static func write(
+ to box: inout CopyOnWriteBox<Wrapped>,
+ using modify: (inout Wrapped) -> Void
+ ) {
+ let resolvedBox: CopyOnWriteBox<Wrapped>
+ if isKnownUniquelyReferenced(&box) {
+ resolvedBox = box
+ } else {
+ resolvedBox = Self(value: box.value)
+ box = resolvedBox
+ }
+ modify(&resolvedBox.value)
+ } | Why is this a static method instead of an instance method? |
swift-openapi-runtime | github_2023 | others | 58 | apple | dnadoba | @@ -0,0 +1,191 @@
+//===----------------------------------------------------------------------===//
+//
+// This source file is part of the SwiftOpenAPIGenerator open source project
+//
+// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors
+// Licensed under Apache License v2.0
+//
+// See LICENSE.txt for license information
+// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors
+//
+// SPDX-License-Identifier: Apache-2.0
+//
+//===----------------------------------------------------------------------===//
+
+/// A type that wraps a value and enforces copy-on-write semantics.
+///
+/// It also enables recursive types by introducing a "box" into the cycle, which
+/// allows the owning type to have a finite size.
+@_spi(Generated)
+public struct CopyOnWriteBox<Wrapped> {
+
+ /// The reference type storage for the box.
+ private final class Storage {
+
+ /// The stored value.
+ var value: Wrapped
+
+ /// Creates a new storage with the provided initial value.
+ /// - Parameter value: The initial value to store in the box.
+ init(value: Wrapped) {
+ self.value = value
+ }
+ }
+
+ /// The internal storage of the box.
+ private var storage: Storage
+
+ /// Creates a new box.
+ /// - Parameter value: The value to store in the box.
+ public init(value: Wrapped) {
+ self.storage = .init(value: value)
+ }
+
+ /// The stored value whose accessors enforce copy-on-write semantics.
+ public var value: Wrapped { | This needs to be `@inlineable` to allow proper optimisation |
swift-openapi-runtime | github_2023 | others | 58 | apple | dnadoba | @@ -0,0 +1,191 @@
+//===----------------------------------------------------------------------===//
+//
+// This source file is part of the SwiftOpenAPIGenerator open source project
+//
+// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors
+// Licensed under Apache License v2.0
+//
+// See LICENSE.txt for license information
+// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors
+//
+// SPDX-License-Identifier: Apache-2.0
+//
+//===----------------------------------------------------------------------===//
+
+/// A type that wraps a value and enforces copy-on-write semantics.
+///
+/// It also enables recursive types by introducing a "box" into the cycle, which
+/// allows the owning type to have a finite size.
+@_spi(Generated)
+public struct CopyOnWriteBox<Wrapped> {
+
+ /// The reference type storage for the box.
+ private final class Storage {
+
+ /// The stored value.
+ var value: Wrapped
+
+ /// Creates a new storage with the provided initial value.
+ /// - Parameter value: The initial value to store in the box.
+ init(value: Wrapped) {
+ self.value = value
+ }
+ }
+
+ /// The internal storage of the box.
+ private var storage: Storage
+
+ /// Creates a new box.
+ /// - Parameter value: The value to store in the box.
+ public init(value: Wrapped) {
+ self.storage = .init(value: value)
+ }
+
+ /// The stored value whose accessors enforce copy-on-write semantics.
+ public var value: Wrapped {
+ get {
+ storage.value
+ }
+ _modify {
+ if !isKnownUniquelyReferenced(&storage) {
+ storage = Storage(value: storage.value)
+ }
+ yield &storage.value
+ } | This might need `@inline(__always)` due to current limitations in the compiler or it otherwise will always allocate.
[Cory has found out that this is necessary a while ago in `swift-collections`.](https://github.com/apple/swift-collections/issues/164) @lukasa do you know if this has changed in newer swift compilers? |
swift-openapi-runtime | github_2023 | others | 58 | apple | dnadoba | @@ -0,0 +1,197 @@
+//===----------------------------------------------------------------------===//
+//
+// This source file is part of the SwiftOpenAPIGenerator open source project
+//
+// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors
+// Licensed under Apache License v2.0
+//
+// See LICENSE.txt for license information
+// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors
+//
+// SPDX-License-Identifier: Apache-2.0
+//
+//===----------------------------------------------------------------------===//
+
+/// A type that wraps a value and enforces copy-on-write semantics.
+///
+/// It also enables recursive types by introducing a "box" into the cycle, which
+/// allows the owning type to have a finite size.
+@_spi(Generated)
+public struct CopyOnWriteBox<Wrapped> {
+
+ /// The reference type storage for the box.
+ @usableFromInline
+ internal final class Storage {
+
+ /// The stored value.
+ @usableFromInline
+ var value: Wrapped
+
+ /// Creates a new storage with the provided initial value.
+ /// - Parameter value: The initial value to store in the box.
+ @usableFromInline
+ init(value: Wrapped) {
+ self.value = value
+ } | `Storage` is implicitly generic because its outer type is generic so this should be `@inlinable` as well. |
swift-openapi-runtime | github_2023 | others | 58 | apple | dnadoba | @@ -0,0 +1,197 @@
+//===----------------------------------------------------------------------===//
+//
+// This source file is part of the SwiftOpenAPIGenerator open source project
+//
+// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors
+// Licensed under Apache License v2.0
+//
+// See LICENSE.txt for license information
+// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors
+//
+// SPDX-License-Identifier: Apache-2.0
+//
+//===----------------------------------------------------------------------===//
+
+/// A type that wraps a value and enforces copy-on-write semantics.
+///
+/// It also enables recursive types by introducing a "box" into the cycle, which
+/// allows the owning type to have a finite size.
+@_spi(Generated)
+public struct CopyOnWriteBox<Wrapped> {
+
+ /// The reference type storage for the box.
+ @usableFromInline
+ internal final class Storage {
+
+ /// The stored value.
+ @usableFromInline
+ var value: Wrapped
+
+ /// Creates a new storage with the provided initial value.
+ /// - Parameter value: The initial value to store in the box.
+ @usableFromInline
+ init(value: Wrapped) {
+ self.value = value
+ }
+ }
+
+ /// The internal storage of the box.
+ @usableFromInline
+ internal var storage: Storage
+
+ /// Creates a new box.
+ /// - Parameter value: The value to store in the box.
+ @inlinable
+ public init(value: Wrapped) {
+ self.storage = .init(value: value)
+ }
+
+ /// The stored value whose accessors enforce copy-on-write semantics.
+ @inlinable
+ public var value: Wrapped {
+ get {
+ storage.value
+ }
+ _modify {
+ if !isKnownUniquelyReferenced(&storage) {
+ storage = Storage(value: storage.value)
+ }
+ yield &storage.value
+ }
+ }
+}
+
+extension CopyOnWriteBox: Encodable where Wrapped: Encodable {
+
+ /// Encodes this value into the given encoder.
+ ///
+ /// If the value fails to encode anything, `encoder` will encode an empty
+ /// keyed container in its place.
+ ///
+ /// This function throws an error if any values are invalid for the given
+ /// encoder's format.
+ ///
+ /// - Parameter encoder: The encoder to write data to.
+ /// - Throws: On an encoding error.
+ public func encode(to encoder: any Encoder) throws {
+ try value.encode(to: encoder)
+ }
+}
+
+extension CopyOnWriteBox: Decodable where Wrapped: Decodable {
+
+ /// Creates a new instance by decoding from the given decoder.
+ ///
+ /// This initializer throws an error if reading from the decoder fails, or
+ /// if the data read is corrupted or otherwise invalid.
+ ///
+ /// - Parameter decoder: The decoder to read data from.
+ /// - Throws: On a decoding error.
+ public init(from decoder: any Decoder) throws {
+ let value = try Wrapped(from: decoder)
+ self.init(value: value)
+ }
+}
+
+extension CopyOnWriteBox: Equatable where Wrapped: Equatable {
+
+ /// Returns a Boolean value indicating whether two values are equal.
+ ///
+ /// Equality is the inverse of inequality. For any values `a` and `b`,
+ /// `a == b` implies that `a != b` is `false`.
+ ///
+ /// - Parameters:
+ /// - lhs: A value to compare.
+ /// - rhs: Another value to compare.
+ /// - Returns: A Boolean value indicating whether the values are equal.
+ public static func == (
+ lhs: CopyOnWriteBox<Wrapped>,
+ rhs: CopyOnWriteBox<Wrapped>
+ ) -> Bool {
+ lhs.value == rhs.value
+ }
+}
+
+extension CopyOnWriteBox: Hashable where Wrapped: Hashable {
+
+ /// Hashes the essential components of this value by feeding them into the
+ /// given hasher.
+ ///
+ /// Implement this method to conform to the `Hashable` protocol. The
+ /// components used for hashing must be the same as the components compared
+ /// in your type's `==` operator implementation. Call `hasher.combine(_:)`
+ /// with each of these components.
+ ///
+ /// - Important: In your implementation of `hash(into:)`,
+ /// don't call `finalize()` on the `hasher` instance provided,
+ /// or replace it with a different instance.
+ /// Doing so may become a compile-time error in the future.
+ ///
+ /// - Parameter hasher: The hasher to use when combining the components
+ /// of this instance.
+ public func hash(into hasher: inout Hasher) { | `@inlinable` is missing. |
swift-openapi-runtime | github_2023 | others | 58 | apple | dnadoba | @@ -0,0 +1,197 @@
+//===----------------------------------------------------------------------===//
+//
+// This source file is part of the SwiftOpenAPIGenerator open source project
+//
+// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors
+// Licensed under Apache License v2.0
+//
+// See LICENSE.txt for license information
+// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors
+//
+// SPDX-License-Identifier: Apache-2.0
+//
+//===----------------------------------------------------------------------===//
+
+/// A type that wraps a value and enforces copy-on-write semantics.
+///
+/// It also enables recursive types by introducing a "box" into the cycle, which
+/// allows the owning type to have a finite size.
+@_spi(Generated)
+public struct CopyOnWriteBox<Wrapped> {
+
+ /// The reference type storage for the box.
+ @usableFromInline
+ internal final class Storage {
+
+ /// The stored value.
+ @usableFromInline
+ var value: Wrapped
+
+ /// Creates a new storage with the provided initial value.
+ /// - Parameter value: The initial value to store in the box.
+ @usableFromInline
+ init(value: Wrapped) {
+ self.value = value
+ }
+ }
+
+ /// The internal storage of the box.
+ @usableFromInline
+ internal var storage: Storage
+
+ /// Creates a new box.
+ /// - Parameter value: The value to store in the box.
+ @inlinable
+ public init(value: Wrapped) {
+ self.storage = .init(value: value)
+ }
+
+ /// The stored value whose accessors enforce copy-on-write semantics.
+ @inlinable
+ public var value: Wrapped {
+ get {
+ storage.value
+ }
+ _modify {
+ if !isKnownUniquelyReferenced(&storage) {
+ storage = Storage(value: storage.value)
+ }
+ yield &storage.value
+ }
+ }
+}
+
+extension CopyOnWriteBox: Encodable where Wrapped: Encodable {
+
+ /// Encodes this value into the given encoder.
+ ///
+ /// If the value fails to encode anything, `encoder` will encode an empty
+ /// keyed container in its place.
+ ///
+ /// This function throws an error if any values are invalid for the given
+ /// encoder's format.
+ ///
+ /// - Parameter encoder: The encoder to write data to.
+ /// - Throws: On an encoding error.
+ public func encode(to encoder: any Encoder) throws {
+ try value.encode(to: encoder)
+ }
+}
+
+extension CopyOnWriteBox: Decodable where Wrapped: Decodable {
+
+ /// Creates a new instance by decoding from the given decoder.
+ ///
+ /// This initializer throws an error if reading from the decoder fails, or
+ /// if the data read is corrupted or otherwise invalid.
+ ///
+ /// - Parameter decoder: The decoder to read data from.
+ /// - Throws: On a decoding error.
+ public init(from decoder: any Decoder) throws { | `@inlinable` missing. |
swift-openapi-runtime | github_2023 | others | 58 | apple | dnadoba | @@ -0,0 +1,197 @@
+//===----------------------------------------------------------------------===//
+//
+// This source file is part of the SwiftOpenAPIGenerator open source project
+//
+// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors
+// Licensed under Apache License v2.0
+//
+// See LICENSE.txt for license information
+// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors
+//
+// SPDX-License-Identifier: Apache-2.0
+//
+//===----------------------------------------------------------------------===//
+
+/// A type that wraps a value and enforces copy-on-write semantics.
+///
+/// It also enables recursive types by introducing a "box" into the cycle, which
+/// allows the owning type to have a finite size.
+@_spi(Generated)
+public struct CopyOnWriteBox<Wrapped> {
+
+ /// The reference type storage for the box.
+ @usableFromInline
+ internal final class Storage {
+
+ /// The stored value.
+ @usableFromInline
+ var value: Wrapped
+
+ /// Creates a new storage with the provided initial value.
+ /// - Parameter value: The initial value to store in the box.
+ @usableFromInline
+ init(value: Wrapped) {
+ self.value = value
+ }
+ }
+
+ /// The internal storage of the box.
+ @usableFromInline
+ internal var storage: Storage
+
+ /// Creates a new box.
+ /// - Parameter value: The value to store in the box.
+ @inlinable
+ public init(value: Wrapped) {
+ self.storage = .init(value: value)
+ }
+
+ /// The stored value whose accessors enforce copy-on-write semantics.
+ @inlinable
+ public var value: Wrapped {
+ get {
+ storage.value
+ }
+ _modify {
+ if !isKnownUniquelyReferenced(&storage) {
+ storage = Storage(value: storage.value)
+ }
+ yield &storage.value
+ }
+ }
+}
+
+extension CopyOnWriteBox: Encodable where Wrapped: Encodable {
+
+ /// Encodes this value into the given encoder.
+ ///
+ /// If the value fails to encode anything, `encoder` will encode an empty
+ /// keyed container in its place.
+ ///
+ /// This function throws an error if any values are invalid for the given
+ /// encoder's format.
+ ///
+ /// - Parameter encoder: The encoder to write data to.
+ /// - Throws: On an encoding error.
+ public func encode(to encoder: any Encoder) throws { | `@inlinable` missing. |
swift-openapi-runtime | github_2023 | others | 55 | apple | simonjbeaumont | @@ -0,0 +1,38 @@
+//===----------------------------------------------------------------------===//
+//
+// This source file is part of the SwiftOpenAPIGenerator open source project
+//
+// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors
+// Licensed under Apache License v2.0
+//
+// See LICENSE.txt for license information
+// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors
+//
+// SPDX-License-Identifier: Apache-2.0
+//
+//===----------------------------------------------------------------------===//
+
+import Foundation
+
+public struct Base64EncodedData: Sendable, Codable, Hashable {
+ var data: Foundation.Data // or [UInt8] or ArraySlice<UInt8>
+
+ public init(data: Foundation.Data) {
+ self.data = data
+ }
+
+ public init(from decoder: any Decoder) throws {
+ let container = try decoder.singleValueContainer()
+ let base64EncodedString = try container.decode(String.self)
+ guard let data = Data(base64Encoded: base64EncodedString) else {
+ throw RuntimeError.invalidBase64String(base64EncodedString)
+ } | In the past I've been bitten by this method takes options: `Data(base64Encoded:options:)` and that those options change the semantics. I've specifically been bitten with additional whitespace, which many tools consider to be valid, but without the option, this method will return nil.
We should confirm what the OpenAPI spec has to say on this, if anything. |
swift-openapi-runtime | github_2023 | others | 55 | apple | simonjbeaumont | @@ -0,0 +1,38 @@
+//===----------------------------------------------------------------------===//
+//
+// This source file is part of the SwiftOpenAPIGenerator open source project
+//
+// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors
+// Licensed under Apache License v2.0
+//
+// See LICENSE.txt for license information
+// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors
+//
+// SPDX-License-Identifier: Apache-2.0
+//
+//===----------------------------------------------------------------------===//
+
+import Foundation
+
+public struct Base64EncodedData: Sendable, Codable, Hashable {
+ var data: Foundation.Data // or [UInt8] or ArraySlice<UInt8>
+
+ public init(data: Foundation.Data) {
+ self.data = data
+ }
+
+ public init(from decoder: any Decoder) throws {
+ let container = try decoder.singleValueContainer()
+ let base64EncodedString = try container.decode(String.self)
+ guard let data = Data(base64Encoded: base64EncodedString) else {
+ throw RuntimeError.invalidBase64String(base64EncodedString)
+ }
+ self.init(data: data)
+ }
+
+ public func encode(to encoder: any Encoder) throws {
+ var container = encoder.singleValueContainer()
+ let base64String = data.base64EncodedString() | Relatedly, we should peruse the `Base64EncodingOptions` and make sure we're doing the nicest thing we can here.
Principle: we should be permissive on input (so long as it doesn't present a security issue) and strict on output. Where "strict" means, likely to be accepted by the greatest number of other tools. |
swift-openapi-runtime | github_2023 | others | 55 | apple | simonjbeaumont | @@ -266,4 +266,13 @@ final class Test_OpenAPIValue: Test_Runtime {
let nestedValue = try XCTUnwrap(nestedDict["nested"] as? Int)
XCTAssertEqual(nestedValue, 2)
}
+
+ func testEncodingDecodingRoundTrip_base64_success() throws {
+ print(String(data: testStructData.base64EncodedData(), encoding: .utf8)!.utf8)
+ let encodedData = Base64EncodedData(data: testStructData)
+ XCTAssertEqual(
+ try JSONDecoder().decode(Base64EncodedData.self, from: JSONEncoder().encode(encodedData)), | This test is checking that JSON encoder and decoder round trip works for Data, no? |
swift-openapi-runtime | github_2023 | others | 55 | apple | czechboy0 | @@ -0,0 +1,49 @@
+//===----------------------------------------------------------------------===//
+//
+// This source file is part of the SwiftOpenAPIGenerator open source project
+//
+// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors
+// Licensed under Apache License v2.0
+//
+// See LICENSE.txt for license information
+// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors
+//
+// SPDX-License-Identifier: Apache-2.0
+//
+//===----------------------------------------------------------------------===//
+
+import Foundation
+
+public struct Base64EncodedData: Sendable, Codable, Hashable { | Please add docs for all public symbols, ideally also with info how to use this type (create and consume). |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.