Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use contracts for isPresent #950

Merged
merged 2 commits into from
Aug 21, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import kotlinx.serialization.SerializationException
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.contract
import kotlin.jvm.JvmInline

@Serializable(with = OmissableSerializer::class)
Expand Down Expand Up @@ -70,9 +72,21 @@ class OmissableSerializer<T>(private val childSerializer: KSerializer<T>) : KSer
}
}

fun <T : Any> Omissible<T>.isPresent() = this is Omissible.Present
@OptIn(ExperimentalContracts::class)
fun <T : Any> Omissible<T>.isPresent(): Boolean {
contract {
returns(true) implies (this@isPresent is Omissible.Present<T>)
}
return this is Omissible.Present
}

fun <T : Any> Omissible<T>.isOmitted() = this is Omissible.Omitted
@OptIn(ExperimentalContracts::class)
fun <T : Any> Omissible<T>.isOmitted(): Boolean {
contract {
returns(true) implies (this@isOmitted is Omissible.Omitted<T>)
}
return this is Omissible.Omitted
}

fun <T : Any?> Omissible<T>.takeIfPresent(predicate: (T) -> Boolean = { true }) =
if (this is Omissible.Present) value.takeIf(predicate) else null
Expand Down