Conform CircularBuffer to ExpressibleByArrayLiteral (#1102)

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
This commit is contained in:
Trevör 2019-08-12 16:44:34 +02:00 committed by Cory Benfield
parent dcb3099b77
commit a28a8668b5
3 changed files with 20 additions and 0 deletions

View File

@ -706,3 +706,9 @@ extension CircularBuffer: Hashable where Element: Hashable {
}
}
}
extension CircularBuffer: ExpressibleByArrayLiteral {
public init(arrayLiteral elements: Element...) {
self.init(elements)
}
}

View File

@ -75,6 +75,7 @@ extension CircularBufferTests {
("testModify", testModify),
("testEquality", testEquality),
("testHash", testHash),
("testArrayLiteralInit", testArrayLiteralInit),
]
}
}

View File

@ -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]
XCTAssertEqual(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]
XCTAssertEqual(someInts.count, 7)
XCTAssert(zip(someInts, someIntsArray).allSatisfy(==))
}
}