Skip to content

Conversation

@fabianfett
Copy link
Collaborator

Motivation

Currently the LambdaCodableEncoder is based on the method signature defined by NIOFoundationCompat. But this might not be the most efficient API.

The current API looks like this:

public protocol LambdaCodableEncoder {
    func encode<T: Encodable>(_ value: T, into buffer: inout ByteBuffer) throws
}

The problem here is that the ByteBuffer has already been created with a fixed size by the LambdaHandler default implementation:

/// Implementation of  `Out` to `ByteBuffer` encoding
public extension EventLoopLambdaHandler where Out: Encodable {
    func encode(allocator: ByteBufferAllocator, value: Out) throws -> ByteBuffer? {
        // nio will resize the buffer if necessary
        var buffer = allocator.buffer(capacity: 1024)
        try self.encoder.encode(value, into: &buffer)
        return buffer
    }
}

Other encoders might be able to create a ByteBuffer of the correct size right the beginning though.

extension PureSwiftJSONCoding.JSONEncoder: LambdaCodableEncoder {
    public func encode<T>(_ value: T, into byteBuffer: ByteBuffer) throws -> ByteBuffer where T : Encodable {
        let bytes = try self.encode(value) // byte buffer could be created to the right size right away
        buffer.writeBytes(bytes)
        return buffer
    }
}

Changes

This PR changes the LambdaCodableEncoder protocol to hand over the ByteBufferAllocator to the LambdaCodableEncoder instead of creating a ByteBuffer for the encoder right away. For this reason encoders can size the needed ByteBuffer correctly from the very beginning. The example from above could look like this:

extension PureSwiftJSONCoding.JSONEncoder: LambdaCodableEncoder {
    public func encode<T>(_ value: T, using allocator: ByteBufferAllocator) throws -> ByteBuffer where T : Encodable {
        let bytes = try self.encode(value)
        var buffer = allocator.buffer(capacity: bytes.count)
        buffer.writeBytes(bytes)
        return buffer
    }
}

@fabianfett fabianfett requested a review from tomerd April 25, 2020 12:31
@fabianfett fabianfett force-pushed the make-LambdaCodableEncoder-less-Foundation-biased branch from f2851e0 to 733b0d8 Compare April 25, 2020 12:32
@tomerd tomerd merged commit 2297929 into master Apr 27, 2020
@fabianfett fabianfett deleted the make-LambdaCodableEncoder-less-Foundation-biased branch April 28, 2020 06:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants