Skip to main content

mlt_core/dump/
decode.rs

1//! Typed decode of a single data blob, for callers that render the values themselves.
2
3use serde::Serialize;
4#[cfg(feature = "unstable-v2")]
5use usize_cast::IntoUsize as _;
6
7use super::model::{BlobInfo, DecodeHint};
8use crate::Decoder;
9use crate::decoder::RawStream;
10
11/// One data blob decoded for display, capped at the caller's value count.
12///
13/// [`render`](super::render()) formats the same payloads as text.
14/// This is the structured form, for the wasm binding and anything else that lays out its own view.
15#[derive(Debug, Clone, PartialEq, Serialize)]
16#[serde(
17    tag = "kind",
18    rename_all = "camelCase",
19    rename_all_fields = "camelCase"
20)]
21pub enum DecodedBlob {
22    /// Values that survive an `f64` round-trip.
23    Numbers {
24        values: Vec<f64>,
25        /// Value count before the cap, or `None` when nothing was dropped.
26        truncated_from: Option<u32>,
27    },
28    /// 64-bit values, which an `f64` would round.
29    #[serde(rename = "bigints")]
30    BigInts {
31        values: Vec<i128>,
32        truncated_from: Option<u32>,
33    },
34    Bools {
35        values: Vec<bool>,
36        truncated_from: Option<u32>,
37    },
38    /// A byte payload that is valid UTF-8.
39    Text { value: String },
40    /// A byte payload that is not.
41    Binary { len: u32 },
42    /// The payload did not decode.
43    Error { message: String },
44}
45
46/// Decode `data` the way `info`'s hint says to, keeping at most `max_values` values.
47///
48/// `max_values` of `0` keeps all of them.
49/// A bytes payload is one value rather than a list, so it crosses whole.
50/// Never panics: a decode failure comes back as [`DecodedBlob::Error`].
51pub fn decode_blob(
52    info: BlobInfo,
53    data: &[u8],
54    max_values: usize,
55    dec: &mut Decoder,
56) -> DecodedBlob {
57    // Bound memory/time per blob, as `render` does.
58    dec.reset_budget();
59    let meta = info.meta;
60    match info.hint {
61        DecodeHint::Presence => match RawStream::new(meta, data).decode_bitvec(dec) {
62            Ok(bits) => bools(bits.iter().by_vals().collect(), max_values),
63            Err(e) => error(&e),
64        },
65        #[cfg(feature = "unstable-v2")]
66        DecodeHint::PackedBits => {
67            let n = meta.num_values.into_usize();
68            let available = data.len() * 8;
69            if available < n {
70                return DecodedBlob::Error {
71                    message: format!("needs {n} bits, got {available}"),
72                };
73            }
74            bools(
75                (0..n).map(|i| data[i / 8] >> (i % 8) & 1 == 1).collect(),
76                max_values,
77            )
78        }
79        DecodeHint::Bool => match RawStream::new(meta, data).decode_bools(dec) {
80            Ok(v) => bools(v, max_values),
81            Err(e) => error(&e),
82        },
83        DecodeHint::I32 => numbers(
84            RawStream::new(meta, data).decode_ints::<i32>(dec),
85            max_values,
86        ),
87        DecodeHint::U32 => numbers(
88            RawStream::new(meta, data).decode_ints::<u32>(dec),
89            max_values,
90        ),
91        DecodeHint::F32 => numbers(
92            RawStream::new(meta, data).decode_floats::<f32>(dec),
93            max_values,
94        ),
95        DecodeHint::F64 => numbers(
96            RawStream::new(meta, data).decode_floats::<f64>(dec),
97            max_values,
98        ),
99        DecodeHint::I64 => bigints(
100            RawStream::new(meta, data).decode_ints::<i64>(dec),
101            max_values,
102        ),
103        DecodeHint::U64 => bigints(
104            RawStream::new(meta, data).decode_ints::<u64>(dec),
105            max_values,
106        ),
107        #[cfg(feature = "unstable-v2")]
108        DecodeHint::Alp(params) => bigints(
109            RawStream::new(meta, data).decode_alp_codes(params, dec),
110            max_values,
111        ),
112        DecodeHint::Bytes => match std::str::from_utf8(data) {
113            Ok(s) => DecodedBlob::Text {
114                value: s.to_string(),
115            },
116            Err(_) => DecodedBlob::Binary {
117                len: count(data.len()),
118            },
119        },
120    }
121}
122
123fn numbers<T: Into<f64>>(res: crate::MltResult<Vec<T>>, max_values: usize) -> DecodedBlob {
124    match res {
125        Ok(v) => {
126            let (v, truncated_from) = cap(v, max_values);
127            DecodedBlob::Numbers {
128                values: v.into_iter().map(Into::into).collect(),
129                truncated_from,
130            }
131        }
132        Err(e) => error(&e),
133    }
134}
135
136fn bigints<T: Into<i128>>(res: crate::MltResult<Vec<T>>, max_values: usize) -> DecodedBlob {
137    match res {
138        Ok(v) => {
139            let (v, truncated_from) = cap(v, max_values);
140            DecodedBlob::BigInts {
141                values: v.into_iter().map(Into::into).collect(),
142                truncated_from,
143            }
144        }
145        Err(e) => error(&e),
146    }
147}
148
149fn bools(v: Vec<bool>, max_values: usize) -> DecodedBlob {
150    let (values, truncated_from) = cap(v, max_values);
151    DecodedBlob::Bools {
152        values,
153        truncated_from,
154    }
155}
156
157fn error(e: &crate::MltError) -> DecodedBlob {
158    DecodedBlob::Error {
159        message: e.to_string(),
160    }
161}
162
163/// Keep the first `max_values`, reporting the original count when that drops any.
164fn cap<T>(mut values: Vec<T>, max_values: usize) -> (Vec<T>, Option<u32>) {
165    let total = values.len();
166    if max_values == 0 || total <= max_values {
167        return (values, None);
168    }
169    values.truncate(max_values);
170    (values, Some(count(total)))
171}
172
173fn count(n: usize) -> u32 {
174    u32::try_from(n).unwrap_or(u32::MAX)
175}