1use crate::codec::{ArrayReader, TupleReader};
2use crate::ser::offset_max;
3use crate::{Error, GvDecode, Result, Type, Value};
4
5pub(crate) const MAX_VALUE_DEPTH: usize = 128;
9
10pub fn from_bytes(ty: &Type, data: &[u8]) -> Result<Value> {
17 parse(ty, data, 0)
18}
19
20fn parse(ty: &Type, data: &[u8], depth: usize) -> Result<Value> {
21 if depth > MAX_VALUE_DEPTH {
22 return Err(Error::DepthExceeded);
23 }
24 match ty {
25 Type::Bool => Ok(Value::Bool(bool::decode(data)?)),
28 Type::Byte => Ok(Value::Byte(u8::decode(data)?)),
29 Type::I16 => Ok(Value::I16(i16::from_le_bytes(exact::<2>(data)?))),
30 Type::U16 => Ok(Value::U16(u16::from_le_bytes(exact::<2>(data)?))),
31 Type::I32 | Type::Handle => Ok(Value::I32(i32::from_le_bytes(exact::<4>(data)?))),
32 Type::U32 => Ok(Value::U32(u32::decode(data)?)),
33 Type::I64 => Ok(Value::I64(i64::from_le_bytes(exact::<8>(data)?))),
34 Type::U64 => Ok(Value::U64(u64::decode(data)?)),
35 Type::Double => Ok(Value::Double(u64::from_le_bytes(exact::<8>(data)?))),
36 Type::Str | Type::ObjectPath | Type::Signature => {
37 Ok(Value::Str(<&str>::decode(data)?.to_owned()))
38 }
39 Type::Maybe(elem) => parse_maybe(elem, data, depth),
40 Type::Array(elem) if **elem == Type::Byte => Ok(Value::Bytes(data.to_vec())),
41 Type::Array(elem) => parse_array(elem, data, depth),
42 Type::Tuple(members) => parse_struct(ty, members.iter(), data, depth),
43 Type::DictEntry(key, value) => {
44 parse_struct(ty, [&**key, &**value].into_iter(), data, depth)
45 }
46 Type::Variant => {
47 let (child, _, child_ty) = split_variant(data)?;
48 let value = parse(&child_ty, child, depth + 1)?;
49 Ok(Value::variant(child_ty, value))
50 }
51 }
52}
53
54const ARRAY_PREALLOC_CAP: usize = 4096;
60
61fn parse_maybe(elem: &Type, data: &[u8], depth: usize) -> Result<Value> {
65 if data.is_empty() {
66 return Ok(Value::Maybe(None));
67 }
68 let child = if elem.fixed_size().is_some() {
69 data
70 } else {
71 match data.split_last() {
72 Some((0, rest)) => rest,
73 _ => return Err(Error::NotNormal("maybe lacks its terminating zero byte")),
74 }
75 };
76 Ok(Value::Maybe(Some(Box::new(parse(elem, child, depth + 1)?))))
77}
78
79fn parse_array(elem: &Type, data: &[u8], depth: usize) -> Result<Value> {
80 let mut reader = ArrayReader::new(data, elem.alignment(), elem.fixed_size())?;
81 let mut items = Vec::with_capacity(reader.len().min(ARRAY_PREALLOC_CAP));
82 while let Some(slice) = reader.next_slice() {
83 items.push(parse(elem, slice?, depth + 1)?);
84 }
85 Ok(Value::Array(items))
86}
87
88fn parse_struct<'t>(
89 whole: &Type,
90 members: impl ExactSizeIterator<Item = &'t Type> + Clone,
91 data: &[u8],
92 depth: usize,
93) -> Result<Value> {
94 let n = members.len();
95 if n == 0 {
96 if data != [0] {
97 return Err(Error::NotNormal("empty tuple is not a single zero byte"));
98 }
99 return Ok(Value::Tuple(Vec::new()));
100 }
101 let n_offsets = members
103 .clone()
104 .take(n - 1)
105 .filter(|m| m.fixed_size().is_none())
106 .count();
107 let mut reader = TupleReader::new(data, n_offsets, whole.fixed_size())?;
108 let mut items = Vec::with_capacity(n);
109 let last = n - 1;
110 for (i, member_ty) in members.enumerate() {
111 let slice = reader.field(member_ty.alignment(), member_ty.fixed_size(), i == last)?;
112 items.push(parse(member_ty, slice, depth + 1)?);
113 }
114 reader.finish()?;
115 Ok(Value::Tuple(items))
116}
117
118pub(crate) fn exact<const N: usize>(data: &[u8]) -> Result<[u8; N]> {
119 data.try_into()
120 .map_err(|_| Error::NotNormal("scalar has the wrong size"))
121}
122
123pub(crate) fn split_variant(data: &[u8]) -> Result<(&[u8], &[u8], Type)> {
126 let Some(sep) = data.iter().rposition(|&b| b == 0) else {
127 return Err(Error::NotNormal("variant lacks a type separator"));
128 };
129 let signature = &data[sep + 1..];
130 let sig = std::str::from_utf8(signature)
131 .map_err(|_| Error::NotNormal("variant type signature is not UTF-8"))?;
132 let ty = Type::parse(sig).map_err(|_| Error::NotNormal("variant type signature is invalid"))?;
133 Ok((&data[..sep], signature, ty))
134}
135
136pub(crate) fn check_padding(padding: &[u8]) -> Result<()> {
137 if padding.iter().any(|&b| b != 0) {
138 return Err(Error::NotNormal("padding bytes are not zero"));
139 }
140 Ok(())
141}
142
143pub(crate) fn offset_size_for(len: usize) -> usize {
145 for z in [1usize, 2, 4] {
146 if len <= offset_max(z) {
147 return z;
148 }
149 }
150 8
151}
152
153pub(crate) fn read_offset(bytes: &[u8], z: usize) -> usize {
154 let mut buf = [0u8; 8];
155 buf[..z].copy_from_slice(bytes);
156 u64::from_le_bytes(buf) as usize
157}
158
159#[cfg(test)]
160mod tests {
161 use super::*;
162 use crate::to_bytes;
163
164 fn round_trip(sig: &str, value: &Value) {
165 let ty = Type::parse(sig).unwrap();
166 let bytes = to_bytes(&ty, value).unwrap();
167 let parsed = from_bytes(&ty, &bytes).unwrap();
168 assert_eq!(&parsed, value, "value round-trip for {sig}");
169 assert_eq!(
170 to_bytes(&ty, &parsed).unwrap(),
171 bytes,
172 "byte round-trip for {sig}"
173 );
174 }
175
176 fn checksum_bytes(seed: u8) -> Value {
177 Value::Bytes((0..32).map(|i| seed.wrapping_add(i)).collect())
178 }
179
180 #[test]
181 fn round_trips_scalars_and_simple_containers() {
182 round_trip("y", &Value::Byte(7));
183 round_trip("b", &Value::Bool(true));
184 round_trip("u", &Value::U32(0xdead_beef));
185 round_trip("t", &Value::U64(0x0123_4567_89ab_cdef));
186 round_trip("s", &Value::Str("héllo wörld".into()));
187 round_trip("ay", &Value::Bytes(vec![0, 1, 2, 0, 4]));
188 round_trip(
189 "as",
190 &Value::Array(vec!["a".into(), "".into(), "ccc".into()]),
191 );
192 round_trip(
193 "aay",
194 &Value::Array(vec![Value::Bytes(vec![]), Value::Bytes(vec![1, 2])]),
195 );
196 round_trip("v", &Value::variant(Type::Str, "nested".into()));
197 round_trip(
198 "v",
199 &Value::variant(
200 Type::parse("v").unwrap(),
201 Value::variant(Type::U32, Value::U32(5)),
202 ),
203 );
204 }
205
206 #[test]
209 fn round_trips_the_metadata_only_types() {
210 round_trip("n", &Value::I16(-5));
211 round_trip("q", &Value::U16(5));
212 round_trip("i", &Value::I32(-42));
213 round_trip("h", &Value::I32(7));
214 round_trip("x", &Value::I64(-5));
215 round_trip("d", &Value::double(1.5));
216 round_trip("o", &Value::Str("/a/b".into()));
217 round_trip("g", &Value::Str("ay".into()));
218 round_trip("ms", &Value::Maybe(None));
219 round_trip("ms", &Value::Maybe(Some(Box::new(Value::Str("x".into())))));
220 round_trip(
221 "ms",
222 &Value::Maybe(Some(Box::new(Value::Str(String::new())))),
223 );
224 round_trip("mi", &Value::Maybe(None));
225 round_trip("mi", &Value::Maybe(Some(Box::new(Value::I32(3)))));
226 round_trip(
227 "ami",
228 &Value::Array(vec![
229 Value::Maybe(Some(Box::new(Value::I32(1)))),
230 Value::Maybe(None),
231 ]),
232 );
233 round_trip(
234 "(sid)",
235 &Value::Tuple(vec![
236 Value::Str("a".into()),
237 Value::I32(5),
238 Value::double(-0.5),
239 ]),
240 );
241 }
242
243 #[test]
246 fn maybe_framing() {
247 let ty = Type::parse("ms").unwrap();
248 assert_eq!(
249 to_bytes(&ty, &Value::Maybe(None)).unwrap(),
250 Vec::<u8>::new()
251 );
252 assert_eq!(
253 to_bytes(
254 &ty,
255 &Value::Maybe(Some(Box::new(Value::Str(String::new()))))
256 )
257 .unwrap(),
258 [0, 0]
259 );
260 assert_eq!(
261 from_bytes(&ty, &[]).unwrap(),
262 Value::Maybe(None),
263 "no bytes is Nothing"
264 );
265 assert!(from_bytes(&ty, &[1]).is_err(), "a missing terminator");
266 }
267
268 #[test]
269 fn round_trips_commit_shaped_value() {
270 let metadata = Value::Array(vec![
272 Value::Tuple(vec![
273 "ostree.ref-binding".into(),
274 Value::variant(
275 Type::parse("as").unwrap(),
276 Value::Array(vec!["test/main".into()]),
277 ),
278 ]),
279 Value::Tuple(vec![
280 "version".into(),
281 Value::variant(Type::Str, "1.0".into()),
282 ]),
283 ]);
284 let commit = Value::Tuple(vec![
285 metadata,
286 Value::Bytes(vec![]), Value::Array(vec![]), "subject".into(),
289 "".into(),
290 Value::U64(1_700_000_000u64.swap_bytes()),
291 checksum_bytes(0x10),
292 checksum_bytes(0x50),
293 ]);
294 round_trip("(a{sv}aya(say)sstayay)", &commit);
295 }
296
297 #[test]
298 fn round_trips_summary_shaped_value() {
299 let ref_meta = Value::Array(vec![Value::Tuple(vec![
301 "ostree.commit.timestamp".into(),
302 Value::variant(Type::U64, Value::U64(1_700_000_000u64.swap_bytes())),
303 ])]);
304 let refs = Value::Array(vec![Value::Tuple(vec![
305 "test/main".into(),
306 Value::Tuple(vec![Value::U64(431), checksum_bytes(0x30), ref_meta]),
307 ])]);
308 let global = Value::Array(vec![Value::Tuple(vec![
309 "ostree.summary.mode".into(),
310 Value::variant(Type::Str, "bare".into()),
311 ])]);
312 round_trip("(a(s(taya{sv}))a{sv})", &Value::Tuple(vec![refs, global]));
313 }
314
315 #[test]
316 fn round_trips_delta_shaped_values() {
317 let meta_entry = Value::Tuple(vec![
318 Value::U32(0),
319 checksum_bytes(0x60),
320 Value::U64(4096),
321 Value::U64(8192),
322 Value::Bytes(vec![1; 33]),
323 ]);
324 round_trip("(uayttay)", &meta_entry);
325
326 let fallback = Value::Tuple(vec![
327 Value::Byte(1),
328 checksum_bytes(0x70),
329 Value::U64(100),
330 Value::U64(200),
331 ]);
332 round_trip("(yaytt)", &fallback);
333
334 let modes = Value::Array(vec![Value::Tuple(vec![
335 Value::U32(0o100644u32.swap_bytes()),
336 Value::U32(0),
337 Value::U32(0),
338 ])]);
339 let xattrs = Value::Array(vec![Value::Array(vec![])]);
340 let part = Value::Tuple(vec![
341 modes,
342 xattrs,
343 Value::Bytes(vec![0xaa; 40]),
344 Value::Bytes(vec![b'S', 0x01]),
345 ]);
346 round_trip("(a(uuu)aa(ayay)ayay)", &part);
347 }
348
349 #[test]
350 fn round_trips_offset_size_boundaries() {
351 for n in [250usize, 255, 256, 300, 70_000] {
352 let value = Value::Array(vec![Value::Bytes(vec![0x5a; n])]);
353 round_trip("aay", &value);
354 }
355 }
356
357 #[test]
358 fn array_length_does_not_drive_preallocation() {
359 let data = vec![0xffu8; 1 << 20];
365 assert_eq!(
366 from_bytes(&Type::parse("ab").unwrap(), &data),
367 Err(Error::NotNormal("boolean is not 0 or 1"))
368 );
369 }
370
371 #[test]
372 fn rejects_bad_scalars() {
373 let u = Type::parse("u").unwrap();
374 assert!(from_bytes(&u, &[1, 2, 3]).is_err());
375 assert!(from_bytes(&u, &[1, 2, 3, 4, 5]).is_err());
376 let b = Type::parse("b").unwrap();
377 assert_eq!(
378 from_bytes(&b, &[2]),
379 Err(Error::NotNormal("boolean is not 0 or 1"))
380 );
381 }
382
383 #[test]
384 fn rejects_bad_strings() {
385 let s = Type::parse("s").unwrap();
386 assert!(from_bytes(&s, b"abc").is_err()); assert!(from_bytes(&s, b"a\0b\0").is_err()); assert!(from_bytes(&s, &[0xff, 0xfe, 0]).is_err()); assert!(from_bytes(&s, b"").is_err()); }
391
392 #[test]
393 fn rejects_nonzero_padding() {
394 let ty = Type::parse("(su)").unwrap();
396 let good = to_bytes(&ty, &Value::Tuple(vec!["abcd".into(), Value::U32(9)])).unwrap();
397 assert!(from_bytes(&ty, &good).is_ok());
398 let mut bad = good.clone();
399 bad[6] = 1;
400 assert_eq!(
401 from_bytes(&ty, &bad),
402 Err(Error::NotNormal("padding bytes are not zero"))
403 );
404 }
405
406 #[test]
407 fn rejects_malformed_array_framing() {
408 let ty = Type::parse("as").unwrap();
409 assert!(from_bytes(&ty, &[b'a', 0, 3]).is_err());
411 assert!(from_bytes(&ty, &[b'a', 0, 1, 2]).is_err());
413 let au = Type::parse("au").unwrap();
415 assert!(from_bytes(&au, &[0; 6]).is_err());
416 }
417
418 #[test]
419 fn rejects_malformed_tuples() {
420 let empty = Type::parse("()").unwrap();
421 assert!(from_bytes(&empty, &[0]).is_ok());
422 assert!(from_bytes(&empty, &[1]).is_err());
423 assert!(from_bytes(&empty, &[]).is_err());
424 assert!(from_bytes(&empty, &[0, 0]).is_err());
425 let uuu = Type::parse("(uuu)").unwrap();
427 assert!(from_bytes(&uuu, &[0; 13]).is_err());
428 let su = Type::parse("(su)").unwrap();
430 assert!(from_bytes(&su, b"a\0\0\0\x05\0\0\0\0\0\x02").is_err());
431 }
432
433 #[test]
434 fn rejects_malformed_variants() {
435 let v = Type::parse("v").unwrap();
436 assert!(from_bytes(&v, b"").is_err()); assert!(from_bytes(&v, b"ab").is_err()); assert!(from_bytes(&v, b"a\0d").is_err()); assert!(from_bytes(&v, b"\0").is_err()); }
441
442 #[test]
443 fn rejects_variant_depth_bomb() {
444 let ty = Type::parse("v").unwrap();
447 let mut bytes = vec![1u8, 0, b'y'];
448 for _ in 0..128 {
449 bytes.push(0);
450 bytes.push(b'v');
451 }
452 assert_eq!(from_bytes(&ty, &bytes), Err(Error::DepthExceeded));
453
454 let mut value = Value::variant(Type::Byte, Value::Byte(1));
457 for _ in 0..127 {
458 value = Value::variant(Type::Variant, value);
459 }
460 let ok = to_bytes(&ty, &value).unwrap();
461 assert_eq!(from_bytes(&ty, &ok).unwrap(), value);
462 let bomb = Value::variant(Type::Variant, value);
463 assert_eq!(to_bytes(&ty, &bomb), Err(Error::DepthExceeded));
464 }
465}