day_spec/resource.rs
1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! Bundled resources: efficient random read-only access to app-declared data, backed by each
5//! toolkit's native resource mechanism (DESIGN.md §18.3).
6//!
7//! `day build` stages the files declared under a project's `assets/` (and `images/`) into each
8//! platform's native resource store, **uncompressed where possible** so the runtime can hand back a
9//! zero-copy view. At runtime `resource("name")` returns a [`Resource`] whose bytes are borrowed
10//! directly from that store: an mmap of a bundle file on Apple, the NDK `AAssetManager` buffer on
11//! Android, `g_resources_lookup_data` on GTK, `QResource::data` on Qt, the rawfile fd on ArkUI.
12//!
13//! The active backend registers its opener once via [`set_resource_opener`]; if none is registered
14//! (desktop dev, host tests, and the Apple backends, whose native mechanism *is* a bundle file) the
15//! default opener mmaps the file resolved from `DAY_ASSET_ROOT` or the app bundle.
16
17use std::any::Any;
18use std::borrow::Cow;
19use std::path::PathBuf;
20use std::sync::OnceLock;
21
22// ---------------------------------------------------------------------------
23// Typed resource identifiers (§18.5)
24//
25// `image(...)`, `resource(...)`, and `Font::custom(...)` take these newtypes rather than a bare
26// `&str`. Every value is meant to come from a generated `res::images/assets/fonts::…` constant
27// (`day-build`), so referencing a resource that isn't bundled is a compile error and the available
28// names autocomplete. A string *literal* does not coerce, which is what turns "present" from a
29// convention into a guarantee; a name only known at runtime uses the explicit `::dynamic`
30// escape hatch (or, for images/assets, `From<String>`).
31// ---------------------------------------------------------------------------
32
33macro_rules! resource_name {
34 ($(#[$m:meta])* $name:ident, $what:literal) => {
35 $(#[$m])*
36 #[derive(Clone, Debug, PartialEq, Eq)]
37 pub struct $name(Cow<'static, str>);
38
39 impl $name {
40 #[doc = concat!("A ", $what, " known at compile time — the form the generated `res::…` constants use.")]
41 pub const fn from_static(name: &'static str) -> Self {
42 $name(Cow::Borrowed(name))
43 }
44 #[doc = concat!("Escape hatch for a ", $what, " computed at runtime (no build-time presence guarantee).")]
45 pub fn dynamic(name: impl Into<String>) -> Self {
46 $name(Cow::Owned(name.into()))
47 }
48 /// The underlying wire name the backend resolves by.
49 pub fn as_str(&self) -> &str {
50 &self.0
51 }
52 }
53
54 // Owned strings convert (dynamic names); a `&str` literal does not, so
55 // `image("typo")` / `resource("typo")` fail to compile.
56 impl From<String> for $name {
57 fn from(s: String) -> Self {
58 $name(Cow::Owned(s))
59 }
60 }
61
62 impl std::fmt::Display for $name {
63 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
64 f.write_str(&self.0)
65 }
66 }
67 };
68}
69
70resource_name!(
71 /// The bundled-image name that [`resource()`](crate::resource()) callers resolve by (the file stem).
72 ImageName,
73 "bundled-image name"
74);
75resource_name!(
76 /// The bundled-data name that [`resource`] resolves by: the file's path relative to
77 /// `resource/assets/`, `/`-separated (a top-level file is just its file name, extension
78 /// included).
79 AssetName,
80 "bundled-asset name"
81);
82resource_name!(
83 /// A bundled-asset directory (§18.5): a folder's path relative to `resource/assets/`,
84 /// `/`-separated, no trailing slash. The generated `res::assets::…` tree carries one
85 /// constant per folder, sharing its module's name: `res::assets::web::minisite` is the
86 /// `AssetDir` and `res::assets::web::minisite::index_html` a file within it.
87 AssetDir,
88 "bundled-asset directory"
89);
90
91impl AssetDir {
92 /// Name a file under this directory, for [`resource`]: the escape hatch for paths
93 /// composed at runtime (`dir.join("posts/1.html")`); prefer the generated file constants
94 /// where the path is known.
95 #[must_use]
96 pub fn join(&self, rel: &str) -> AssetName {
97 AssetName::dynamic(format!("{}/{}", self.as_str(), rel.trim_start_matches('/')))
98 }
99}
100resource_name!(
101 /// The bundled-vector name that [`resource()`](crate::resource()) callers resolve by (docs/vectors.md):
102 /// the stem of a `resource/vectors/` SVG (or `.symbolset` bundle). Vectors and images share one
103 /// per-backend resolution namespace; staging guarantees every vector name resolves as whatever
104 /// form that backend loads natively (a `VectorDrawable`, a catalog entry, a rasterized PNG).
105 VectorName,
106 "bundled-vector name"
107);
108
109/// Vector and image names resolve through the same per-backend channel (nav-item icons, the
110/// toolbar's `.image(…)`, `bar_action`, all name-based); this conversion is that shared
111/// namespace made explicit.
112impl From<VectorName> for ImageName {
113 fn from(v: VectorName) -> ImageName {
114 ImageName::dynamic(v.as_str().to_owned())
115 }
116}
117
118/// The family name of a bundled custom font, feeding `Font::custom`. Holds a `&'static str` (so
119/// `Font` stays `Copy`); generated `res::fonts::…` constants supply it. The untyped
120/// `Font::Custom(&'static str, f64)` variant remains the escape hatch for a family known another way.
121#[derive(Clone, Copy, Debug, PartialEq, Eq)]
122pub struct FontFamily(&'static str);
123
124impl FontFamily {
125 /// A font family known at compile time: the form the generated `res::fonts::…` constants use.
126 #[must_use]
127 pub const fn from_static(family: &'static str) -> Self {
128 FontFamily(family)
129 }
130 /// The underlying family name (what `Font::Custom` carries).
131 #[must_use]
132 pub const fn as_str(&self) -> &'static str {
133 self.0
134 }
135}
136
137impl std::fmt::Display for FontFamily {
138 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
139 f.write_str(self.0)
140 }
141}
142
143/// A handle to a bundled resource's bytes with efficient random read-only access.
144///
145/// The bytes stay valid for the lifetime of the `Resource`: it owns a guard (an mmap, a native
146/// `GBytes`/`QResource`/`AAsset` handle, or an owned buffer) that keeps the backing store alive.
147/// `Resource` is neither `Send` nor `Sync`; like the rest of the day runtime it is used on the
148/// main/UI thread.
149pub struct Resource {
150 ptr: *const u8,
151 len: usize,
152 /// Keeps the backing store alive while `ptr`/`len` are borrowed from it.
153 _guard: Box<dyn Any>,
154}
155
156impl Resource {
157 /// Build a `Resource` from a raw byte view plus the guard that owns it. Backends call this from
158 /// their opener after obtaining a zero-copy pointer from the native resource API.
159 ///
160 /// # Safety
161 /// `ptr` must point to `len` valid, immutable bytes that remain valid for as long as `guard` is
162 /// alive, and `guard` must own (and keep alive) that backing store.
163 #[must_use]
164 pub unsafe fn from_raw(ptr: *const u8, len: usize, guard: Box<dyn Any>) -> Resource {
165 Resource {
166 ptr,
167 len,
168 _guard: guard,
169 }
170 }
171
172 /// Build a `Resource` from owned bytes: the copy fallback for backends that cannot expose a
173 /// stable pointer into their store (or when a native API only offers a read-into-buffer call).
174 #[must_use]
175 pub fn from_vec(bytes: Vec<u8>) -> Resource {
176 let boxed: Box<[u8]> = bytes.into_boxed_slice();
177 let ptr = boxed.as_ptr();
178 let len = boxed.len();
179 // Moving the box moves the (fat) pointer, not the heap allocation, so `ptr` stays valid.
180 Resource {
181 ptr,
182 len,
183 _guard: Box::new(boxed),
184 }
185 }
186
187 /// Total byte length of the resource.
188 #[must_use]
189 pub fn len(&self) -> usize {
190 self.len
191 }
192
193 /// Whether the resource is empty.
194 #[must_use]
195 pub fn is_empty(&self) -> bool {
196 self.len == 0
197 }
198
199 /// A zero-copy view of the full contents. Backed directly by the native store (no allocation,
200 /// no copy). Wrap in [`std::io::Cursor`] for `Read`/`Seek`-style access.
201 #[must_use]
202 pub fn as_slice(&self) -> &[u8] {
203 // Safety: `ptr`/`len` describe a valid immutable region kept alive by `_guard`.
204 unsafe { std::slice::from_raw_parts(self.ptr, self.len) }
205 }
206
207 /// Random-access read: copy up to `buf.len()` bytes starting at `offset` into `buf`, returning
208 /// the number of bytes copied (0 if `offset >= len`). A direct `memcpy` from the backing store,
209 /// no allocation: the efficient primitive for seeking around a large embedded blob.
210 pub fn read_at(&self, offset: usize, buf: &mut [u8]) -> usize {
211 let data = self.as_slice();
212 if offset >= data.len() {
213 return 0;
214 }
215 let n = buf.len().min(data.len() - offset);
216 buf[..n].copy_from_slice(&data[offset..offset + n]);
217 n
218 }
219
220 /// Copy the full contents into a freshly allocated `Vec`.
221 #[must_use]
222 pub fn to_vec(&self) -> Vec<u8> {
223 self.as_slice().to_vec()
224 }
225}
226
227/// A backend's resource opener: maps a declared name (e.g. `"stations.json"`) to its bytes, or
228/// `None` if there is no such resource.
229pub type ResourceOpener = fn(&str) -> Option<Resource>;
230
231static OPENER: OnceLock<ResourceOpener> = OnceLock::new();
232
233/// Register the active backend's resource opener (Android `AAssetManager`, GTK `GResource`, Qt
234/// `QResource`, ArkUI rawfile, …). Called once during backend init. A second call is ignored, so a
235/// backend that shares the default file opener need not call this at all.
236pub fn set_resource_opener(opener: ResourceOpener) {
237 let _ = OPENER.set(opener);
238}
239
240/// Open a bundled resource by name for efficient random read-only access.
241///
242/// Returns `None` if the backend has no resource with that name. Takes an [`AssetName`]: pass a
243/// generated `res::assets::…` constant (e.g. `resource(res::assets::stations_json)`) for a checked,
244/// guaranteed-present reference, or [`AssetName::dynamic`] for a name known only at runtime.
245pub fn resource(name: impl Into<AssetName>) -> Option<Resource> {
246 let name = name.into();
247 let name = name.as_str();
248 match OPENER.get() {
249 Some(open) => open(name),
250 None => default_open(name),
251 }
252}
253
254/// The default opener: mmap the file resolved from `DAY_ASSET_ROOT` (dev runs / `day launch`) or the
255/// app bundle's `Resources/assets`. This is the Apple backends' native path (a plain bundle file)
256/// and the desktop/host-test path.
257fn default_open(name: &str) -> Option<Resource> {
258 let path = resolve_resource_path(name)?;
259 let file = std::fs::File::open(&path).ok()?;
260 // Safety: we open read-only and never mutate the mapping; the `Mmap` guard keeps it alive.
261 let mmap = unsafe { memmap2::Mmap::map(&file).ok()? };
262 let ptr = mmap.as_ptr();
263 let len = mmap.len();
264 Some(unsafe { Resource::from_raw(ptr, len, Box::new(mmap)) })
265}
266
267/// Resolve a data-resource name to an on-disk path: `DAY_ASSET_ROOT` first (dev / CLI launch), then
268/// bundle-relative locations next to the executable (macOS `.app`, Linux `share`).
269fn resolve_resource_path(name: &str) -> Option<PathBuf> {
270 for var in ASSET_ROOT_VARS {
271 if let Ok(root) = std::env::var(var) {
272 let p = PathBuf::from(root).join(name);
273 if p.exists() {
274 return Some(p);
275 }
276 }
277 }
278 if let Ok(exe) = std::env::current_exe()
279 && let Some(dir) = exe.parent()
280 {
281 for rel in ["../Resources/assets", "Resources/assets", "assets"] {
282 let p = dir.join(rel).join(name);
283 if p.exists() {
284 return Some(p);
285 }
286 }
287 }
288 None
289}
290
291/// Resolve a data-asset file (a `/`-relative path under `resource/assets/`) to its on-disk
292/// location, for consumers that must hand a native API a path rather than bytes: lottie-ios
293/// takes a filepath, and its by-name initializer would otherwise look only at the bundle root,
294/// where Day stages nothing. Same probe order as [`resource`]: `DAY_ASSET_ROOT` (dev /
295/// `day launch`), then the bundle-relative roots.
296/// The roots a dev run probes for data assets, in order: the project's own `resource/assets/`,
297/// then the tree `day build` stages the assets its pieces ship into (docs/extending.md). A
298/// packaged app has one merged `assets/` directory beside the binary and needs neither.
299const ASSET_ROOT_VARS: [&str; 2] = ["DAY_ASSET_ROOT", "DAY_PIECE_ASSET_ROOT"];
300
301#[must_use]
302pub fn resolve_asset_file(name: &str) -> Option<PathBuf> {
303 resolve_resource_path(name)
304}
305
306/// Resolve a data-asset directory (an [`AssetDir`]'s `/`-relative path) to its on-disk
307/// location, for consumers whose local-content channel is a file URL, like the inline web
308/// view on the Apple backends (day-piece-webview's docs/webview.md). Same probe order as file
309/// resolution: `DAY_ASSET_ROOT` (dev / `day launch`), then the bundle-relative roots.
310#[must_use]
311pub fn resolve_asset_dir(rel: &str) -> Option<PathBuf> {
312 // Canonicalized: consumers derive URLs from this path, and a literal `..` segment (the
313 // bundle probe below goes through `MacOS/../Resources`) breaks prefix comparison against
314 // the standardized URLs engines report back.
315 let canon = |p: PathBuf| p.canonicalize().ok().filter(|c| c.is_dir());
316 for var in ASSET_ROOT_VARS {
317 if let Ok(root) = std::env::var(var)
318 && let Some(p) = canon(PathBuf::from(root).join(rel))
319 {
320 return Some(p);
321 }
322 }
323 if let Ok(exe) = std::env::current_exe()
324 && let Some(dir) = exe.parent()
325 {
326 for base in ["../Resources/assets", "Resources/assets", "assets"] {
327 if let Some(p) = canon(dir.join(base).join(rel)) {
328 return Some(p);
329 }
330 }
331 }
332 None
333}
334
335/// Image file extensions probed when an `image("name")` reference omits an extension.
336const IMAGE_EXTS: [&str; 8] = ["png", "jpg", "jpeg", "gif", "bmp", "webp", "pdf", "svg"];
337
338/// The suffixes `Vector::weight` appends to a glyph name (docs/vectors.md).
339pub const WEIGHT_SUFFIXES: [&str; 2] = ["__light", "__bold"];
340
341/// The base glyph a weight-suffixed name aliases, or `None` if the name carries no suffix.
342///
343/// Only SF-template sources have true per-weight art, so only they stage `__light`/`__bold`
344/// assets. A plain SVG stages once and every weight resolves back to it here, which is what
345/// keeps `.weight(…)` from 404-ing on art that has no weight axis, without staging a byte-identical
346/// copy of every glyph per weight. (Before this, 38 of Day-Showcase's 39 sources were staged three
347/// times over as identical copies.)
348#[must_use]
349pub fn weight_alias(name: &str) -> Option<&str> {
350 WEIGHT_SUFFIXES
351 .iter()
352 .find_map(|s| name.strip_suffix(s))
353 .filter(|base| !base.is_empty())
354}
355
356/// Resolve an image name to an on-disk file, for the file-loading backends (AppKit/GTK/Qt, and the
357/// desktop/dev path). Probes `DAY_IMAGE_ROOT` (the project's `images/` under `day launch`) first,
358/// then `DAY_ASSET_ROOT` and the bundle, trying the bare name and, if it has no extension, each
359/// known image extension. Native-pipeline backends (iOS `Assets.car`, Android `R`, …) resolve by
360/// name through their own store and do not use this.
361#[must_use]
362pub fn resolve_image_file(name: &str) -> Option<PathBuf> {
363 let mut roots: Vec<PathBuf> = Vec::new();
364 // DAY_VECTOR_RASTER_ROOT: the build-time raster cache for `resource/vectors/`
365 // (docs/vectors.md), which is how the file-loading desktop backends resolve a vector name
366 // with no native vector pipeline.
367 for var in ["DAY_IMAGE_ROOT", "DAY_VECTOR_RASTER_ROOT", "DAY_ASSET_ROOT"] {
368 if let Ok(v) = std::env::var(var) {
369 roots.push(PathBuf::from(v));
370 }
371 }
372 if let Ok(exe) = std::env::current_exe()
373 && let Some(dir) = exe.parent()
374 {
375 // Packed layouts (docs/vectors.md): `day pack` stages the vector raster cache under
376 // `vectors/raster` (inside `Contents/Resources` for a .app, beside the exe for the
377 // flat Windows payload), ordered after `images` to mirror the env-root precedence.
378 for rel in [
379 "../Resources/images",
380 "../Resources/vectors/raster",
381 "../Resources/assets",
382 "images",
383 "vectors/raster",
384 "assets",
385 ] {
386 roots.push(dir.join(rel));
387 }
388 }
389 // A weight-suffixed name probes its own art first, then the base glyph it aliases
390 // (`weight_alias`): the raster half of the same fallback the SVG resolver does.
391 let names: Vec<&str> = match weight_alias(name) {
392 Some(base) => vec![name, base],
393 None => vec![name],
394 };
395 let has_ext = std::path::Path::new(name).extension().is_some();
396 // Name-major, not root-major: a staged variant found in any root beats the base glyph found in
397 // a higher-precedence one, so a template's own `__bold` art is never shadowed by its Regular.
398 for (name, root) in names
399 .iter()
400 .flat_map(|n| roots.iter().map(move |r| (*n, r.clone())))
401 {
402 let exact = root.join(name);
403 if exact.is_file() {
404 return Some(exact);
405 }
406 if !has_ext {
407 for ext in IMAGE_EXTS {
408 let p = root.join(format!("{name}.{ext}"));
409 if p.is_file() {
410 return Some(p);
411 }
412 }
413 }
414 }
415 None
416}
417
418/// Resolve a vector name to its staged glyph SVG, for backends that render SVG natively
419/// (docs/vectors.md): `DAY_VECTOR_SVG_ROOT` under `day launch`, else the packed layouts:
420/// `Contents/Resources/vectors/svg` in a .app, `vectors/svg` beside a flat-layout exe.
421/// `None` (name isn't a vector, or the layout carries no SVGs) means fall back to
422/// [`resolve_image_file`]'s raster resolution.
423#[must_use]
424pub fn resolve_vector_svg(name: &str) -> Option<PathBuf> {
425 let mut roots: Vec<PathBuf> = Vec::new();
426 if let Ok(v) = std::env::var("DAY_VECTOR_SVG_ROOT") {
427 roots.push(PathBuf::from(v));
428 }
429 if let Ok(exe) = std::env::current_exe()
430 && let Some(dir) = exe.parent()
431 {
432 roots.push(dir.join("../Resources/vectors/svg"));
433 roots.push(dir.join("vectors/svg"));
434 }
435 if let Some(found) = roots
436 .iter()
437 .map(|r| r.join(format!("{name}.svg")))
438 .find(|p| p.is_file())
439 {
440 return Some(found);
441 }
442 // A weight that stages no art of its own resolves to the base glyph (see `weight_alias`).
443 let base = weight_alias(name)?;
444 roots
445 .into_iter()
446 .map(|r| r.join(format!("{base}.svg")))
447 .find(|p| p.is_file())
448}
449
450/// Resolve a vector name to its staged XAML geometry (docs/vectors.md), the form day-toolkit-winui draws
451/// as real `Path` geometry: vector at any size, and tintable by brush at runtime.
452/// `DAY_VECTOR_XAML_ROOT` under `day launch`, else `vectors/xaml` beside a flat-layout exe.
453/// `None` (name isn't a vector, the art was outside the convertible subset, or the layout
454/// carries no geometry) means fall back to [`resolve_image_file`]'s raster resolution.
455#[must_use]
456pub fn resolve_vector_xaml(name: &str) -> Option<PathBuf> {
457 let mut roots: Vec<PathBuf> = Vec::new();
458 if let Ok(v) = std::env::var("DAY_VECTOR_XAML_ROOT") {
459 roots.push(PathBuf::from(v));
460 }
461 if let Ok(exe) = std::env::current_exe()
462 && let Some(dir) = exe.parent()
463 {
464 roots.push(dir.join("vectors/xaml"));
465 }
466 if let Some(found) = roots
467 .iter()
468 .map(|r| r.join(format!("{name}.xamlgeom")))
469 .find(|p| p.is_file())
470 {
471 return Some(found);
472 }
473 let base = weight_alias(name)?;
474 roots
475 .into_iter()
476 .map(|r| r.join(format!("{base}.xamlgeom")))
477 .find(|p| p.is_file())
478}
479
480/// Day's own drawing of `sym`, written to a cache file and answered as a path.
481///
482/// Backends that load icons from files (Qt's SVG icon engine, gdk-pixbuf) can then use the shared
483/// fallback through the loader they already have, instead of each growing a way to rasterize a
484/// path string. Written once per symbol per process; a failure to write answers `None` and the
485/// caller falls back to a label.
486#[must_use]
487pub fn stage_symbol_svg(sym: crate::Symbol) -> Option<PathBuf> {
488 let svg = sym.outline_svg()?;
489 let dir = std::env::temp_dir().join("day-symbols");
490 let file = dir.join(format!("{sym:?}.svg"));
491 if file.is_file() {
492 return Some(file);
493 }
494 std::fs::create_dir_all(&dir).ok()?;
495 std::fs::write(&file, svg).ok()?;
496 Some(file)
497}
498
499#[cfg(test)]
500mod tests {
501 use super::*;
502
503 // One test owns the process env (set_var races across threads), covering both the default
504 // data opener and the image-file resolver sequentially.
505 #[test]
506 fn env_backed_resource_access() {
507 let dir = std::env::temp_dir().join(format!("day-res-test-{}", std::process::id()));
508 std::fs::create_dir_all(&dir).unwrap();
509 let payload: Vec<u8> = (0u8..=255).cycle().take(1000).collect();
510 std::fs::write(dir.join("blob.bin"), &payload).unwrap();
511 std::fs::write(dir.join("logo.png"), b"x").unwrap();
512 // SAFETY: this is the only test that touches the env.
513 unsafe {
514 std::env::set_var("DAY_ASSET_ROOT", &dir);
515 std::env::set_var("DAY_IMAGE_ROOT", &dir);
516 }
517
518 // default data opener: whole view + random access + clamping + miss.
519 let res = resource(AssetName::from_static("blob.bin")).expect("resource present");
520 assert_eq!(res.len(), 1000);
521 assert!(!res.is_empty());
522 assert_eq!(res.as_slice(), &payload[..]);
523 let mut buf = [0u8; 16];
524 assert_eq!(res.read_at(500, &mut buf), 16);
525 assert_eq!(&buf, &payload[500..516]);
526 assert_eq!(res.read_at(995, &mut buf), 5);
527 assert_eq!(&buf[..5], &payload[995..1000]);
528 assert_eq!(res.read_at(2000, &mut buf), 0);
529 assert!(resource(AssetName::from_static("does-not-exist.bin")).is_none());
530 // Dynamic names go through the explicit escape hatch.
531 assert!(resource(AssetName::dynamic(String::from("nope.bin"))).is_none());
532
533 // image-file resolver: extension inference + exact + miss.
534 assert_eq!(resolve_image_file("logo"), Some(dir.join("logo.png")));
535 assert_eq!(resolve_image_file("logo.png"), Some(dir.join("logo.png")));
536 assert_eq!(resolve_image_file("missing"), None);
537
538 // Weight aliasing (docs/vectors.md): a plain SVG stages one asset, so its `__light` /
539 // `__bold` names must resolve back to it rather than miss. `logo` has no weight art of
540 // its own, which is exactly the case every non-template glyph is in.
541 assert_eq!(weight_alias("logo__bold"), Some("logo"));
542 assert_eq!(weight_alias("logo"), None);
543 assert_eq!(weight_alias("__bold"), None); // suffix alone aliases nothing
544 assert_eq!(resolve_image_file("logo__bold"), Some(dir.join("logo.png")));
545 assert_eq!(
546 resolve_image_file("logo__light"),
547 Some(dir.join("logo.png"))
548 );
549 // A miss stays a miss: the alias must not invent art for a name with no base either.
550 assert_eq!(resolve_image_file("missing__bold"), None);
551
552 // The SVG resolver aliases the same way, and a staged variant still wins over its base.
553 let svgs = dir.join("svg");
554 std::fs::create_dir_all(&svgs).unwrap();
555 std::fs::write(svgs.join("plain.svg"), b"<svg/>").unwrap();
556 std::fs::write(svgs.join("tmpl.svg"), b"<svg/>").unwrap();
557 std::fs::write(svgs.join("tmpl__bold.svg"), b"<svg/>").unwrap();
558 // SAFETY: single test owning the env.
559 unsafe { std::env::set_var("DAY_VECTOR_SVG_ROOT", &svgs) };
560 assert_eq!(
561 resolve_vector_svg("plain__bold"),
562 Some(svgs.join("plain.svg"))
563 );
564 assert_eq!(
565 resolve_vector_svg("tmpl__bold"),
566 Some(svgs.join("tmpl__bold.svg")),
567 "a staged variant must not be shadowed by its base"
568 );
569 assert_eq!(resolve_vector_svg("absent__bold"), None);
570 // SAFETY: single test owning the env.
571 unsafe { std::env::remove_var("DAY_VECTOR_SVG_ROOT") };
572
573 // SAFETY: single test owning the env.
574 unsafe {
575 std::env::remove_var("DAY_ASSET_ROOT");
576 std::env::remove_var("DAY_IMAGE_ROOT");
577 }
578 std::fs::remove_dir_all(&dir).ok();
579 }
580
581 #[test]
582 fn from_vec_view_is_stable() {
583 let r = Resource::from_vec(vec![1, 2, 3, 4]);
584 assert_eq!(r.as_slice(), &[1, 2, 3, 4]);
585 assert_eq!(r.to_vec(), vec![1, 2, 3, 4]);
586 let mut b = [0u8; 2];
587 assert_eq!(r.read_at(2, &mut b), 2);
588 assert_eq!(b, [3, 4]);
589 }
590}