diff --git a/tribune-core/src/main/kotlin/com/sksamuel/tribune/core/nulls.kt b/tribune-core/src/main/kotlin/com/sksamuel/tribune/core/nulls.kt index ffc53f3..f69cfcf 100644 --- a/tribune-core/src/main/kotlin/com/sksamuel/tribune/core/nulls.kt +++ b/tribune-core/src/main/kotlin/com/sksamuel/tribune/core/nulls.kt @@ -42,7 +42,7 @@ fun Parser.notNull(ifNull: () -> E): Parser = Parser { input: I -> this@notNull.parse(input).flatMap { it?.right() ?: ifNull().leftNel() } } /** - * Maps a [Parser] to never fail, by replacing any failing values with null. + * Transforms a [Parser] to never fail, by replacing any failing values with null. */ fun Parser.failAsNull(): Parser = Parser { input: I -> this@failAsNull.parse(input).fold({ Either.Right(null) }, { it.right() }) } diff --git a/tribune-core/src/main/kotlin/com/sksamuel/tribune/core/strings/lengths.kt b/tribune-core/src/main/kotlin/com/sksamuel/tribune/core/strings/lengths.kt index 98eb7b6..237b983 100644 --- a/tribune-core/src/main/kotlin/com/sksamuel/tribune/core/strings/lengths.kt +++ b/tribune-core/src/main/kotlin/com/sksamuel/tribune/core/strings/lengths.kt @@ -9,7 +9,7 @@ import com.sksamuel.tribune.core.flatMap /** * Narrows an existing String -> String [Parser] by enforcing an exact length on the input string. * - * For strings which have length that differs than the given [len] arguments, an invalid is + * For strings which have length that differs than the given [len] arguments, a failure is * returned with the error message generated by [ifError]. * * @param len the max length, inclusive @@ -25,6 +25,27 @@ fun Parser.length(len: Int, ifError: (String) -> E): Parser } } +/** + * Narrows an existing String -> String [Parser] by enforcing an exact length on the input string. + * + * For strings which have length that differs than the given [len] arguments, a failure is + * returned with the error message generated by [ifError]. + * + * @param len the max length, inclusive + * @param ifError the error generating function + * + * @return valid if the input string is less than or equal to [len] or an invalid otherwise. + */ +@JvmName("lengthOrNull") +fun Parser.length(len: Int, ifError: (String) -> E): Parser = + flatMap { + when { + it == null -> Either.Right(null) + it.length == len -> it.right() + else -> ifError(it).leftNel() + } + } + /** * Maps a string producing [Parser] by enforcing a length on the string. *