Skip to content

Commit

Permalink
Conform CircularBuffer to ExpressibleByArrayLiteral
Browse files Browse the repository at this point in the history
Motivation:
Making CircularBuffer conform to ExpressibleByArrayLiteral enables
directly initializing it from an array literal, which can sometimes
make its use simpler and more natural, for instance:
foo.circularBuffer = [1,2,3] // vs `= CircularBuffer([1,2,3])`
Foo(circularBuffer: [a, b, c]) // vs `: CircularBuffer([a, b, c])`
This is consistent with other standard Swift collections, such as
Set, as well as existing NIO types (eg: WebSocketMaskingKey).

Modifications:
Extend CircularBuffer to conform to ExpressibleByArrayLiteral

Result:
CircularBuffer can now be initialized from array literals
  • Loading branch information
PopFlamingo committed Aug 11, 2019
1 parent d30aa6a commit b0810df
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
6 changes: 6 additions & 0 deletions Sources/NIO/CircularBuffer.swift
Expand Up @@ -706,3 +706,9 @@ extension CircularBuffer: Hashable where Element: Hashable {
}
}
}

extension CircularBuffer: ExpressibleByArrayLiteral {
public init(arrayLiteral elements: Element...) {
self.init(elements)
}
}
13 changes: 13 additions & 0 deletions Tests/NIOTests/CircularBufferTests.swift
Expand Up @@ -971,4 +971,17 @@ class CircularBufferTests: XCTestCase {
XCTAssertEqual(Set([prependBuff,appendBuff]).count, 1)
}

func testArrayLiteralInit() {
let empty: CircularBuffer<Int> = []
XCTAssert(empty.isEmpty)

let increasingInts: CircularBuffer = [1, 2, 3, 4, 5]
XCTAssert(increasingInts.count == 5)
XCTAssert(zip(increasingInts, 1...5).allSatisfy(==))

let someIntsArray = [-9, 384, 2, 10, 0, 0, 0]
let someInts: CircularBuffer = [-9, 384, 2, 10, 0, 0, 0]
XCTAssert(someInts.count == 7)
XCTAssert(zip(someInts, someIntsArray).allSatisfy(==))
}
}

0 comments on commit b0810df

Please sign in to comment.