Remove incorrect assertion in MarkedCircularBuffer.popFirst (#1627)

Motivation:

`MarkedCircularBuffer.popFirst()` asserts that the backing buffer should
contain more than zero elements yet `popFirst()` allows `nil` to be
returned when there is no value to return.

Modifications:

- Move the assertion from `popFirst() -> Element?` to `removeFirst() -> Element`
- Test for `popFirst()`

Result:

- We can safely call `popFirst()` on an empty `MarkedCircularBuffer` in
  debug mode.
This commit is contained in:
George Barnett 2020-09-03 14:06:14 +01:00 committed by GitHub
parent 08c7821ba3
commit 98721c75b0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 20 additions and 6 deletions

View File

@ -41,12 +41,12 @@ public struct MarkedCircularBuffer<Element>: CustomStringConvertible {
/// Removes the first element from the buffer.
@inlinable
public mutating func removeFirst() -> Element {
assert(self._buffer.count > 0)
return self.popFirst()!
}
@inlinable
public mutating func popFirst() -> Element? {
assert(self._buffer.count > 0)
if let markedIndexOffset = self._markedIndexOffset {
if markedIndexOffset > 0 {
self._markedIndexOffset = markedIndexOffset - 1

View File

@ -36,6 +36,7 @@ extension MarkedCircularBufferTests {
("testCount", testCount),
("testSubscript", testSubscript),
("testIsEmpty", testIsEmpty),
("testPopFirst", testPopFirst),
]
}
}

View File

@ -123,11 +123,24 @@ class MarkedCircularBufferTests: XCTestCase {
buf.append(i)
}
XCTAssertFalse(buf.isEmpty)
let _ = buf.removeFirst()
let _ = buf.removeFirst()
let _ = buf.removeFirst()
let _ = buf.removeFirst()
XCTAssertEqual(buf.removeFirst(), 1)
XCTAssertEqual(buf.removeFirst(), 2)
XCTAssertEqual(buf.removeFirst(), 3)
XCTAssertEqual(buf.removeFirst(), 4)
XCTAssertTrue(buf.isEmpty)
}
func testPopFirst() throws {
var buf = MarkedCircularBuffer<Int>(initialCapacity: 4)
for i in 1...4 {
buf.append(i)
}
XCTAssertFalse(buf.isEmpty)
XCTAssertEqual(buf.popFirst(), 1)
XCTAssertEqual(buf.popFirst(), 2)
XCTAssertEqual(buf.popFirst(), 3)
XCTAssertEqual(buf.popFirst(), 4)
XCTAssertNil(buf.popFirst())
XCTAssertTrue(buf.isEmpty)
}
}