Skip to content

Commit

Permalink
Merge pull request #38 from orlandos-nl/jo/sendable
Browse files Browse the repository at this point in the history
Sendable support
  • Loading branch information
Joannis authored Jan 24, 2024
2 parents 8396a38 + f48d825 commit a56bfba
Show file tree
Hide file tree
Showing 5 changed files with 46 additions and 11 deletions.
29 changes: 29 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,35 @@ var decoder = IkigaJSONDecoder()
let user = try decoder.decode(User.self, from: data)
```

### In Hummingbird 2

Conform Ikiga to Hummingbird's protocols like so:

```swift
extension IkigaJSONEncoder: HBResponseEncoder {
public func encode(_ value: some Encodable, from request: HBRequest, context: some HBBaseRequestContext) throws -> HBResponse {
// Capacity should roughly cover the amount of data you regularly expect to encode
// However, the buffer will grow if needed
var buffer = context.allocator.buffer(capacity: 2048)
try self.encodeAndWrite(value, into: &buffer)
return HBResponse(
status: .ok,
headers: [
.contentType: "application/json; charset=utf-8",
],
body: .init(byteBuffer: buffer)
)
}
}

extension IkigaJSONDecoder: HBRequestDecoder {
public func decode<T>(_ type: T.Type, from request: HBRequest, context: some HBBaseRequestContext) async throws -> T where T : Decodable {
let data = try await request.body.collate(maxSize: context.maxUploadSize)
return try self.decode(T.self, from: data)
}
}
```

### In Vapor 4

Conform Ikiga to Vapor 4's protocols like so:
Expand Down
14 changes: 10 additions & 4 deletions Sources/IkigaJSON/Codable/JSONDecoder.swift
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import Foundation
import NIOConcurrencyHelpers
import NIO

enum JSONDecoderError: Error {
Expand Down Expand Up @@ -34,7 +35,7 @@ func date(from string: String) throws -> Date {
internal enum SuperCodingKey: String, CodingKey { case `super` }

/// These settings can be used to alter the decoding process.
public struct JSONDecoderSettings {
public struct JSONDecoderSettings: @unchecked Sendable {
public init() {}

/// This userInfo is accessible by the Decodable types that are being created
Expand Down Expand Up @@ -71,12 +72,17 @@ public struct JSONDecoderSettings {
}

/// A JSON Decoder that aims to be largely functionally equivalent to Foundation.JSONDecoder with more for optimization.
public final class IkigaJSONDecoder {
public final class IkigaJSONDecoder: Sendable {
private let settingsBox: NIOLockedValueBox<JSONDecoderSettings>

/// These settings can be used to alter the decoding process.
public var settings: JSONDecoderSettings
public var settings: JSONDecoderSettings {
get { settingsBox.withLockedValue { $0 } }
set { settingsBox.withLockedValue { $0 = newValue } }
}

public init(settings: JSONDecoderSettings = JSONDecoderSettings()) {
self.settings = settings
self.settingsBox = .init(settings)
}

/// Parses the Decodable type from an UnsafeBufferPointer.
Expand Down
8 changes: 4 additions & 4 deletions Sources/IkigaJSON/Codable/JSONEncoder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import NIO


/// These settings influence the encoding process.
public struct JSONEncoderSettings {
public struct JSONEncoderSettings: @unchecked Sendable {
public init() {}

/// The manner of expanding internal buffers for growing encoding demands
Expand Down Expand Up @@ -75,7 +75,7 @@ public struct JSONEncoderSettings {
}

/// The manner of expanding internal buffers for growing encoding demands
public enum ExpansionMode {
public enum ExpansionMode: Sendable {
/// For limited RAM environments
case smallest

Expand Down Expand Up @@ -113,7 +113,7 @@ final class SharedEncoderData {
/// Any data after the userCapacity is lost
func expand(to count: Int, usedCapacity size: Int) {
let new = UnsafeMutablePointer<UInt8>.allocate(capacity: count)
new.assign(from: pointer, count: size)
new.update(from: pointer, count: size)
pointer.deallocate()
totalSize = count
self.pointer = new
Expand Down Expand Up @@ -203,7 +203,7 @@ final class SharedEncoderData {


/// A JSON Encoder that aims to be largely functionally equivalent to Foundation.JSONEncoder.
public struct IkigaJSONEncoder {
public struct IkigaJSONEncoder: @unchecked Sendable {
public var userInfo = [CodingUserInfoKey : Any]()

/// These settings influence the encoding process.
Expand Down
4 changes: 2 additions & 2 deletions Sources/IkigaJSON/Codable/NilValueCodingStrategy.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
/// encoded values that are `nil`. Note that calling any variant of `encode()`
/// with an `Optional` type is always equivalent to calling `encodeNil()` if the
/// value is `nil`.
public enum NilValueEncodingStrategy: Equatable {
public enum NilValueEncodingStrategy: Equatable, Sendable {
/// Follow `Encodable`'s default behavior:
///
/// - `encodeIfPresent()`: Skip encoding for `nil` inputs.
Expand Down Expand Up @@ -31,7 +31,7 @@ public enum NilValueEncodingStrategy: Equatable {

/// Defines the possible strategies for determining whether to treat a missing key
/// or value requested as an optional type as `nil` when decoding.
public enum NilValueDecodingStrategy: Equatable {
public enum NilValueDecodingStrategy: Equatable, Sendable {
/// Follow `Decodable`'s default behavior:
///
/// - `decodeNil(forKey:)`: Throw `.keyNotFound` when the key is missing.
Expand Down
2 changes: 1 addition & 1 deletion Tests/IkigaJSONTests/JSONTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ final class IkigaJSONTests: XCTestCase {
let secretNumber: Decimal = 3.1414
let info = Info(secretNumber: secretNumber)
let jsonObject = try IkigaJSONEncoder().encodeJSONObject(from: info)
XCTAssertEqualWithAccuracy(jsonObject["secretNumber"].double!, 3.1414, accuracy: 0.001)
XCTAssertEqual(jsonObject["secretNumber"].double!, 3.1414, accuracy: 0.001)
let info2 = try IkigaJSONDecoder().decode(Info.self, from: jsonObject.data)
XCTAssertEqual(info, info2)
}
Expand Down

0 comments on commit a56bfba

Please sign in to comment.