Skip to content
This repository has been archived by the owner on Jan 26, 2025. It is now read-only.

Commit

Permalink
Add safeToKString
Browse files Browse the repository at this point in the history
  • Loading branch information
toasterofbread committed Mar 13, 2024
1 parent 0e0cfaf commit f38d098
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
7 changes: 4 additions & 3 deletions src/commonMain/kotlin/cinterop/mpv/MpvClientImpl.kt
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import spms.server.SpMs
import spms.socketapi.shared.SpMsPlayerRepeatMode
import spms.socketapi.shared.SpMsPlayerState
import kotlin.math.roundToInt
import cinterop.utils.safeToKString

private const val URL_PREFIX: String = "spmp://"

Expand Down Expand Up @@ -269,7 +270,7 @@ abstract class MpvClientImpl(headless: Boolean = true): LibMpvClient(headless) {
MPV_EVENT_PROPERTY_CHANGE -> {
val data: mpv_event_property = event.data.pointedAs()

when (data.name?.toKString()) {
when (data.name?.safeToKString()) {
"core-idle" -> {
val playing: Boolean = !data.data.pointedAs<BooleanVar>().value
onEvent(SpMsPlayerEvent.PropertyChanged("is_playing", JsonPrimitive(playing)), clientless = true)
Expand All @@ -280,14 +281,14 @@ abstract class MpvClientImpl(headless: Boolean = true): LibMpvClient(headless) {
MPV_EVENT_HOOK -> {
val data: mpv_event_hook = event.data.pointedAs()
launch {
onMpvHook(data.name?.toKString(), data.id)
onMpvHook(data.name?.safeToKString(), data.id)
}
}

MPV_EVENT_LOG_MESSAGE -> {
if (SpMs.logging_enabled) {
val message: mpv_event_log_message = event.data.pointedAs()
SpMs.log("From mpv (${message.prefix?.toKString()}): ${message.text?.toKString()}")
SpMs.log("From mpv (${message.prefix?.safeToKString()}): ${message.text?.safeToKString()}")
}
}
}
Expand Down
17 changes: 17 additions & 0 deletions src/commonMain/kotlin/cinterop/utils/safeToKString.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
@file:Suppress("INVISIBLE_MEMBER", "INVISIBLE_REFERENCE")
package cinterop.utils

import kotlinx.cinterop.*

fun CPointer<ByteVar>.safeToKString(): String {
val nativeBytes = this

var length = 0
while (nativeBytes[length] != 0.toByte()) {
++length
}

val bytes = ByteArray(length)
nativeMemUtils.getByteArray(nativeBytes.pointed, bytes, length)
return bytes.decodeToString()
}

0 comments on commit f38d098

Please sign in to comment.