FrontStack: Ensure that claimed invariant is maintained (#6960)

* FrontStack: Ensure that claimed invariant is maintained

The documentation of `FrontStack` claims that the head of the
`FQPrepend` is never empty but there's a way to violate this claimed
invariant.

This PR makes sure the invariant is maintained and then uses the
invariant to remove a redundant `else`-branch.

CHANGELOG_BEGIN
CHANGELOG_END

* Remove initials from NOTE

CHANGELOG_BEGIN
CHANGELOG_END
This commit is contained in:
Martin Huschenbett 2020-08-03 13:39:04 +02:00 committed by GitHub
parent 6a678c5733
commit de3f593399
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -76,10 +76,9 @@ final class FrontStack[+A] private (fq: FQ[A], val length: Int) {
case FQPrepend(head, tail) =>
if (head.length > 1) {
Some((head.head, new FrontStack(FQPrepend(head.tail, tail), length - 1)))
} else if (head.length > 0) {
Some((head.head, new FrontStack(tail, length - 1)))
} else {
throw new RuntimeException(s"FrontStack had FQPrepend with non-empty head: $head")
// NOTE: We maintain the invariant that `head` is never empty.
Some((head.head, new FrontStack(tail, length - 1)))
}
}
} else {
@ -151,7 +150,11 @@ object FrontStack extends FrontStackInstances {
def empty[A]: FrontStack[A] = emptySingleton
def apply[A](xs: ImmArray[A]): FrontStack[A] =
new FrontStack(FQPrepend(xs, FQEmpty), length = xs.length)
if (xs.length > 0) {
new FrontStack(FQPrepend(xs, FQEmpty), length = xs.length)
} else {
empty
}
def apply[T](element: T): FrontStack[T] =
new FrontStack(FQCons(element, FQEmpty), length = 1)