Use Cbor (#572)
* Track marshal/unmarshal performance * Use Cbor * Refine * Drop logging --------- Co-authored-by: GG Bond <whatever@tagkong.com>
This commit is contained in:
1 parent
9eb606810f
commit
c817726ab3
3 files changed
+9
-30
No files matched your search
@@ -1,34 +1,13 @@
|
||||
package com.hippo.ehviewer.client.parser
|
||||
|
||||
import com.hippo.ehviewer.client.parseAs
|
||||
import io.ktor.util.moveToByteArray
|
||||
import java.nio.ByteBuffer
|
||||
import okio.Buffer
|
||||
import okio.Source
|
||||
import okio.Timeout
|
||||
import okio.buffer
|
||||
|
||||
fun ByteBuffer.asSource() = object : Source {
|
||||
private val buffer = this@asSource.slice()
|
||||
private val len = buffer.capacity()
|
||||
|
||||
override fun close() = Unit
|
||||
|
||||
override fun read(sink: Buffer, byteCount: Long): Long {
|
||||
if (buffer.position() == len) return -1
|
||||
val pos = buffer.position()
|
||||
val newLimit = (pos + byteCount).toInt().coerceAtMost(len)
|
||||
buffer.limit(newLimit)
|
||||
return sink.write(buffer).toLong()
|
||||
}
|
||||
|
||||
override fun timeout() = Timeout.NONE
|
||||
}
|
||||
import kotlinx.serialization.cbor.Cbor
|
||||
import kotlinx.serialization.decodeFromByteArray
|
||||
|
||||
inline fun <reified T> unmarshalParsingAs(body: ByteBuffer, parser: (ByteBuffer, Int) -> Int): T {
|
||||
// We want to use cbor as it have smaller output size
|
||||
// But we would rather reuse allocated ByteArrays (i.e. decode with okio Buffer)
|
||||
val jsonBytes = parser(body, body.limit())
|
||||
body.clear()
|
||||
body.limit(jsonBytes)
|
||||
return body.asSource().buffer().use { it.parseAs<T>() }
|
||||
val cborBytes = parser(body, body.limit())
|
||||
body.limit(cborBytes)
|
||||
val array = body.moveToByteArray()
|
||||
return Cbor.decodeFromByteArray<T>(array)
|
||||
}
|
||||
@@ -15,7 +15,7 @@ tl = "0.7"
|
||||
log = "0.4"
|
||||
android_logger = { default-features = false, version = "0.13" }
|
||||
once_cell = { default-features = false, version = "1.19" }
|
||||
serde_json = "1.0"
|
||||
serde_cbor = "0.11"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
|
||||
[profile.release]
|
||||
|
||||
@@ -91,7 +91,7 @@ where
|
||||
let slice = slice_from_raw_parts_mut(ptr, 0x80000);
|
||||
Cursor::new(&mut *slice)
|
||||
};
|
||||
serde_json::to_writer(&mut cursor, &value).unwrap();
|
||||
serde_cbor::to_writer(&mut cursor, &value).unwrap();
|
||||
cursor.position() as i32
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user