Rust + NDK on Android, Part 11 of 15.This series teaches Android developers how to ship Rust in production apps, no prior Rust required. Hub: Rust on Android: How to Use It, How to Debug It, and Why It's Worth It. Previous: Low-Latency Audio DSP with Rust: AAudio and Oboe from a Rust Core. Next: Cryptography with Rust on Android: ring and RustCrypto Instead of Rolling Your Own.
Parsing JSON in Rust on Android pays off under one condition: the parsed objects never cross back into Kotlin. Parse a multi-megabyte export with serde, aggregate it on the Rust side, and return one small summary record, and the boundary costs you a single struct. Parse it in Rust and then marshal fifty thousand objects back into Kotlin, and you have paid for serde plus the expensive half of kotlinx.serialization anyway: allocating the object graph on the JVM heap.
This part builds the series’ rust/parser crate around that rule: serde derive structs for a transactions export, streaming CSV and NDJSON aggregation that holds one record in memory at a time, and a UniFFI boundary returning a compact summary Kotlin receives as a plain data class. It also explains why there is no benchmark table yet, and how I will produce the numbers.
This assumes the toolchain from Part 1 and the UniFFI wiring from Part 3. Part 6 built the cost model for crossing the boundary; this part is its advice applied: make the chunky call.
Key Takeaways
- Serde’s derive gives you the @Serializable experience with stricter checks: the generated code is type-checked at compile time, and a field that does not match the data is a typed runtime error naming the field, never a silent null.
- The win condition is aggregation. Return one UniFFI record across the boundary instead of a Vec of parsed rows, the chunky-call rule from Part 6.
- Streaming through the csv crate’s record iterator or serde_json’s StreamDeserializer keeps memory flat no matter how large the file grows.
- For ordinary API payloads, kotlinx.serialization stays the right tool. This post ships methodology instead of invented numbers; measurements land when the companion module does.
When does it pay to parse JSON in Rust on Android?
Not for your API responses. A payload of a few kilobytes deserialized with kotlinx.serialization or Moshi parses comfortably within a frame, with zero FFI in your build. If that is your whole parsing story, close this tab and keep the build simple.
The problem class is files. A bank statement export the user imports, two seasons of cached sports data for offline mode, an analytics log your app has been appending to for months. These arrive as multi-megabyte JSON or CSV, and they hurt on the JVM in a specific way: one object allocated per row plus one per nested field, the whole graph on the heap next to the raw text, and the collection pressure landing while your UI tries to hold a frame budget of roughly 16 ms at 60 Hz (Android vitals, slow rendering).
Kotlin is not helpless here, and pretending otherwise would be selling you something. Moshi reads token by token over Okio, and kotlinx.serialization has an experimental decodeToSequence for streaming from an InputStream (kotlinx.serialization API docs). What neither can change is the allocation model: every row still becomes JVM objects for the garbage collector to trace and sweep. Serde deserializes into plain structs with no collector, and when the aggregation happens on the Rust side too, the JVM heap never sees the dataset at all.
If heavy parsing were your only native need, adding rustup, the NDK and a second language to fix one screen would be a hard sell, and I said as much in the hub post. By Part 11 the toolchain is already in your build, so the marginal cost is one more crate in the workspace.
One manifest: serde, csv, and UniFFI
The crate lives at rust/parser in the series workspace. The manifest at rust/parser/Cargo.toml:
[package]
name = "parser"
version = "0.1.0"
edition = "2021"
[lib]
crate-type = ["cdylib"]
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"
csv = "1"
thiserror = "2"
uniffi = "0.29"
Each dependency has a job. serde with the derive feature is the code generator, the ksp step of this world, except it runs inside the normal compile and its output is type-checked like everything else (serde.rs). serde_json and csv are format front ends; serde itself is format agnostic, which is why one Transaction struct will feed both parsers below. And uniffi 0.29 is the boundary, wired into the Gradle build exactly as in Part 3.
Serde structs: @Serializable with a stricter compiler
The row type sits at the top of rust/parser/src/lib.rs, together with the scaffolding macro every UniFFI crate needs once:
use std::collections::BTreeMap;
use std::fs::File;
use std::io::BufReader;
use serde::Deserialize;
uniffi::setup_scaffolding!();
/// One row of the export. Serde fills this the way kotlinx.serialization
/// fills an @Serializable data class, with mismatches surfacing as
/// typed errors naming the field, not silent nulls.
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Transaction {
pub id: String,
pub posted_at: String,
pub amount_cents: i64,
pub currency: String,
pub category: String,
}
If you write kotlinx.serialization, you already know this struct. #[derive(Deserialize)] is @Serializable, and #[serde(rename_all = "camelCase")] does the job of @SerialName for the whole struct at once, so posted_at binds to postedAt in the data. A missing field is a typed error naming the field and position, not an exception from somewhere inside a decoder. Nullable fields become Option<String>, and #[serde(default)] fills absent values like default parameters in a data class.
The part with no Kotlin equivalent: the same struct drives the CSV parser. The csv crate matches header names against the same serialized names, so an export whose header row reads id,postedAt,amountCents,currency,category deserializes into Transaction with no extra annotations.
Return the answer, not the objects
Now the boundary types, still in rust/parser/src/lib.rs. Two records for the result and one error enum:
#[derive(Debug, Clone, uniffi::Record)]
pub struct CategoryTotal {
pub category: String,
pub rows: u64,
pub cents: i64,
}
#[derive(Debug, Clone, uniffi::Record)]
pub struct TxSummary {
pub rows: u64,
pub total_cents: i64,
pub largest_cents: i64,
pub categories: Vec<CategoryTotal>,
}
#[derive(Debug, thiserror::Error, uniffi::Error)]
pub enum ParseError {
#[error("could not read {path}: {reason}")]
Io { path: String, reason: String },
#[error("bad record {row}: {reason}")]
Malformed { row: u64, reason: String },
}
The records become Kotlin data classes, as covered in Part 3. The error enum becomes a sealed ParseException hierarchy with the variant fields as properties, the exception mapping Part 8 built by hand, generated for free.
Why a summary and not Vec<Transaction>? UniFFI moves compound values across the FFI by serializing them into a byte buffer and rebuilding them on the other side (UniFFI docs). Returning eighty thousand rows means eighty thousand records lowered in Rust and eighty thousand objects allocated in Kotlin, the exact storm we moved to Rust to avoid. The aggregation lives here instead:
#[derive(Default)]
struct Accumulator {
rows: u64,
total_cents: i64,
largest_cents: i64,
categories: BTreeMap<String, (u64, i64)>,
}
impl Accumulator {
fn push(&mut self, tx: &Transaction) {
self.rows += 1;
self.total_cents += tx.amount_cents;
self.largest_cents = self.largest_cents.max(tx.amount_cents);
let entry = self.categories.entry(tx.category.clone()).or_insert((0, 0));
entry.0 += 1;
entry.1 += tx.amount_cents;
}
fn finish(self) -> TxSummary {
TxSummary {
rows: self.rows,
total_cents: self.total_cents,
largest_cents: self.largest_cents,
categories: self
.categories
.into_iter()
.map(|(category, (rows, cents))| CategoryTotal { category, rows, cents })
.collect(),
}
}
}
/// Parse a whole JSON array already held in memory, for payloads that
/// arrived as a network body rather than a file.
#[uniffi::export]
pub fn summarize_json(payload: String) -> Result<TxSummary, ParseError> {
let transactions: Vec<Transaction> =
serde_json::from_str(&payload).map_err(|e| ParseError::Malformed {
row: e.line() as u64,
reason: e.to_string(),
})?;
let mut acc = Accumulator::default();
for tx in &transactions {
acc.push(tx);
}
Ok(acc.finish())
}
summarize_json is the simple case: the payload crosses once as a string, becomes a Vec on the Rust heap, and only TxSummary comes back. The string crossing is not free, Part 6 built the cost model for it, but it happens once. For data already on disk we can skip crossing the payload entirely.
Streaming CSV and NDJSON in constant memory
For files, Kotlin sends a path and Rust opens the file itself. The CSV version streams: the iterator deserializes one record, the accumulator folds it, the record drops before the next is read. Memory stays flat whether the file holds a thousand rows or ten million. Also in rust/parser/src/lib.rs:
/// Stream a CSV export from disk. One record is alive at a time,
/// so memory use does not grow with file size.
#[uniffi::export]
pub fn summarize_csv(path: String) -> Result<TxSummary, ParseError> {
let mut reader = csv::Reader::from_path(&path).map_err(|e| ParseError::Io {
path: path.clone(),
reason: e.to_string(),
})?;
let mut acc = Accumulator::default();
for (i, record) in reader.deserialize::<Transaction>().enumerate() {
let tx = record.map_err(|e| ParseError::Malformed {
row: i as u64 + 1,
reason: e.to_string(),
})?;
acc.push(&tx);
}
Ok(acc.finish())
}
JSON gets the same shape when the export is newline delimited, one JSON object per line. serde_json’s StreamDeserializer walks a sequence of whitespace-separated values from a reader, which covers NDJSON exactly (serde_json docs):
/// Stream a newline-delimited JSON export from disk with the same
/// constant-memory profile as the CSV path.
#[uniffi::export]
pub fn summarize_ndjson(path: String) -> Result<TxSummary, ParseError> {
let file = File::open(&path).map_err(|e| ParseError::Io {
path: path.clone(),
reason: e.to_string(),
})?;
let stream = serde_json::Deserializer::from_reader(BufReader::new(file))
.into_iter::<Transaction>();
let mut acc = Accumulator::default();
for (i, item) in stream.enumerate() {
let tx = item.map_err(|e| ParseError::Malformed {
row: i as u64 + 1,
reason: e.to_string(),
})?;
acc.push(&tx);
}
Ok(acc.finish())
}
A giant top-level JSON array does not stream through StreamDeserializer, because the brackets make it one value. Either take the summarize_json route and hold the Vec in Rust memory, still far cheaper than the JVM heap, or write a custom serde visitor that folds elements as they parse. If you control the exporter, emit NDJSON and the problem disappears.
The Kotlin side is one suspend function
The generated bindings expose summarizeCsv, summarizeJson and summarizeNdjson as top-level functions in the uniffi.parser package, exactly as Part 3 set up. The wrapper at app/src/main/java/dev/davthecoder/rustseries/parsing/TransactionReports.kt:
package dev.davthecoder.rustseries.parsing
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import uniffi.parser.ParseException
import uniffi.parser.TxSummary
import uniffi.parser.summarizeCsv
sealed interface ReportState {
data class Ready(val summary: TxSummary) : ReportState
data class Failed(val message: String) : ReportState
}
class TransactionReports {
suspend fun buildReport(csvPath: String): ReportState =
withContext(Dispatchers.IO) {
try {
ReportState.Ready(summarizeCsv(csvPath))
} catch (e: ParseException.Io) {
ReportState.Failed("Could not read ${e.path}")
} catch (e: ParseException.Malformed) {
ReportState.Failed("Bad record at row ${e.row}: ${e.reason}")
}
}
}
Three notes. The exported functions block their calling thread for the length of the parse, so withContext(Dispatchers.IO) is not decoration; call this on the main thread and you have moved the jank, not removed it. The typed catches work because UniFFI turned ParseError into a sealed exception hierarchy with path, row and reason as real properties. And rows: u64 arrives as a Kotlin ULong, since UniFFI maps unsigned integers onto Kotlin’s unsigned types (UniFFI docs); use i64 if you would rather hand your UI a plain Long.
One Android wrinkle: summarizeCsv wants a real filesystem path, and a content:// URI from the Storage Access Framework is not one. Copy the picked document into cacheDir once and pass that path. The zero-copy alternative, handing Rust a detached file descriptor, is Part 6 territory; for a once-per-import parse, the copy is fine and simple.
Where the benchmark numbers will come from
This is where a chart should sit, and it stays empty on purpose. The series prints measurements, and the rust/parser module has not shipped yet. What I can give you now is the methodology, so the numbers mean something when they land.
The harness follows the rules from Part 5: release builds with R8, a named physical mid-range device, warm-up iterations before anything is recorded, medians of repeated runs rather than best case. The dataset is generated deterministically by a script committed next to the crate and swept from a few hundred kilobytes to tens of megabytes, so anyone can regenerate the identical input.
Three configurations get measured at each size. Pure Kotlin: kotlinx.serialization parsing and aggregating on Dispatchers.Default. Rust with the payload crossing: summarizeJson receiving the whole string through UniFFI. Rust streaming from disk: summarizeCsv and summarizeNdjson receiving only a path. Peak memory rides along with elapsed time, sampled via Debug.getNativeHeapAllocatedSize() and the runtime heap counters, because the constant-memory claim deserves a graph.
What I expect, and will happily be corrected on by my own data: for payloads Kotlin parses within a frame or two there is nothing to win, and kotlinx.serialization keeps the job on simplicity alone. Somewhere past that the curves cross, and the streaming path should pull away as files grow, because its memory use does not scale with input. Where that crossover sits is the one I refuse to guess in print.
Frequently Asked Questions
Should I return parsed objects from Rust to Kotlin through UniFFI?
Only in small numbers. UniFFI serializes every record across the FFI and rebuilds it as a Kotlin object, so returning tens of thousands of rows recreates the allocation pressure you left the JVM to escape. Return aggregates, or hold the dataset behind a Rust object and expose paging methods that return one screen of rows at a time.
Part 12, Cryptography with Rust on Android: ring and RustCrypto Instead of Rolling Your Own, swaps hand-rolled crypto for audited crates and leaves key custody inside the Keystore. The series index lives in the hub post.
Rust + NDK on Android, Part 11 of 15.This series teaches Android developers how to ship Rust in production apps, no prior Rust required. Hub: Rust on Android: How to Use It, How to Debug It, and Why It's Worth It. Previous: Low-Latency Audio DSP with Rust: AAudio and Oboe from a Rust Core. Next: Cryptography with Rust on Android: ring and RustCrypto Instead of Rolling Your Own.
Parsear JSON en Rust sobre Android compensa bajo una sola condición: los objetos parseados no vuelven nunca a Kotlin. Parsea una exportación de varios megabytes con serde, agrégala en el lado Rust y devuelve un record de resumen pequeño, y la frontera te cuesta un único struct. Parsea en Rust y luego marshalling de cincuenta mil objetos de vuelta a Kotlin, y has pagado serde más la mitad cara de kotlinx.serialization de todos modos: reservar el grafo de objetos en el heap de la JVM.
Esta parte construye el crate rust/parser de la serie alrededor de esa regla: structs derivados con serde para una exportación de transacciones, agregación en streaming de CSV y NDJSON que mantiene un solo record en memoria cada vez, y una frontera UniFFI que devuelve un resumen compacto que Kotlin recibe como una data class normal. También explica por qué todavía no hay tabla de benchmark, y cómo voy a sacar los números.
Esto da por hechos la cadena de herramientas de la Parte 1 y el cableado de UniFFI de la Parte 3. La Parte 6 construyó el modelo de coste de cruzar la frontera; esta parte es ese consejo aplicado: haz la llamada gruesa.
Ideas clave
- El derive de Serde te da la experiencia de @Serializable con comprobaciones más estrictas: el código generado se verifica en tipos en tiempo de compilación, y un campo que no casa con los datos es un error de ejecución tipado que nombra el campo, nunca un null silencioso.
- La condición para ganar es la agregación. Devuelve un record de UniFFI al cruzar la frontera, en lugar de un Vec de filas parseadas: la regla de la llamada gruesa de la Parte 6.
- Hacer streaming con el iterador de records del crate csv o con el StreamDeserializer de serde_json mantiene la memoria plana por muy grande que crezca el archivo.
- Para los payloads normales de una API, kotlinx.serialization sigue siendo la herramienta adecuada. Este post entrega metodología en lugar de números inventados; las medidas llegan cuando llegue el módulo que las acompaña.
¿Cuándo compensa parsear JSON en Rust sobre Android?
No para las respuestas de tu API. Un payload de unos pocos kilobytes, deserializado con kotlinx.serialization o con Moshi, se parsea con holgura dentro de un frame, y sin nada de FFI en tu build. Si esa es toda tu historia de parseo, cierra esta pestaña y deja el build simple.
La clase de problema son los archivos. Una exportación de extracto bancario que importa el usuario, dos temporadas de datos deportivos en caché para el modo sin conexión, un log de analítica al que tu app lleva meses añadiendo líneas. Llegan como JSON o CSV de varios megabytes, y duelen en la JVM de una forma concreta: un objeto reservado por fila más uno por cada campo anidado, el grafo entero en el heap junto al texto en bruto, y la presión del recolector cayendo mientras tu UI intenta cumplir un presupuesto de frame de unos 16 ms a 60 Hz (Android vitals, renderizado lento).
Kotlin no está indefenso aquí, y fingir lo contrario sería venderte algo. Moshi lee token a token sobre Okio, y kotlinx.serialization tiene un decodeToSequence experimental para hacer streaming desde un InputStream (documentación de la API de kotlinx.serialization). Lo que ninguno de los dos puede cambiar es el modelo de reservas: cada fila sigue convirtiéndose en objetos de la JVM para que el recolector de basura los trace y los barra. Serde deserializa a structs planos, sin recolector, y cuando la agregación ocurre también en el lado Rust, el heap de la JVM no ve el conjunto de datos en absoluto.
Si el parseo pesado fuera tu única necesidad nativa, añadir rustup, el NDK y un segundo lenguaje para arreglar una pantalla sería un argumento difícil de vender, y eso mismo dije en el post hub. En la Parte 11 la cadena de herramientas ya está en tu build, así que el coste marginal es un crate más en el workspace.
Un manifiesto: serde, csv y UniFFI
El crate vive en rust/parser, dentro del workspace de la serie. El manifiesto, en rust/parser/Cargo.toml:
[package]
name = "parser"
version = "0.1.0"
edition = "2021"
[lib]
crate-type = ["cdylib"]
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"
csv = "1"
thiserror = "2"
uniffi = "0.29"
Cada dependencia tiene un trabajo. serde con la feature derive es el generador de código, el paso ksp de este mundo, salvo que corre dentro de la compilación normal y su salida se comprueba en tipos como todo lo demás (serde.rs). serde_json y csv son frontends de formato; serde en sí es agnóstico del formato, y por eso un solo struct Transaction alimentará los dos parsers de más abajo. Y uniffi 0.29 es la frontera, cableada en el build de Gradle exactamente como en la Parte 3.
Structs de Serde: @Serializable con un compilador más estricto
El tipo de la fila está al principio de rust/parser/src/lib.rs, junto con la macro de andamiaje que todo crate de UniFFI necesita una vez:
use std::collections::BTreeMap;
use std::fs::File;
use std::io::BufReader;
use serde::Deserialize;
uniffi::setup_scaffolding!();
/// One row of the export. Serde fills this the way kotlinx.serialization
/// fills an @Serializable data class, with mismatches surfacing as
/// typed errors naming the field, not silent nulls.
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Transaction {
pub id: String,
pub posted_at: String,
pub amount_cents: i64,
pub currency: String,
pub category: String,
}
Si escribes kotlinx.serialization, este struct ya te suena. #[derive(Deserialize)] es @Serializable, y #[serde(rename_all = "camelCase")] hace el trabajo de @SerialName para todo el struct de una vez, de modo que posted_at se enlaza con postedAt en los datos. Un campo que falta es un error tipado que nombra el campo y la posición, no una excepción salida de algún punto dentro de un decoder. Los campos anulables se vuelven Option<String>, y #[serde(default)] rellena los valores ausentes como los parámetros por defecto de una data class.
La parte que no tiene equivalente en Kotlin: el mismo struct alimenta el parser de CSV. El crate csv casa los nombres de cabecera con los mismos nombres serializados, así que una exportación cuya fila de cabecera dice id,postedAt,amountCents,currency,category se deserializa en Transaction sin anotaciones extra.
Devuelve la respuesta, no los objetos
Ahora los tipos de la frontera, todavía en rust/parser/src/lib.rs. Dos records para el resultado y un enum de error:
#[derive(Debug, Clone, uniffi::Record)]
pub struct CategoryTotal {
pub category: String,
pub rows: u64,
pub cents: i64,
}
#[derive(Debug, Clone, uniffi::Record)]
pub struct TxSummary {
pub rows: u64,
pub total_cents: i64,
pub largest_cents: i64,
pub categories: Vec<CategoryTotal>,
}
#[derive(Debug, thiserror::Error, uniffi::Error)]
pub enum ParseError {
#[error("could not read {path}: {reason}")]
Io { path: String, reason: String },
#[error("bad record {row}: {reason}")]
Malformed { row: u64, reason: String },
}
Los records se convierten en data classes de Kotlin, como se cubre en la Parte 3. El enum de error se convierte en una jerarquía sellada de ParseException, con los campos de la variante como propiedades: el mapeo de excepciones que la Parte 8 construyó a mano, generado gratis.
¿Por qué un resumen y no Vec<Transaction>? UniFFI mueve los valores compuestos a través de la FFI serializándolos en un búfer de bytes y reconstruyéndolos al otro lado (documentación de UniFFI). Devolver ochenta mil filas significa ochenta mil records bajados en Rust y ochenta mil objetos reservados en Kotlin: exactamente la tormenta de la que nos fuimos a Rust para escapar. La agregación vive aquí, en su lugar:
#[derive(Default)]
struct Accumulator {
rows: u64,
total_cents: i64,
largest_cents: i64,
categories: BTreeMap<String, (u64, i64)>,
}
impl Accumulator {
fn push(&mut self, tx: &Transaction) {
self.rows += 1;
self.total_cents += tx.amount_cents;
self.largest_cents = self.largest_cents.max(tx.amount_cents);
let entry = self.categories.entry(tx.category.clone()).or_insert((0, 0));
entry.0 += 1;
entry.1 += tx.amount_cents;
}
fn finish(self) -> TxSummary {
TxSummary {
rows: self.rows,
total_cents: self.total_cents,
largest_cents: self.largest_cents,
categories: self
.categories
.into_iter()
.map(|(category, (rows, cents))| CategoryTotal { category, rows, cents })
.collect(),
}
}
}
/// Parse a whole JSON array already held in memory, for payloads that
/// arrived as a network body rather than a file.
#[uniffi::export]
pub fn summarize_json(payload: String) -> Result<TxSummary, ParseError> {
let transactions: Vec<Transaction> =
serde_json::from_str(&payload).map_err(|e| ParseError::Malformed {
row: e.line() as u64,
reason: e.to_string(),
})?;
let mut acc = Accumulator::default();
for tx in &transactions {
acc.push(tx);
}
Ok(acc.finish())
}
summarize_json es el caso sencillo: el payload cruza una vez como cadena, se convierte en un Vec en el heap de Rust, y solo vuelve TxSummary. Cruzar la cadena no es gratis —la Parte 6 construyó el modelo de coste—, pero ocurre una sola vez. Para datos que ya están en disco podemos saltarnos por completo cruzar el payload.
CSV y NDJSON en streaming, con memoria constante
Para los archivos, Kotlin manda una ruta y Rust abre el archivo él mismo. La versión CSV hace streaming: el iterador deserializa un record, el acumulador lo pliega, y el record se descarta antes de leer el siguiente. La memoria se queda plana tanto si el archivo tiene mil filas como si tiene diez millones. También en rust/parser/src/lib.rs:
/// Stream a CSV export from disk. One record is alive at a time,
/// so memory use does not grow with file size.
#[uniffi::export]
pub fn summarize_csv(path: String) -> Result<TxSummary, ParseError> {
let mut reader = csv::Reader::from_path(&path).map_err(|e| ParseError::Io {
path: path.clone(),
reason: e.to_string(),
})?;
let mut acc = Accumulator::default();
for (i, record) in reader.deserialize::<Transaction>().enumerate() {
let tx = record.map_err(|e| ParseError::Malformed {
row: i as u64 + 1,
reason: e.to_string(),
})?;
acc.push(&tx);
}
Ok(acc.finish())
}
JSON toma la misma forma cuando la exportación va delimitada por saltos de línea, un objeto JSON por línea. El StreamDeserializer de serde_json recorre una secuencia de valores separados por espacios en blanco a partir de un reader, y eso cubre NDJSON exactamente (documentación de serde_json):
/// Stream a newline-delimited JSON export from disk with the same
/// constant-memory profile as the CSV path.
#[uniffi::export]
pub fn summarize_ndjson(path: String) -> Result<TxSummary, ParseError> {
let file = File::open(&path).map_err(|e| ParseError::Io {
path: path.clone(),
reason: e.to_string(),
})?;
let stream = serde_json::Deserializer::from_reader(BufReader::new(file))
.into_iter::<Transaction>();
let mut acc = Accumulator::default();
for (i, item) in stream.enumerate() {
let tx = item.map_err(|e| ParseError::Malformed {
row: i as u64 + 1,
reason: e.to_string(),
})?;
acc.push(&tx);
}
Ok(acc.finish())
}
Un array JSON gigante en el nivel superior no hace streaming a través de StreamDeserializer, porque los corchetes lo convierten en un solo valor. O tomas la vía de summarize_json y te quedas el Vec en memoria de Rust, todavía mucho más barato que el heap de la JVM, o escribes un visitor de serde a medida que pliega los elementos según se parsean. Si controlas el exportador, emite NDJSON y el problema desaparece.
El lado Kotlin es una sola función suspend
Los bindings generados exponen summarizeCsv, summarizeJson y summarizeNdjson como funciones de nivel superior en el paquete uniffi.parser, exactamente como lo dejó montado la Parte 3. El wrapper está en app/src/main/java/dev/davthecoder/rustseries/parsing/TransactionReports.kt:
package dev.davthecoder.rustseries.parsing
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import uniffi.parser.ParseException
import uniffi.parser.TxSummary
import uniffi.parser.summarizeCsv
sealed interface ReportState {
data class Ready(val summary: TxSummary) : ReportState
data class Failed(val message: String) : ReportState
}
class TransactionReports {
suspend fun buildReport(csvPath: String): ReportState =
withContext(Dispatchers.IO) {
try {
ReportState.Ready(summarizeCsv(csvPath))
} catch (e: ParseException.Io) {
ReportState.Failed("Could not read ${e.path}")
} catch (e: ParseException.Malformed) {
ReportState.Failed("Bad record at row ${e.row}: ${e.reason}")
}
}
}
Tres notas. Las funciones exportadas bloquean el hilo que las llama durante todo el parseo, así que withContext(Dispatchers.IO) no es decoración; llama a esto en el hilo principal y habrás movido los tirones, no los habrás quitado. Los catch tipados funcionan porque UniFFI convirtió ParseError en una jerarquía sellada de excepciones, con path, row y reason como propiedades de verdad. Y rows: u64 llega como un ULong de Kotlin, porque UniFFI mapea los enteros sin signo a los tipos sin signo de Kotlin (documentación de UniFFI); usa i64 si prefieres entregar a tu UI un Long normal.
Un pliegue propio de Android: summarizeCsv quiere una ruta real del sistema de archivos, y un URI content:// del Storage Access Framework no lo es. Copia el documento elegido a cacheDir una vez y pasa esa ruta. La alternativa zero-copy, entregar a Rust un descriptor de archivo detached, es territorio de la Parte 6; para un parseo de una vez por importación, la copia está bien y es simple.
De dónde van a salir los números del benchmark
Aquí es donde debería sentarse un gráfico, y se queda vacío a propósito. La serie publica medidas, y el módulo rust/parser todavía no ha salido. Lo que puedo darte ahora es la metodología, para que los números signifiquen algo cuando aterricen.
El arnés sigue las reglas de la Parte 5: builds de release con R8, un dispositivo físico de gama media con nombre, iteraciones de calentamiento antes de anotar nada, medianas de ejecuciones repetidas en lugar del mejor caso. El conjunto de datos lo genera de forma determinista un script commiteado al lado del crate, y barre desde unos cientos de kilobytes hasta decenas de megabytes, para que cualquiera pueda regenerar la misma entrada.
En cada tamaño se miden tres configuraciones. Kotlin puro: kotlinx.serialization parseando y agregando en Dispatchers.Default. Rust con el payload cruzando: summarizeJson recibiendo la cadena entera a través de UniFFI. Rust en streaming desde disco: summarizeCsv y summarizeNdjson recibiendo solo una ruta. La memoria pico viaja junto al tiempo transcurrido, muestreada con Debug.getNativeHeapAllocatedSize() y los contadores del heap en tiempo de ejecución, porque la afirmación de memoria constante merece un gráfico.
Lo que espero, y que corregiré encantado con mis propios datos: para los payloads que Kotlin parsea en un frame o dos no hay nada que ganar, y kotlinx.serialization se queda el trabajo solo por simplicidad. En algún punto más allá las curvas se cruzan, y la vía en streaming debería despegar conforme crecen los archivos, porque su uso de memoria no escala con la entrada. Dónde se sienta ese cruce es el que me niego a adivinar por escrito.
Preguntas frecuentes
¿Debería devolver objetos parseados de Rust a Kotlin a través de UniFFI?
Solo en cantidades pequeñas. UniFFI serializa cada record a través de la FFI y lo reconstruye como un objeto de Kotlin, así que devolver decenas de miles de filas recrea la presión de reservas de la que te fuiste de la JVM para escapar. Devuelve agregados, o guarda el conjunto de datos detrás de un objeto de Rust y expón métodos de paginación que devuelvan una pantalla de filas cada vez.
La Parte 12, Cryptography with Rust on Android: ring and RustCrypto Instead of Rolling Your Own, cambia el cripto hecho a mano por crates auditados y deja la custodia de las claves dentro del Keystore. El índice de la serie vive en el post hub.
Rust + NDK on Android, Part 11 of 15.This series teaches Android developers how to ship Rust in production apps, no prior Rust required. Hub: Rust on Android: How to Use It, How to Debug It, and Why It's Worth It. Previous: Low-Latency Audio DSP with Rust: AAudio and Oboe from a Rust Core. Next: Cryptography with Rust on Android: ring and RustCrypto Instead of Rolling Your Own.
การพาร์ส JSON ใน Rust บน Android คุ้มภายใต้เงื่อนไขเดียว: อ็อบเจกต์ที่พาร์สแล้วไม่ข้ามกลับเข้า Kotlin พาร์สไฟล์ส่งออกขนาดหลายเมกะไบต์ด้วย serde รวมมันฝั่ง Rust แล้วคืนเรคอร์ดสรุปเล็กหนึ่งก้อน ขอบเขตจะเสียคุณแค่ struct เดียว พาร์สใน Rust แล้วจัดเรียงวัตถุห้าหมื่นชิ้นกลับเข้า Kotlin เท่ากับจ่ายทั้ง serde และครึ่งที่แพงของ kotlinx.serialization อยู่ดี: การจัดสรรกราฟวัตถุบนฮีปของ JVM
ตอนนี้สร้าง crate rust/parser ของชุดรอบกฎนั้น: struct จาก serde derive สำหรับไฟล์ส่งออกรายการธุรกรรม การรวม CSV และ NDJSON แบบสตรีมที่ถือเรคอร์ดในหน่วยความจำครั้งละหนึ่งรายการ และขอบเขต UniFFI ที่คืนสรุปกะทัดรัดซึ่ง Kotlin รับเป็น data class ธรรมดา มันยังอธิบายว่าทำไมยังไม่มีตารางเบนช์มาร์ก และผมจะผลิตตัวเลขอย่างไร
สิ่งนี้สมมติทูลเชนจาก ตอนที่ 1 และการเดินสาย UniFFI จาก ตอนที่ 3 ตอนที่ 6 สร้างโมเดลต้นทุนการข้ามขอบเขต ตอนนี้เอาคำแนะนำนั้นมาใช้: เรียกเป็นก้อน
ประเด็นสำคัญ
- derive ของ Serde ให้ประสบการณ์แบบ @Serializable พร้อมการตรวจที่เข้มกว่า: โค้ดที่สร้างขึ้นถูกตรวจชนิดตอนคอมไพล์ และฟิลด์ที่ไม่ตรงกับข้อมูลเป็นข้อผิดพลาดรันไทม์แบบมีชนิดที่ระบุชื่อฟิลด์ ไม่เคยเป็น null เงียบๆ
- เงื่อนไขที่ชนะคือการรวมข้อมูล คืนเรคอร์ด UniFFI หนึ่งก้อนข้ามขอบเขต แทน Vec ของแถวที่พาร์สแล้ว ตามกฎเรียกเป็นก้อนจาก ตอนที่ 6
- การสตรีมผ่านอิตเทอเรเตอร์เรคอร์ดของ crate csv หรือ StreamDeserializer ของ serde_json ทำให้หน่วยความจำราบ ไม่ว่าไฟล์จะโตแค่ไหน
- สำหรับเพย์โหลด API ธรรมดา kotlinx.serialization ยังเป็นเครื่องมือที่ถูก บทความนี้ชิประเบียบวิธี แทนตัวเลขที่คิดขึ้น การวัดจะลงเมื่อโมดูลคู่กันลง
เมื่อใดการพาร์ส JSON ใน Rust บน Android จึงคุ้ม?
ไม่ใช่สำหรับเรสปอนส์ API ของคุณ เพย์โหลดไม่กี่กิโลไบต์ที่ดีซีเรียลไลซ์ด้วย kotlinx.serialization หรือ Moshi พาร์สได้สบายภายในเฟรม โดยไม่มี FFI ในบิลด์ ถ้านั่นคือเรื่องการพาร์สทั้งหมด ให้ปิดแท็บนี้แล้วรักษาบิลด์ให้เรียบง่าย
คลาสของปัญหาคือไฟล์ ไฟล์ส่งออกใบแจ้งยอดธนาคารที่ผู้ใช้นำเข้า ข้อมูลกีฬาที่แคชไว้สองฤดูกาลสำหรับโหมดออฟไลน์ ล็อกแอนะลิติกส์ที่แอปเขียนต่อท้ายมาหลายเดือน สิ่งเหล่านี้มาเป็น JSON หรือ CSV ขนาดหลายเมกะไบต์ และมันเจ็บบน JVM ในแบบเฉพาะ: หนึ่งอ็อบเจกต์ที่ถูกจัดสรรต่อแถว บวกหนึ่งต่อฟิลด์ที่ซ้อน กราฟทั้งก้อนบนฮีปข้างข้อความดิบ และแรงกดของการเก็บกวาดมาตอนที่ UI พยายามรักษางบเฟรมราว 16 ms ที่ 60 Hz (Android vitals, slow rendering)
Kotlin ไม่ได้จนมุมตรงนี้ และการแกล้งว่าเป็นอย่างอื่นคือการขายอะไรบางอย่างให้คุณ Moshi อ่านทีละโทเค็นบน Okio และ kotlinx.serialization มี decodeToSequence แบบทดลองสำหรับสตรีมจาก InputStream (kotlinx.serialization API docs) สิ่งที่ทั้งคู่เปลี่ยนไม่ได้คือโมเดลการจัดสรร: ทุกแถวยังกลายเป็นอ็อบเจกต์ JVM ให้ตัวเก็บกวาดขยะไล่และกวาด Serde ดีซีเรียลไลซ์เข้า struct ธรรมดาที่ไม่มีตัวเก็บกวาด และเมื่อการรวมข้อมูลเกิดฝั่ง Rust ด้วย ฮีปของ JVM ไม่เห็นชุดข้อมูลเลย
ถ้าการพาร์สงานหนักเป็นความต้องการเนทีฟอย่างเดียว การเพิ่ม rustup, NDK และภาษาที่สองเพื่อแก้หน้าจอเดียวจะขายยาก และผมพูดแบบนั้นใน บทความฮับ เมื่อถึงตอนที่ 11 ทูลเชนอยู่ในบิลด์แล้ว ดังนั้นต้นทุนส่วนเพิ่มคืออีกหนึ่ง crate ในเวิร์กสเปซ
มานิเฟสต์เดียว: serde, csv และ UniFFI
crate อยู่ที่ rust/parser ในเวิร์กสเปซของชุด มานิเฟสต์ที่ rust/parser/Cargo.toml:
[package]
name = "parser"
version = "0.1.0"
edition = "2021"
[lib]
crate-type = ["cdylib"]
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"
csv = "1"
thiserror = "2"
uniffi = "0.29"
แต่ละดีเพนเดนซีมีงาน serde พร้อมฟีเจอร์ derive คือตัวสร้างโค้ด ขั้น ksp ของโลกนี้ ต่างตรงที่มันรันในการคอมไพล์ปกติ และเอาต์พุตถูกตรวจชนิดเหมือนอย่างอื่น (serde.rs) serde_json และ csv คือส่วนหน้าของรูปแบบ serde เองไม่ผูกกับรูปแบบ ซึ่งเป็นเหตุที่ struct Transaction หนึ่งตัวจะป้อนพาร์เซอร์ทั้งสองด้านล่าง และ uniffi 0.29 คือขอบเขต เดินสายเข้าบิลด์ Gradle เหมือนใน ตอนที่ 3
struct ของ Serde: @Serializable พร้อมคอมไพเลอร์ที่เข้มกว่า
ชนิดของแถวอยู่บนสุดของ rust/parser/src/lib.rs พร้อมแมโคร scaffolding ที่ทุก crate ของ UniFFI ต้องมีครั้งเดียว:
use std::collections::BTreeMap;
use std::fs::File;
use std::io::BufReader;
use serde::Deserialize;
uniffi::setup_scaffolding!();
/// One row of the export. Serde fills this the way kotlinx.serialization
/// fills an @Serializable data class, with mismatches surfacing as
/// typed errors naming the field, not silent nulls.
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Transaction {
pub id: String,
pub posted_at: String,
pub amount_cents: i64,
pub currency: String,
pub category: String,
}
ถ้าคุณเขียน kotlinx.serialization คุณรู้จัก struct นี้แล้ว #[derive(Deserialize)] คือ @Serializable และ #[serde(rename_all = "camelCase")] ทำงานของ @SerialName ให้ทั้ง struct ในครั้งเดียว ดังนั้น posted_at ผูกกับ postedAt ในข้อมูล ฟิลด์ที่หายคือข้อผิดพลาดแบบมีชนิดที่ระบุชื่อฟิลด์และตำแหน่ง ไม่ใช่ exception จากที่ใดที่หนึ่งในตัวถอดรหัส ฟิลด์ที่เป็น null ได้กลายเป็น Option<String> และ #[serde(default)] เติมค่าที่ขาดเหมือนพารามิเตอร์ค่าเริ่มต้นใน data class
ส่วนที่ไม่มีสิ่งเทียบใน Kotlin: struct เดียวกันขับพาร์เซอร์ CSV crate csv จับคู่ชื่อส่วนหัวกับชื่อที่ซีเรียลไลซ์เดียวกัน ดังนั้นไฟล์ส่งออกที่แถวส่วนหัวอ่านว่า id,postedAt,amountCents,currency,category จะดีซีเรียลไลซ์เข้า Transaction โดยไม่ต้องมีแอโนเทชันเพิ่ม
คืนคำตอบ ไม่ใช่อ็อบเจกต์
ตอนนี้คือชนิดของขอบเขต ยังอยู่ใน rust/parser/src/lib.rs สองเรคอร์ดสำหรับผลลัพธ์ และหนึ่ง enum ของข้อผิดพลาด:
#[derive(Debug, Clone, uniffi::Record)]
pub struct CategoryTotal {
pub category: String,
pub rows: u64,
pub cents: i64,
}
#[derive(Debug, Clone, uniffi::Record)]
pub struct TxSummary {
pub rows: u64,
pub total_cents: i64,
pub largest_cents: i64,
pub categories: Vec<CategoryTotal>,
}
#[derive(Debug, thiserror::Error, uniffi::Error)]
pub enum ParseError {
#[error("could not read {path}: {reason}")]
Io { path: String, reason: String },
#[error("bad record {row}: {reason}")]
Malformed { row: u64, reason: String },
}
เรคอร์ดกลายเป็น data class ของ Kotlin ตามที่ครอบคลุมใน ตอนที่ 3 enum ของข้อผิดพลาดกลายเป็นลำดับชั้น ParseException แบบ sealed โดยฟิลด์ของ variant เป็นพร็อพเพอร์ตี การแมป exception ที่ ตอนที่ 8 สร้างด้วยมือ ได้มาฟรี
ทำไมเป็นสรุป ไม่ใช่ Vec<Transaction>? UniFFI ย้ายค่าประกอบข้าม FFI โดยซีเรียลไลซ์เข้าบัฟเฟอร์ไบต์แล้วสร้างใหม่ฝั่งตรงข้าม (UniFFI docs) การคืนแปดหมื่นแถวหมายถึงแปดหมื่นเรคอร์ดที่ถูกลดใน Rust และแปดหมื่นอ็อบเจกต์ที่ถูกจัดสรรใน Kotlin พายุเดียวกับที่เราย้ายไป Rust เพื่อหนี การรวมข้อมูลอยู่ที่นี่แทน:
#[derive(Default)]
struct Accumulator {
rows: u64,
total_cents: i64,
largest_cents: i64,
categories: BTreeMap<String, (u64, i64)>,
}
impl Accumulator {
fn push(&mut self, tx: &Transaction) {
self.rows += 1;
self.total_cents += tx.amount_cents;
self.largest_cents = self.largest_cents.max(tx.amount_cents);
let entry = self.categories.entry(tx.category.clone()).or_insert((0, 0));
entry.0 += 1;
entry.1 += tx.amount_cents;
}
fn finish(self) -> TxSummary {
TxSummary {
rows: self.rows,
total_cents: self.total_cents,
largest_cents: self.largest_cents,
categories: self
.categories
.into_iter()
.map(|(category, (rows, cents))| CategoryTotal { category, rows, cents })
.collect(),
}
}
}
/// Parse a whole JSON array already held in memory, for payloads that
/// arrived as a network body rather than a file.
#[uniffi::export]
pub fn summarize_json(payload: String) -> Result<TxSummary, ParseError> {
let transactions: Vec<Transaction> =
serde_json::from_str(&payload).map_err(|e| ParseError::Malformed {
row: e.line() as u64,
reason: e.to_string(),
})?;
let mut acc = Accumulator::default();
for tx in &transactions {
acc.push(tx);
}
Ok(acc.finish())
}
summarize_json คือกรณีง่าย: เพย์โหลดข้ามครั้งเดียวเป็นสตริง กลายเป็น Vec บนฮีปของ Rust และมีแค่ TxSummary ที่กลับมา การข้ามสตริงไม่ฟรี ตอนที่ 6 สร้างโมเดลต้นทุนไว้ แต่มันเกิดครั้งเดียว สำหรับข้อมูลที่อยู่บนดิสก์แล้ว เราข้ามการส่งเพย์โหลดไปได้เลย
การสตรีม CSV และ NDJSON ในหน่วยความจำคงที่
สำหรับไฟล์ Kotlin ส่งพาธ และ Rust เปิดไฟล์เอง เวอร์ชัน CSV สตรีม: อิตเทอเรเตอร์ดีซีเรียลไลซ์หนึ่งเรคอร์ด ตัวสะสมพับมัน เรคอร์ดถูกดรอปก่อนอ่านตัวถัดไป หน่วยความจำราบไม่ว่าไฟล์จะมีพันแถวหรือสิบล้านแถว ก็อยู่ใน rust/parser/src/lib.rs:
/// Stream a CSV export from disk. One record is alive at a time,
/// so memory use does not grow with file size.
#[uniffi::export]
pub fn summarize_csv(path: String) -> Result<TxSummary, ParseError> {
let mut reader = csv::Reader::from_path(&path).map_err(|e| ParseError::Io {
path: path.clone(),
reason: e.to_string(),
})?;
let mut acc = Accumulator::default();
for (i, record) in reader.deserialize::<Transaction>().enumerate() {
let tx = record.map_err(|e| ParseError::Malformed {
row: i as u64 + 1,
reason: e.to_string(),
})?;
acc.push(&tx);
}
Ok(acc.finish())
}
JSON ได้รูปเดียวกันเมื่อไฟล์ส่งออกคั่นด้วยบรรทัดใหม่ หนึ่งอ็อบเจกต์ JSON ต่อบรรทัด StreamDeserializer ของ serde_json เดินลำดับของค่าที่คั่นด้วยช่องว่างจาก reader ซึ่งครอบคลุม NDJSON พอดี (serde_json docs):
/// Stream a newline-delimited JSON export from disk with the same
/// constant-memory profile as the CSV path.
#[uniffi::export]
pub fn summarize_ndjson(path: String) -> Result<TxSummary, ParseError> {
let file = File::open(&path).map_err(|e| ParseError::Io {
path: path.clone(),
reason: e.to_string(),
})?;
let stream = serde_json::Deserializer::from_reader(BufReader::new(file))
.into_iter::<Transaction>();
let mut acc = Accumulator::default();
for (i, item) in stream.enumerate() {
let tx = item.map_err(|e| ParseError::Malformed {
row: i as u64 + 1,
reason: e.to_string(),
})?;
acc.push(&tx);
}
Ok(acc.finish())
}
อาร์เรย์ JSON ระดับบนสุดขนาดมหึมาไม่สตรีมผ่าน StreamDeserializer เพราะวงเล็บทำให้มันเป็นค่าเดียว จะเดินทาง summarize_json แล้วถือ Vec ในหน่วยความจำ Rust ซึ่งยังถูกกว่าฮีป JVM มาก หรือเขียน visitor ของ serde เองที่พับองค์ประกอบระหว่างพาร์ส ถ้าคุณควบคุมตัวส่งออก ให้ส่ง NDJSON แล้วปัญหาหายไป
ฝั่ง Kotlin คือฟังก์ชัน suspend หนึ่งตัว
บิดดิงที่สร้างขึ้นเปิด summarizeCsv, summarizeJson และ summarizeNdjson เป็นฟังก์ชันระดับบนสุดในแพ็กเกจ uniffi.parser ตามที่ ตอนที่ 3 ตั้งไว้ ตัวห่อที่ app/src/main/java/dev/davthecoder/rustseries/parsing/TransactionReports.kt:
package dev.davthecoder.rustseries.parsing
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import uniffi.parser.ParseException
import uniffi.parser.TxSummary
import uniffi.parser.summarizeCsv
sealed interface ReportState {
data class Ready(val summary: TxSummary) : ReportState
data class Failed(val message: String) : ReportState
}
class TransactionReports {
suspend fun buildReport(csvPath: String): ReportState =
withContext(Dispatchers.IO) {
try {
ReportState.Ready(summarizeCsv(csvPath))
} catch (e: ParseException.Io) {
ReportState.Failed("Could not read ${e.path}")
} catch (e: ParseException.Malformed) {
ReportState.Failed("Bad record at row ${e.row}: ${e.reason}")
}
}
}
สามหมายเหตุ ฟังก์ชันที่เอ็กซ์พอร์ตบล็อกเธรดที่เรียกมันตลอดระยะการพาร์ส ดังนั้น withContext(Dispatchers.IO) ไม่ใช่ของตกแต่ง เรียกสิ่งนี้บนเธรดหลักแล้วคุณย้ายอาการกระตุก ไม่ได้เอาออก การจับแบบมีชนิดใช้ได้เพราะ UniFFI เปลี่ยน ParseError เป็นลำดับชั้น exception แบบ sealed โดย path, row และ reason เป็นพร็อพเพอร์ตีจริง และ rows: u64 มาถึงเป็น ULong ของ Kotlin เพราะ UniFFI แมปจำนวนเต็มไม่มีเครื่องหมายไปชนิดไม่มีเครื่องหมายของ Kotlin (UniFFI docs) ใช้ i64 ถ้าอยากส่ง Long ธรรมดาให้ UI
รอยย่นของ Android ข้อหนึ่ง: summarizeCsv อยากได้พาธระบบไฟล์จริง และ URI content:// จาก Storage Access Framework ไม่ใช่พาธนั้น คัดลอกเอกสารที่เลือกเข้า cacheDir ครั้งเดียวแล้วส่งพาธนั้น ทางเลือกแบบไม่คัดลอก คือส่ง file descriptor ที่ถอดออกให้ Rust เป็นเขตของ ตอนที่ 6 สำหรับการพาร์สครั้งเดียวต่อการนำเข้า การคัดลอกใช้ได้และเรียบง่าย
ตัวเลขเบนช์มาร์กจะมาจากไหน
นี่คือที่ที่ควรมีกราฟ และมันว่างโดยตั้งใจ ชุดนี้พิมพ์การวัด และโมดูล rust/parser ยังไม่ชิป สิ่งที่ให้ได้ตอนนี้คือระเบียบวิธี เพื่อให้ตัวเลขมีความหมายเมื่อมันลง
ฮาร์เนสตามกฎจาก ตอนที่ 5: บิลด์ release พร้อม R8 อุปกรณ์จริงระดับกลางที่ระบุชื่อ รอบอุ่นเครื่องก่อนบันทึกอะไร ค่ามัธยฐานของการรันซ้ำ แทนกรณีที่ดีที่สุด ชุดข้อมูลถูกสร้างแบบกำหนดได้ด้วยสคริปต์ที่คอมมิตข้าง crate และกวาดจากไม่กี่ร้อยกิโลไบต์ถึงหลายสิบเมกะไบต์ เพื่อให้ใครก็สร้างอินพุตชุดเดียวกันใหม่ได้
สามรูปแบบถูกวัดที่แต่ละขนาด Kotlin ล้วน: kotlinx.serialization พาร์สและรวมบน Dispatchers.Default Rust ที่เพย์โหลดข้าม: summarizeJson รับทั้งสตริงผ่าน UniFFI Rust ที่สตรีมจากดิสก์: summarizeCsv และ summarizeNdjson รับแค่พาธ หน่วยความจำสูงสุดไปพร้อมเวลาที่ผ่าน เก็บตัวอย่างผ่าน Debug.getNativeHeapAllocatedSize() และตัวนับฮีปรันไทม์ เพราะคำกล่าวเรื่องหน่วยความจำคงที่สมควรได้กราฟ
สิ่งที่ผมคาด และยอมให้ข้อมูลของตัวเองแก้ได้: สำหรับเพย์โหลดที่ Kotlin พาร์สได้ภายในหนึ่งหรือสองเฟรม ไม่มีอะไรให้ชนะ และ kotlinx.serialization เก็บงานไว้ด้วยความเรียบง่ายอย่างเดียว ที่ใดที่หนึ่งเลยจุดนั้นเส้นโค้งตัดกัน และทางสตรีมควรดึงห่างเมื่อไฟล์โต เพราะการใช้หน่วยความจำของมันไม่สเกลตามอินพุต จุดตัดนั้นอยู่ตรงไหนคือสิ่งเดียวที่ผมไม่ยอมเดาเป็นลายลักษณ์อักษร
คำถามที่พบบ่อย
ควรคืนอ็อบเจกต์ที่พาร์สแล้วจาก Rust ไป Kotlin ผ่าน UniFFI ไหม?
เฉพาะเมื่อจำนวนน้อย UniFFI ซีเรียลไลซ์ทุกเรคอร์ดข้าม FFI แล้วสร้างใหม่เป็นอ็อบเจกต์ Kotlin ดังนั้นการคืนแถวหลายหมื่นแถวสร้างแรงกดการจัดสรรที่คุณออกจาก JVM เพื่อหนีกลับมา คืนค่าที่รวมแล้ว หรือถือชุดข้อมูลไว้หลังอ็อบเจกต์ Rust แล้วเปิดเมธอดแบ่งหน้าซึ่งคืนแถวทีละหนึ่งหน้าจอ
ตอนที่ 12 การเข้ารหัสด้วย Rust บน Android: ring และ RustCrypto แทนการเขียนเอง เปลี่ยนคริปโตที่ม้วนเองเป็น crate ที่ผ่านการตรวจสอบ และทิ้งการดูแลคีย์ไว้ใน Keystore ดัชนีของชุดอยู่ใน บทความฮับ

Loading comments…Cargando comentarios…กำลังโหลดความคิดเห็น…