Skip to content

Commit

Permalink
Issue-2734 - Create static function for padding
Browse files Browse the repository at this point in the history
  • Loading branch information
ali-ahsan-ali committed Aug 6, 2024
1 parent 8a05b6a commit 3c4c678
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 1 deletion.
9 changes: 9 additions & 0 deletions Sources/NIOCore/ByteBuffer-core.swift
Original file line number Diff line number Diff line change
Expand Up @@ -893,6 +893,7 @@ public struct ByteBuffer {
/// - Returns: Bool indicating whether the buffer capacity has been shrunk to the desiredCapacity.
@inlinable
@discardableResult public mutating func shrinkBufferCapacity(to desiredCapacity: Int) -> Bool {
let desiredCapacity = ByteBuffer.addPaddingTo(desiredCapacity)
guard desiredCapacity < capacity, desiredCapacity > readableBytes else {
return false
}
Expand All @@ -903,6 +904,14 @@ public struct ByteBuffer {

return true
}

/// Returns size of buffer capacity with optimal padding
/// - Parameter initialCapacity: Capacity that needs expansion with padding
/// - Returns: Capacity with calculated padding
@inlinable
static func addPaddingTo(_ initialCapacity: Int) -> Int {
initialCapacity == 0 ? 0 : initialCapacity.nextPowerOf2()
}

/// The reader index or the number of bytes previously read from this `ByteBuffer`. `readerIndex` is `0` for a
/// newly allocated `ByteBuffer`.
Expand Down
2 changes: 1 addition & 1 deletion Sources/NIOCore/Codec.swift
Original file line number Diff line number Diff line change
Expand Up @@ -797,7 +797,7 @@ public final class MessageToByteHandler<Encoder: MessageToByteEncoder>: ChannelO

public init(_ encoder: Encoder, desiredBufferCapacity: Int) {
self.encoder = encoder
self.desiredBufferCapacity = desiredBufferCapacity.nextPowerOf2()
self.desiredBufferCapacity = desiredBufferCapacity
}

public init(_ encoder: Encoder) {
Expand Down
5 changes: 5 additions & 0 deletions Tests/NIOCoreTests/ByteBufferTest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1891,6 +1891,11 @@ class ByteBufferTest: XCTestCase {
XCTAssertTrue(buffer.shrinkBufferCapacity(to: desiredCapacity))
XCTAssertEqual(buffer.capacity, 1024)
}

func testExpansionOfCapacityWithPadding() throws {
XCTAssertEqual(ByteBuffer.addPaddingTo(12), 16)
XCTAssertEqual(ByteBuffer.addPaddingTo(0), 0)
}

func testDumpBytesFormat() throws {
self.buf.clear()
Expand Down

0 comments on commit 3c4c678

Please sign in to comment.