unityrs_core/value/mod.rs
1// Ported from UnityPy 1.25.2 (MIT): UnityPy/helpers/TypeTreeHelper.py. See THIRD_PARTY_LICENSES.
2//! The dynamic value: UnityPy's `parse_as_dict()` model, made self-describing.
3//!
4//! Each variant is one Python type with the distinctions the canonical dump
5//! keeps (`docs/CANONICAL_DUMP.md` section 3), so the encoder and the Python
6//! conversion need no typetree, only the names:
7//!
8//! | UnityPy (Boost path) | `Value` |
9//! |---|---|
10//! | `int` (any width, `bool` apart) | `Int`, or `UInt` above `i64::MAX` |
11//! | `float` from a `float` node | `F32` (the bit pattern) |
12//! | `float` from a `double` node | `F64` (the bit pattern) |
13//! | `str` (surrogate-escaped) | `Str` (the raw bytes) |
14//! | `bytes` (`TypelessData`) | `Bytes` (a zero-copy slice of the file) |
15//! | `list` read as one run of a primitive | `Prims` (`vector<UInt8>`/`char` as zero-copy bytes) |
16//! | any other `list` (classes, strings, pairs, vectors) | `List` |
17//! | `tuple` (`pair`; the pure-Python path's aligned primitive arrays) | `Tuple` |
18//! | `dict` (insertion order, `PyDict_SetItem`) | `Dict` |
19//!
20//! Dict keys are [`NodeId`]s of the [`crate::typetree::NodeList`] the map was read with, so a
21//! field costs no allocation and no reference count. A [`Parsed`] holds those
22//! lists: the root tree's first, then each ref-type tree a `ReferencedObject`
23//! read through. [`Map::list`] says which list a map's keys belong to.
24//!
25//! **Memory.** A [`Parsed`] carries the [`Charge`] for every allocation its
26//! value holds (each list, map, tuple and primitive run, at
27//! [`crate::limits::heap_cost`] of its capacity, and the table of its node
28//! lists), charged to the input's meter by the reader before it allocated
29//! them. Dropping the `Parsed` returns them, so values a caller keeps count
30//! against the input's bound for as long as they are kept. So the value
31//! cannot leave its charge: `Parsed` is not `Clone`, its value is reached
32//! by reference only ([`Parsed::value`]), and `Value` is not `Clone` either
33//! (a deep copy would be an uncharged allocation the size of the input's
34//! value). The reader builds every list, map, tuple and run through a
35//! [`ValueBuilder`], the one metered path; `Map` has no growth method.
36//!
37//! **A built value travels with its charge.** The builder hands each list,
38//! map, tuple and run back as a [`Built`]: the value and the charge for its
39//! heap, which no public method separates. A `Built` goes into its parent's
40//! metered vector ([`MeteredVec::push_built`], [`MeteredVec::push_entry`],
41//! [`MeteredVec::set_entry`]), which takes its charge along, or into the
42//! `Parsed` ([`ValueBuilder::finish`]); dropped anywhere, its value and its
43//! charge go together. So no value the builder made can outlive its charge,
44//! whenever the builder itself is dropped (round 5: the builder kept every
45//! charge until `finish`, and a value taken before a builder was dropped
46//! lived on uncharged).
47//!
48//! **What the types pin, and what a test pins.** A `Parsed` has no public
49//! constructor: [`ValueBuilder::finish`] is the only way to one, so every
50//! `Parsed` holds the charges of what it holds. A caller's own value (one to
51//! write, a test's) goes through a builder too, on [`Meter::unlimited`](crate::limits::Meter::unlimited) when
52//! it is not an input's; [`ValueBuilder::scalar`] wraps a value that owns no
53//! heap, and refuses a list, map, tuple or run that owns an allocation. It
54//! cannot refuse a `Str` or `Bytes` that owns a plain `Vec`, since a
55//! `bytes::Bytes` does not say whether it is a slice of a charged buffer
56//! (the file's, [`crate::RawStr::charged`], a decoded block's) or owns
57//! memory no meter saw, so a string or bytes passed to it must be such a
58//! slice (round 6). `Value`'s variants are public data,
59//! though, so the types cannot prove that a value pushed into a vector as a
60//! plain `Value` owns no uncharged heap (a `List` made from a plain `Vec`).
61//! That the reader never does that is its discipline, checked by package
62//! B's counting-allocator test (plan section 7.3), as `tests/memory_model.rs`
63//! checks the builder itself.
64//!
65//! The snippets below must not compile. Stable rustdoc does not check a
66//! `compile_fail` test's error code, so each is written to fail one way
67//! only: the item it names is missing, private or not `Clone`.
68//!
69//! ```compile_fail,E0616
70//! // The value cannot be moved out of its `Parsed` (round 3: the charge
71//! // dropped with the rest of the `Parsed` while the value lived on).
72//! fn take(p: unityrs_core::Parsed) -> unityrs_core::Value {
73//! p.value
74//! }
75//! ```
76//!
77//! ```compile_fail,E0277
78//! // Nor copied without a charge: `Value` is not `Clone`.
79//! fn clone<T: Clone>() {}
80//! clone::<unityrs_core::Value>();
81//! ```
82//!
83//! ```compile_fail,E0277
84//! fn clone<T: Clone>() {}
85//! clone::<unityrs_core::Parsed>();
86//! ```
87//!
88//! ```compile_fail,E0277
89//! fn clone<T: Clone>() {}
90//! clone::<unityrs_core::Map>();
91//! ```
92//!
93//! ```compile_fail,E0277
94//! fn clone<T: Clone>() {}
95//! clone::<unityrs_core::PrimArray>();
96//! ```
97//!
98//! ```compile_fail,E0599
99//! // A map does not grow outside the reader's metered builder.
100//! let _ = unityrs_core::Map::push_unique;
101//! ```
102//!
103//! ```compile_fail,E0599
104//! // Not by insertion either (a test-only helper inside the crate).
105//! let _ = unityrs_core::Map::insert;
106//! ```
107//!
108//! ```compile_fail,E0599
109//! // Nor is one allocated at an unmetered capacity.
110//! let _ = unityrs_core::Map::with_capacity;
111//! ```
112//!
113//! ```compile_fail,E0599
114//! // A `Parsed` is not assembled from charges the caller picked, with any
115//! // arguments: the reader finishes a `ValueBuilder`.
116//! let _ = unityrs_core::Parsed::new;
117//! ```
118//!
119//! ```compile_fail,E0599
120//! // Nor without a charge (round 4): a caller's value goes through a
121//! // builder on `Meter::unlimited()`.
122//! let _ = unityrs_core::Parsed::unmetered;
123//! ```
124//!
125//! ```compile_fail,E0616
126//! // A built value does not leave its charge (round 5): its fields are
127//! // private, and no method moves the value out.
128//! fn take(b: unityrs_core::value::Built) -> unityrs_core::Value {
129//! b.value
130//! }
131//! ```
132//!
133//! ```compile_fail,E0599
134//! let _ = unityrs_core::value::Built::into_value;
135//! ```
136//!
137//! ```
138//! // What the snippets above refuse, a caller does this way.
139//! use unityrs_core::limits::Meter;
140//! use unityrs_core::typetree::{NodeList, NodeRow};
141//! use unityrs_core::{Value, ValueBuilder};
142//! let root = NodeList::trusted(vec![NodeRow::new(0, "int", "v")]).unwrap().into_shared().unwrap();
143//! let b = ValueBuilder::new(&Meter::unlimited(), root).unwrap();
144//! let mut items = b.vec();
145//! items.push(Value::Int(1)).unwrap();
146//! let list = b.list(items);
147//! let p = b.finish(list, 4);
148//! assert_eq!(p.value(), &Value::List(vec![Value::Int(1)]));
149//! ```
150//!
151//! Owner: the scaffold (implemented types and helpers); package B may add
152//! methods and fast paths but not change these signatures.
153
154use bytes::Bytes;
155
156use crate::limits::{Charge, ChargeError, MeteredVec};
157use crate::raw::RawStr;
158use crate::typetree::NodeId;
159
160/// Index of a [`crate::typetree::NodeList`] in [`Parsed::lists`]: the root tree's list, then
161/// one per distinct ref-type tree a `ReferencedObject` read through
162/// (deduplicated by `Arc` pointer, so the count is bounded by the file's ref
163/// types, which the input's meter bounds, and which can pass `u16`). A `u32`
164/// costs nothing: [`Map`] stays 32 bytes.
165pub type ListIx = u32;
166
167/// One object's value, the node lists that name its keys, the reader that
168/// built it, and the charge for the value's memory and the lists' table
169/// (module docs).
170#[derive(Debug)]
171pub struct Parsed {
172 lists: Vec<crate::typetree::SharedNodes>,
173 value: Value,
174 /// Where the read ended, from the object's start (the trailing alignment
175 /// included); compared with `byte_size` by `check_read`. Signed: the
176 /// pure-Python reader's position can end before its start (a negative
177 /// `TypelessData` length moves it back; UnityPy then reports, say,
178 /// "only read -96 bytes"). UnityPyBoost's is never negative.
179 pub bytes_read: i64,
180 read_by: ReadBy,
181 charge: Charge,
182}
183
184/// Which of UnityPy's two readers built a value: `read_typetree` picks
185/// UnityPyBoost's for an object of `byte_size > 0` and the pure-Python one
186/// for `byte_size == 0` (`helpers/TypeTreeHelper.py:146-153`). Each reads
187/// some trees its own way (`CANONICAL_DUMP.md` section 7), and
188/// [`crate::walk::WriteRules::MirrorReader`] writes a value as the reader
189/// that built it reads.
190#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
191pub enum ReadBy {
192 /// UnityPyBoost's reader ([`crate::walk::boost`]), and a value a caller
193 /// builds ([`ValueBuilder::finish`]).
194 #[default]
195 Boost,
196 /// The pure-Python reader ([`crate::walk::python`]).
197 Python,
198}
199
200impl PartialEq for Parsed {
201 /// The value, the lists, `bytes_read` and the reader; the charge is
202 /// bookkeeping.
203 fn eq(&self, other: &Self) -> bool {
204 self.lists == other.lists
205 && self.value == other.value
206 && self.bytes_read == other.bytes_read
207 && self.read_by == other.read_by
208 }
209}
210
211impl Eq for Parsed {}
212
213/// A value read through a typetree. Not `Clone` (module docs).
214#[derive(Debug, PartialEq, Eq)]
215pub enum Value {
216 /// `bool` (any non-zero byte is true).
217 Bool(bool),
218 /// Every integer that fits `i64`.
219 Int(i64),
220 /// A `UInt64`/`FileSize` value above `i64::MAX`.
221 UInt(u64),
222 /// A `float` node's bits, after [`crate::walk::FloatMode`].
223 F32(u32),
224 /// A `double` node's bits, every bit kept.
225 F64(u64),
226 /// A `string`: raw bytes, valid UTF-8 or not.
227 Str(RawStr),
228 /// `TypelessData`.
229 Bytes(Bytes),
230 /// A primitive array read as one run.
231 Prims(PrimArray),
232 /// Any other array.
233 List(Vec<Value>),
234 /// A `pair` (two items), or an aligned primitive array on the pure-Python path.
235 Tuple(Box<[Value]>),
236 /// A class, `PPtr`, registry or `ReferencedObject`.
237 Dict(Map),
238}
239
240/// A run of primitives, decoded to native values (floats as bit patterns).
241#[derive(Debug, PartialEq, Eq)]
242pub enum PrimArray {
243 /// `vector<bool>`.
244 Bool(Box<[bool]>),
245 /// `vector<UInt8>` and `vector<char>`: a zero-copy slice of the file.
246 U8(Bytes),
247 /// `vector<SInt8>`.
248 I8(Box<[i8]>),
249 /// `vector<UInt16>`.
250 U16(Box<[u16]>),
251 /// `vector<SInt16>`.
252 I16(Box<[i16]>),
253 /// `vector<UInt32>`.
254 U32(Box<[u32]>),
255 /// `vector<SInt32>`.
256 I32(Box<[i32]>),
257 /// `vector<UInt64>`.
258 U64(Box<[u64]>),
259 /// `vector<SInt64>`.
260 I64(Box<[i64]>),
261 /// `vector<float>`: bit patterns.
262 F32(Box<[u32]>),
263 /// `vector<double>`: bit patterns.
264 F64(Box<[u64]>),
265}
266
267impl PrimArray {
268 /// Number of elements.
269 #[must_use]
270 pub fn len(&self) -> usize {
271 match self {
272 Self::Bool(v) => v.len(),
273 Self::U8(v) => v.len(),
274 Self::I8(v) => v.len(),
275 Self::U16(v) => v.len(),
276 Self::I16(v) => v.len(),
277 Self::U32(v) | Self::F32(v) => v.len(),
278 Self::I32(v) => v.len(),
279 Self::U64(v) | Self::F64(v) => v.len(),
280 Self::I64(v) => v.len(),
281 }
282 }
283
284 /// Whether the array is empty.
285 #[must_use]
286 pub fn is_empty(&self) -> bool {
287 self.len() == 0
288 }
289}
290
291/// A dict in insertion order with `PyDict_SetItem` semantics. Built whole
292/// ([`ValueBuilder::map`], or [`Map::from_entries`] for a value a caller
293/// makes), never grown in place.
294#[derive(Debug, PartialEq, Eq, Default)]
295pub struct Map {
296 list: ListIx,
297 entries: Vec<(NodeId, Value)>,
298}
299
300impl Map {
301 /// An empty map whose keys name nodes of `Parsed::lists()[list]`.
302 #[must_use]
303 pub fn new(list: ListIx) -> Self {
304 Self {
305 list,
306 entries: Vec::new(),
307 }
308 }
309
310 /// A map a *caller* builds (a value to write, a test's), over entries
311 /// with distinct keys. Not charged to anything: the reader builds maps
312 /// with [`ValueBuilder::map`], which takes a metered vector.
313 #[must_use]
314 pub fn from_entries(list: ListIx, entries: Vec<(NodeId, Value)>) -> Self {
315 Self { list, entries }
316 }
317
318 /// Which node list names the keys.
319 #[must_use]
320 pub fn list(&self) -> ListIx {
321 self.list
322 }
323
324 /// `PyDict_SetItem` on an unmetered map, for the scaffold's tests: an
325 /// existing key keeps its position and takes the new value. Not in the
326 /// library: the reader grows a class's entries in a metered vector, and
327 /// a repeated name replaces its first entry's value in place with
328 /// `MeteredVec::set_entry`, which keeps the new value's charge (plan
329 /// 3.10, "Linear dicts").
330 #[cfg(test)]
331 pub(crate) fn insert(&mut self, key: NodeId, value: Value) {
332 match self.entries.iter_mut().find(|(k, _)| *k == key) {
333 Some((_, v)) => *v = value,
334 None => self.entries.push((key, value)),
335 }
336 }
337
338 /// The entries' capacity (tests: a finished dict holds no spare
339 /// entries, plan 3.10, "Bounds").
340 #[cfg(test)]
341 pub(crate) fn capacity(&self) -> usize {
342 self.entries.capacity()
343 }
344
345 /// The entries in order.
346 #[must_use]
347 pub fn entries(&self) -> &[(NodeId, Value)] {
348 &self.entries
349 }
350
351 /// The value under `key`.
352 #[must_use]
353 pub fn get(&self, key: NodeId) -> Option<&Value> {
354 self.entries.iter().find(|(k, _)| *k == key).map(|(_, v)| v)
355 }
356
357 /// Number of entries.
358 #[must_use]
359 pub fn len(&self) -> usize {
360 self.entries.len()
361 }
362
363 /// Whether the map is empty.
364 #[must_use]
365 pub fn is_empty(&self) -> bool {
366 self.entries.is_empty()
367 }
368}
369
370/// A list, map, tuple or primitive run a [`ValueBuilder`] made, with the
371/// charge for its heap (module docs). No public method separates the two:
372/// the value goes on only into a parent's metered vector
373/// ([`MeteredVec::push_built`], [`MeteredVec::push_entry`],
374/// [`MeteredVec::set_entry`]) or into the `Parsed` ([`ValueBuilder::finish`]),
375/// each of which takes the charge along, and dropped anywhere the two go
376/// together.
377#[derive(Debug)]
378pub struct Built {
379 value: Value,
380 charge: Charge,
381}
382
383impl Built {
384 /// The value, by reference.
385 #[must_use]
386 pub fn value(&self) -> &Value {
387 &self.value
388 }
389
390 /// The charge for the value's heap.
391 #[must_use]
392 pub fn charge(&self) -> &Charge {
393 &self.charge
394 }
395}
396
397impl MeteredVec<Value> {
398 /// Appends a built value (a list's or a tuple's item); this vector keeps
399 /// its charge from then on. A refused growth drops both.
400 pub fn push_built(&mut self, item: Built) -> Result<(), ChargeError> {
401 self.push_charged(item.value, item.charge)
402 }
403}
404
405impl MeteredVec<(NodeId, Value)> {
406 /// Appends a dict entry whose value was built; this vector keeps its
407 /// charge from then on. A refused growth drops both.
408 pub fn push_entry(&mut self, key: NodeId, item: Built) -> Result<(), ChargeError> {
409 self.push_charged((key, item.value), item.charge)
410 }
411
412 /// Replaces the value of entry `pos` with a built one, keeping its key
413 /// and position (a repeated name's `PyDict_SetItem`, plan 3.10's linear
414 /// dict), and keeps its charge. The value replaced is dropped; its charge
415 /// stays with this vector until it drops (charged, never under). False,
416 /// with `item` dropped whole, when `pos` is not an entry.
417 pub fn set_entry(&mut self, pos: usize, item: Built) -> bool {
418 let Built { value, charge } = item;
419 match self.as_mut_slice().get_mut(pos) {
420 Some((_, v)) => {
421 *v = value;
422 self.keep_charge(charge);
423 true
424 }
425 None => false,
426 }
427 }
428}
429
430/// A primitive run, as the reader collects it, for [`ValueBuilder::prims`].
431#[derive(Debug)]
432pub enum PrimRun {
433 /// `vector<bool>`.
434 Bool(MeteredVec<bool>),
435 /// `vector<SInt8>`.
436 I8(MeteredVec<i8>),
437 /// `vector<UInt16>`.
438 U16(MeteredVec<u16>),
439 /// `vector<SInt16>`.
440 I16(MeteredVec<i16>),
441 /// `vector<UInt32>`.
442 U32(MeteredVec<u32>),
443 /// `vector<SInt32>`.
444 I32(MeteredVec<i32>),
445 /// `vector<UInt64>`.
446 U64(MeteredVec<u64>),
447 /// `vector<SInt64>`.
448 I64(MeteredVec<i64>),
449 /// `vector<float>`: bit patterns.
450 F32(MeteredVec<u32>),
451 /// `vector<double>`: bit patterns.
452 F64(MeteredVec<u64>),
453}
454
455impl Parsed {
456 /// A value with lists the crate's tests make (65,537 copies of one list,
457 /// which a builder would deduplicate), charging nothing.
458 #[cfg(test)]
459 pub(crate) fn for_tests(
460 lists: Vec<crate::typetree::SharedNodes>,
461 value: Value,
462 bytes_read: i64,
463 ) -> Self {
464 Self {
465 lists,
466 value,
467 bytes_read,
468 read_by: ReadBy::Boost,
469 charge: Charge::zero(&crate::limits::Meter::unlimited()),
470 }
471 }
472
473 /// The same value, marked as `read_by`'s.
474 pub(crate) fn with_read_by(mut self, read_by: ReadBy) -> Self {
475 self.read_by = read_by;
476 self
477 }
478
479 /// The reader that built the value ([`ReadBy`]).
480 #[must_use]
481 pub fn read_by(&self) -> ReadBy {
482 self.read_by
483 }
484
485 /// The value. By reference only: the value lives as long as its charge.
486 #[must_use]
487 pub fn value(&self) -> &Value {
488 &self.value
489 }
490
491 /// The value, for the copy that cuts its slices loose from the buffer
492 /// they keep alive ([`crate::pin`]), which changes no part of it but
493 /// where its bytes live.
494 pub(crate) fn value_mut(&mut self) -> &mut Value {
495 &mut self.value
496 }
497
498 /// The charge for the value's memory and the lists' table.
499 #[must_use]
500 pub fn charge(&self) -> &Charge {
501 &self.charge
502 }
503
504 /// The node lists; `[0]` is the tree the object was read with.
505 #[must_use]
506 pub fn lists(&self) -> &[crate::typetree::SharedNodes] {
507 &self.lists
508 }
509
510 /// The name of `key` in `map` (empty if the map's list is unknown).
511 #[must_use]
512 pub fn key_name(&self, map: &Map, key: NodeId) -> &[u8] {
513 usize::try_from(map.list)
514 .ok()
515 .and_then(|i| self.lists.get(i))
516 .map_or(&[], |l| l.name(key))
517 }
518
519 /// A map's entries with their names.
520 pub fn entries<'a>(
521 &'a self,
522 map: &'a Map,
523 ) -> impl ExactSizeIterator<Item = (&'a [u8], &'a Value)> + 'a {
524 map.entries()
525 .iter()
526 .map(move |(k, v)| (self.key_name(map, *k), v))
527 }
528
529 /// The value under `name` in `map`.
530 #[must_use]
531 pub fn field<'a>(&'a self, map: &'a Map, name: &[u8]) -> Option<&'a Value> {
532 self.entries(map).find(|(n, _)| *n == name).map(|(_, v)| v)
533 }
534
535 /// The value UnityPy's object mode gives the attribute `name` of `map`'s
536 /// class (`parse_class`, `UnityPyBoost/TypeTreeHelper.cpp:458-583`): its
537 /// keys are the children's cleaned names
538 /// ([`cleans_to`](crate::walk::write::cleans_to)), set in node order, so
539 /// of the children that clean to `name` the last wins. A dict merges a
540 /// repeated raw name into its first entry, which keeps the last value, so
541 /// the winner is found among the node's children and its value under its
542 /// raw name; a map whose node is not known (one a caller built) takes the
543 /// last entry that cleans to `name`.
544 #[must_use]
545 pub fn attr<'a>(&'a self, map: &'a Map, name: &[u8]) -> Option<&'a Value> {
546 let list = usize::try_from(map.list)
547 .ok()
548 .and_then(|i| self.lists.get(i));
549 // The first entry's key is the class's first child, which follows
550 // its node in pre-order.
551 let node = map
552 .entries()
553 .first()
554 .and_then(|(k, _)| k.0.checked_sub(1))
555 .map(crate::typetree::NodeId);
556 let kids = match (list, node) {
557 (Some(l), Some(n)) if l.children(n).first() == map.entries().first().map(|e| &e.0) => {
558 l.children(n)
559 }
560 _ => &[],
561 };
562 if let Some(list) = list.filter(|_| !kids.is_empty()) {
563 let raw = kids
564 .iter()
565 .rev()
566 .map(|k| list.name(*k))
567 .find(|n| crate::walk::write::cleans_to(n, name))?;
568 return self.field(map, raw);
569 }
570 self.entries(map)
571 .filter(|(n, _)| crate::walk::write::cleans_to(n, name))
572 .last()
573 .map(|(_, v)| v)
574 }
575
576 /// Follows dict fields from the root value: `get(&[b"m_Name"])`.
577 #[must_use]
578 pub fn get(&self, path: &[&[u8]]) -> Option<&Value> {
579 let mut v = &self.value;
580 for name in path {
581 let Value::Dict(m) = v else { return None };
582 v = self.field(m, name)?;
583 }
584 Some(v)
585 }
586}
587
588impl Value {
589 /// The integer, if this is one (not a bool, as UnityPy's dict keeps them apart).
590 #[must_use]
591 pub fn as_i64(&self) -> Option<i64> {
592 match self {
593 Self::Int(i) => Some(*i),
594 Self::UInt(u) => i64::try_from(*u).ok(),
595 _ => None,
596 }
597 }
598
599 /// The unsigned integer, if this is a non-negative integer.
600 #[must_use]
601 pub fn as_u64(&self) -> Option<u64> {
602 match self {
603 Self::Int(i) => u64::try_from(*i).ok(),
604 Self::UInt(u) => Some(*u),
605 _ => None,
606 }
607 }
608
609 /// The float as Python holds it (an `F32` widened exactly).
610 #[must_use]
611 pub fn as_f64(&self) -> Option<f64> {
612 match self {
613 Self::F32(b) => Some(f64::from(f32::from_bits(*b))),
614 Self::F64(b) => Some(f64::from_bits(*b)),
615 _ => None,
616 }
617 }
618
619 /// The bool.
620 #[must_use]
621 pub fn as_bool(&self) -> Option<bool> {
622 match self {
623 Self::Bool(b) => Some(*b),
624 _ => None,
625 }
626 }
627
628 /// The string, when it is valid UTF-8.
629 #[must_use]
630 pub fn as_str(&self) -> Option<&str> {
631 match self {
632 Self::Str(s) => s.to_str(),
633 _ => None,
634 }
635 }
636
637 /// Raw bytes: a string's, `TypelessData`'s, or a `vector<UInt8>`'s.
638 #[must_use]
639 pub fn as_bytes(&self) -> Option<&[u8]> {
640 match self {
641 Self::Str(s) => Some(s.as_bytes()),
642 Self::Bytes(b) | Self::Prims(PrimArray::U8(b)) => Some(b),
643 _ => None,
644 }
645 }
646
647 /// The zero-copy buffer of `TypelessData` or a `vector<UInt8>`, for a
648 /// hand-off to another stage without copying.
649 #[must_use]
650 pub fn as_shared_bytes(&self) -> Option<&Bytes> {
651 match self {
652 Self::Bytes(b) | Self::Prims(PrimArray::U8(b)) => Some(b),
653 _ => None,
654 }
655 }
656
657 /// The map, if this is a dict.
658 #[must_use]
659 pub fn as_dict(&self) -> Option<&Map> {
660 match self {
661 Self::Dict(m) => Some(m),
662 _ => None,
663 }
664 }
665}
666
667mod builder;
668mod edit;
669mod flat;
670
671pub use builder::ValueBuilder;
672
673#[cfg(test)]
674mod tests;