Add bounded library snapshot strings
This commit is contained in:
@@ -27,6 +27,7 @@ import java.io.OutputStream
|
||||
object LibrarySnapshotCodec {
|
||||
const val MAGIC = "AUXSNAP"
|
||||
private const val SCHEMA_VERSION = 1
|
||||
private const val MAX_STRING_BYTES = 1024 * 1024
|
||||
private val MAGIC_BYTES = MAGIC.toByteArray(Charsets.US_ASCII)
|
||||
|
||||
data class Header(val magic: String, val schemaVersion: Int)
|
||||
@@ -51,4 +52,24 @@ object LibrarySnapshotCodec {
|
||||
}
|
||||
return Header(String(magic, Charsets.US_ASCII), schemaVersion)
|
||||
}
|
||||
|
||||
fun writeString(output: OutputStream, value: String) {
|
||||
val bytes = value.toByteArray(Charsets.UTF_8)
|
||||
require(bytes.size <= MAX_STRING_BYTES) { "Snapshot string exceeds byte limit" }
|
||||
val dataOutput = DataOutputStream(output)
|
||||
dataOutput.writeInt(bytes.size)
|
||||
dataOutput.write(bytes)
|
||||
dataOutput.flush()
|
||||
}
|
||||
|
||||
fun readString(input: InputStream): String {
|
||||
val dataInput = DataInputStream(input)
|
||||
val byteCount = dataInput.readInt()
|
||||
if (byteCount < 0 || byteCount > MAX_STRING_BYTES) {
|
||||
throw IOException("Invalid snapshot string length: $byteCount")
|
||||
}
|
||||
val bytes = ByteArray(byteCount)
|
||||
dataInput.readFully(bytes)
|
||||
return String(bytes, Charsets.UTF_8)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -73,4 +73,15 @@ class LibrarySnapshotCodecTest {
|
||||
LibrarySnapshotCodec.readHeader(ByteArrayInputStream(truncated))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun string_roundTrip_preservesUtf8Text() {
|
||||
val value = "Album 初音ミク 🎵"
|
||||
val output = ByteArrayOutputStream()
|
||||
|
||||
LibrarySnapshotCodec.writeString(output, value)
|
||||
val decoded = LibrarySnapshotCodec.readString(ByteArrayInputStream(output.toByteArray()))
|
||||
|
||||
assertEquals(value, decoded)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user