Skip to main content

unityrs_texture/
fetch.rs

1//! A texture's inline bytes, or its streamed resource. Own bundle rows are
2//! searched before the Environment, candidates in order, containers from
3//! inner to outer, and directory rows from last to first. Each core call
4//! remains separately observable through [`Hooks`].
5
6use std::sync::Arc;
7
8use unityrs_core::env::{Environment, resource_candidates};
9use unityrs_core::files::{BundleFile, File, ParentKind, SerializedFile};
10use unityrs_core::limits::{ChargeError, Meter};
11use unityrs_core::pystr::{lower_eq, ntpath_basename, simplify_name_vec};
12use unityrs_core::{Bytes, RawStr};
13
14/// `m_StreamData`, retaining signed and wide integers until read.
15#[derive(Clone, Debug)]
16pub struct Stream {
17    /// The resource path as read.
18    pub path: RawStr,
19    /// The reader's offset.
20    pub offset: i128,
21    /// The read size; -1 reads to the end.
22    pub size: i128,
23}
24
25/// The core range, or a Python slice of the whole resource.
26#[derive(Clone, Copy, Debug, PartialEq, Eq)]
27pub enum Span {
28    /// Offset and size, both representable by the core range API.
29    Range(u64, u64),
30    /// Signed or wider indices, clamped when the resource length is known.
31    Slice(i128, i128),
32}
33
34impl Stream {
35    /// The memory reader's `read(size)` at `offset`.
36    #[must_use]
37    pub fn span(&self) -> Span {
38        if self.size == 0 {
39            return Span::Range(0, 0);
40        }
41        if self.size == -1 {
42            return Span::Slice(self.offset, i128::MAX);
43        }
44        let end = self.offset.checked_add(self.size);
45        match (
46            u64::try_from(self.offset),
47            u64::try_from(self.size),
48            end.and_then(|e| u64::try_from(e).ok()),
49        ) {
50            (Ok(o), Ok(n), Some(_)) => Span::Range(o, n),
51            _ => Span::Slice(self.offset, end.unwrap_or(i128::MAX)),
52        }
53    }
54}
55
56/// Python's `data[start:stop]`, including negative indices and clamping.
57#[must_use]
58pub fn python_slice(len: usize, start: i128, stop: i128) -> std::ops::Range<usize> {
59    let n = i128::try_from(len).unwrap_or(i128::MAX);
60    let at = |i: i128| {
61        let i = if i < 0 { i.saturating_add(n) } else { i };
62        usize::try_from(i.clamp(0, n)).unwrap_or(len)
63    };
64    let (a, b) = (at(start), at(stop));
65    a..b.max(a)
66}
67
68/// Fetch failures preserve whether the Environment or an own row failed,
69/// so exporters can assign their own resource and data skip reasons.
70#[derive(Debug, thiserror::Error)]
71pub enum Error {
72    /// A name, lookup work, or other metered helper was refused.
73    #[error(transparent)]
74    Charge(#[from] ChargeError),
75    /// Opening or reading an own directory row failed.
76    #[error("texture data: {0}")]
77    Data(#[source] unityrs_core::Error),
78    /// The Environment failed to resolve or read the resource.
79    #[error("texture resource: {error}")]
80    Resource {
81        /// The original Environment failure.
82        #[source]
83        error: unityrs_core::Error,
84        /// The original stream path, sharing its object's storage.
85        path: RawStr,
86    },
87    /// An own row is a SerializedFile, which cannot be read as bytes.
88    #[error("texture resource is a SerializedFile")]
89    Serialized,
90    /// An own row is a WebFile, unsupported as a resource reader.
91    #[error("texture resource is a WebFile")]
92    Web,
93}
94
95/// Per-core-call hooks. Map errors *inside* the caller's refusal probe;
96/// Environment calls can additionally inspect evictions after the probe.
97pub trait Hooks {
98    /// The exporter's classified error.
99    type Error;
100
101    /// One core call, independently probed.
102    fn probe<T>(&self, f: impl FnOnce() -> Result<T, Error>) -> Result<T, Self::Error>
103    where
104        Self: Sized;
105
106    /// One Environment call, independently probed and observed.
107    fn env_call<T>(&self, f: impl FnOnce() -> Result<T, Error>) -> Result<T, Self::Error>
108    where
109        Self: Sized;
110
111    /// A failed own row whose type is known after its successful core call.
112    fn row_error(&self, error: Error) -> Self::Error;
113}
114
115struct Direct;
116
117impl Hooks for Direct {
118    type Error = Error;
119
120    fn probe<T>(&self, f: impl FnOnce() -> Result<T, Error>) -> Result<T, Error> {
121        f()
122    }
123
124    fn env_call<T>(&self, f: impl FnOnce() -> Result<T, Error>) -> Result<T, Error> {
125        f()
126    }
127
128    fn row_error(&self, error: Error) -> Error {
129        error
130    }
131}
132
133fn parent_bundle(kind: Option<&ParentKind>) -> Option<Arc<BundleFile>> {
134    match kind? {
135        ParentKind::Bundle { bundle, .. } => bundle.upgrade(),
136        ParentKind::Web { .. } => None,
137    }
138}
139
140fn read_span(s: &Stream) -> (u64, u64, Option<(i128, i128)>) {
141    match s.span() {
142        Span::Range(offset, size) => (offset, size, None),
143        Span::Slice(start, stop) => (0, u64::MAX, Some((start, stop))),
144    }
145}
146
147fn sliced(bytes: Bytes, slice: Option<(i128, i128)>) -> Bytes {
148    match slice {
149        None => bytes,
150        Some((start, stop)) => bytes.slice(python_slice(bytes.len(), start, stop)),
151    }
152}
153
154fn own_chain<H: Hooks>(
155    from: &SerializedFile,
156    s: &Stream,
157    meter: &Arc<Meter>,
158    hooks: &H,
159) -> Result<Option<Bytes>, H::Error> {
160    let work = |n: usize| {
161        hooks.probe(|| {
162            meter
163                .count_decode(u64::try_from(n).unwrap_or(u64::MAX))
164                .map_err(Error::Charge)
165        })
166    };
167    work(s.path.len())?;
168    for candidate in &resource_candidates(&s.path) {
169        work(candidate.len())?;
170        let name = hooks.probe(|| candidate.joined_vec(meter).map_err(Error::Charge))?;
171        let key =
172            hooks.probe(|| simplify_name_vec(name.as_slice(), meter).map_err(Error::Charge))?;
173        let mut container = parent_bundle(from.parent().map(|p| &p.kind));
174        while let Some(b) = container {
175            work(b.directory().len().saturating_add(1))?;
176            for (i, row) in b.directory().iter().enumerate().rev() {
177                work(row.path.len())?;
178                if !lower_eq(ntpath_basename(row.path.as_bytes()), key.as_slice()) {
179                    continue;
180                }
181                match hooks.probe(|| b.entry(i).map_err(Error::Data))? {
182                    File::Raw(_) => {
183                        let (offset, size, slice) = read_span(s);
184                        let bytes = hooks.probe(|| {
185                            b.entry_range(i, offset..offset.saturating_add(size))
186                                .map_err(Error::Data)
187                        })?;
188                        return Ok(Some(sliced(bytes, slice)));
189                    }
190                    File::Serialized(_) => return Err(hooks.row_error(Error::Serialized)),
191                    File::Web(_) => return Err(hooks.row_error(Error::Web)),
192                    File::Bundle(_) => {}
193                }
194            }
195            container = parent_bundle(b.parent().map(|p| &p.kind));
196        }
197    }
198    Ok(None)
199}
200
201/// Inline data wins. Otherwise search own rows, then the Environment.
202/// Missing streams and empty paths give empty data. Returned bytes share
203/// their existing allocation; all name and resource allocations are
204/// charged by the core before allocation, and lookup work is metered.
205pub fn fetch(
206    env: &Environment,
207    from: &Arc<SerializedFile>,
208    inline: &Bytes,
209    stream: Option<&Stream>,
210    meter: &Arc<Meter>,
211) -> Result<Bytes, Error> {
212    fetch_with(env, from, inline, stream, meter, &Direct)
213}
214
215/// [`fetch`] with separately classified probes around every core call.
216pub fn fetch_with<H: Hooks>(
217    env: &Environment,
218    from: &Arc<SerializedFile>,
219    inline: &Bytes,
220    stream: Option<&Stream>,
221    meter: &Arc<Meter>,
222    hooks: &H,
223) -> Result<Bytes, H::Error> {
224    if !inline.is_empty() {
225        return Ok(inline.clone());
226    }
227    let Some(s) = stream.filter(|s| !s.path.is_empty()) else {
228        return Ok(Bytes::new());
229    };
230    if let Some(bytes) = own_chain(from, s, meter, hooks)? {
231        return Ok(bytes);
232    }
233    let (offset, size, slice) = read_span(s);
234    hooks.env_call(|| {
235        env.resource(from, &s.path, offset, size)
236            .map(|bytes| sliced(bytes, slice))
237            .map_err(|error| Error::Resource {
238                error,
239                path: s.path.clone(),
240            })
241    })
242}
243
244const _: () = crate::send_sync::<Stream>();
245const _: () = crate::send_sync::<Span>();
246const _: () = crate::send_sync::<Error>();
247const _: () = crate::send_sync::<dyn Hooks<Error = Error> + Send + Sync>();