mirror of
https://github.com/jellyfin/jellyfin-sdk-kotlin.git
synced 2025-02-17 06:37:29 +00:00
Add String.toUUID and String.toUUIDOrNull functions (#171)
* Add String.toUUID and String.toUUIDOrNull functions * Improve UUID functions kdoc
This commit is contained in:
parent
5761359226
commit
d768b89c82
@ -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()
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user