org.whispersystems.signalservice.api.util.OptionalUtil.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of signal-service-java Show documentation
Show all versions of signal-service-java Show documentation
Signal Service communication library for Java, unofficial fork
package org.whispersystems.signalservice.api.util
import okio.ByteString
import java.util.Optional
object OptionalUtil {
@JvmStatic
@SafeVarargs
fun or(vararg optionals: Optional): Optional {
return optionals.firstOrNull { it.isPresent } ?: Optional.empty()
}
@JvmStatic
fun byteArrayEquals(a: Optional, b: Optional): Boolean {
return if (a.isPresent != b.isPresent) {
false
} else if (a.isPresent) {
a.get().contentEquals(b.get())
} else {
true
}
}
@JvmStatic
fun byteArrayHashCode(bytes: Optional): Int {
return if (bytes.isPresent) {
bytes.get().contentHashCode()
} else {
0
}
}
@JvmStatic
fun absentIfEmpty(value: String?): Optional {
return if (value.isNullOrEmpty()) {
Optional.empty()
} else {
Optional.of(value)
}
}
@JvmStatic
fun absentIfEmpty(value: ByteString?): Optional {
return if (value == null || value.size == 0) {
Optional.empty()
} else {
Optional.of(value.toByteArray())
}
}
@JvmStatic
fun emptyIfListEmpty(list: List?): Optional> {
return list.asOptional()
}
fun E?.asOptional(): Optional {
return Optional.ofNullable(this)
}
fun List?.asOptional(): Optional> {
return Optional.ofNullable(this?.takeIf { it.isNotEmpty() })
}
fun String?.emptyIfStringEmpty(): Optional {
return absentIfEmpty(this)
}
}