2017-10-21 23:59:16 +00:00
|
|
|
package com.github.michaelbull.result
|
2017-10-21 15:52:29 +00:00
|
|
|
|
|
|
|
/**
|
2017-10-21 20:19:21 +00:00
|
|
|
* Creates an [Iterator] over the possibly contained [value][Ok.value].
|
|
|
|
* The iterator yields one [value][Ok.value] if the [Result] is [Ok], otherwise throws [NoSuchElementException].
|
|
|
|
*
|
2017-10-21 15:52:29 +00:00
|
|
|
* - Rust: [Result.iter](https://doc.rust-lang.org/std/result/enum.Result.html#method.iter)
|
2017-10-21 20:19:21 +00:00
|
|
|
*
|
|
|
|
* @return [Iterator] over the possibly contained [value][Ok.value].
|
2017-10-21 15:52:29 +00:00
|
|
|
*/
|
|
|
|
fun <V, E> Result<V, E>.iterator(): Iterator<V> {
|
|
|
|
return ResultIterator(this)
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2017-10-21 20:19:21 +00:00
|
|
|
* Creates a [MutableIterator] over the possibly contained [value][Ok.value].
|
|
|
|
* The iterator yields one [value][Ok.value] if the [Result] is [Ok], otherwise throws [NoSuchElementException].
|
|
|
|
*
|
|
|
|
* - Rust: [Result.iter_mut](https://doc.rust-lang.org/std/result/enum.Result.html#method.iter_mut)
|
|
|
|
*
|
|
|
|
* @return The [MutableIterator] over the possibly contained [value][Ok.value].
|
2017-10-21 15:52:29 +00:00
|
|
|
*/
|
|
|
|
fun <V, E> Result<V, E>.mutableIterator(): MutableIterator<V> {
|
|
|
|
return ResultIterator(this)
|
|
|
|
}
|
|
|
|
|
|
|
|
private class ResultIterator<out V, out E>(private val result: Result<V, E>) : MutableIterator<V> {
|
2017-10-21 20:19:21 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* A flag indicating whether this [Iterator] has [yielded] its [Result].
|
|
|
|
*/
|
2017-10-21 15:52:29 +00:00
|
|
|
private var yielded = false
|
|
|
|
|
2017-10-21 20:19:21 +00:00
|
|
|
/**
|
|
|
|
* @return `true` if the [value][Ok.value] is not [yielded] and [Ok], `false` otherwise.
|
|
|
|
*/
|
2017-10-21 15:52:29 +00:00
|
|
|
override fun hasNext(): Boolean {
|
|
|
|
if (yielded) {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
return when (result) {
|
|
|
|
is Ok -> true
|
|
|
|
is Error -> false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-10-21 20:19:21 +00:00
|
|
|
/**
|
|
|
|
* @return The [Result's][Result] [value][Ok.value] if not [yielded] and [Ok].
|
|
|
|
* @throws NoSuchElementException if the [Result] is [yielded] or is not [Ok].
|
|
|
|
*/
|
2017-10-21 15:52:29 +00:00
|
|
|
override fun next(): V {
|
|
|
|
if (!yielded && result is Ok) {
|
|
|
|
yielded = true
|
|
|
|
return result.value
|
|
|
|
} else {
|
|
|
|
throw NoSuchElementException()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-10-21 20:19:21 +00:00
|
|
|
/**
|
|
|
|
* Flags this [Iterator] as having [yielded] its [Result].
|
|
|
|
*/
|
2017-10-21 15:52:29 +00:00
|
|
|
override fun remove() {
|
|
|
|
yielded = true
|
|
|
|
}
|
|
|
|
}
|