Add String.toUUID and String.toUUIDOrNull functions (#171)

* Add String.toUUID and String.toUUIDOrNull functions

* Improve UUID functions kdoc
This commit is contained in:
Niels van Velzen 2021-01-25 22:27:23 +01:00 committed by GitHub
parent 5761359226
commit d768b89c82
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -8,23 +8,35 @@ import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import java.util.*
private val UUID_REGEX = "^([a-z\\d]{8})([a-z\\d]{4})([a-z\\d]{4})([a-z\\d]{4})([a-z\\d]{12})\$".toRegex()
/**
* A UUID serializer that supports the GUIDs without dashes from the Jellyfin API
* Convert string to UUID. Accepts simple and hyphenated notations.
* @throws IllegalArgumentException if string is not a valid UUID.
*/
public fun String.toUUID(): UUID = UUID.fromString(replace(UUID_REGEX, "$1-$2-$3-$4-$5"))
/**
* Convert string to UUID or null if the string is not an UUID.
* Accepts simple and hyphenated notations.
*/
public fun String.toUUIDOrNull(): UUID? = try {
toUUID()
} catch (err: IllegalArgumentException) {
null
}
/**
* A UUID serializer that supports the GUIDs without dashes from the Jellyfin API.
*/
public class UUIDSerializer : KSerializer<UUID> {
override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("UUID", PrimitiveKind.STRING)
override fun deserialize(decoder: Decoder): UUID {
val uuid = decoder.decodeString()
return UUID.fromString(uuid.replace(UUID_REGEX, "$1-$2-$3-$4-$5"))
return decoder.decodeString().toUUID()
}
override fun serialize(encoder: Encoder, value: UUID) {
encoder.encodeString(value.toString())
}
private companion object {
private val UUID_REGEX = "^([a-z\\d]{8})([a-z\\d]{4})([a-z\\d]{4})([a-z\\d]{4})([a-z\\d]{12})\$".toRegex()
}
}