Skip to main content

truce_utils/
lib.rs

1#![forbid(unsafe_code)]
2
3//! Dependency-free utilities shared across the truce workspace.
4//!
5//! - [`cast`] - numeric-cast helpers for the audio-plugin → host FFI
6//!   boundary (`usize` ↔ `u32` length casts, host `f64` ↔ DSP `f32`,
7//!   discrete-index ↔ normalized).
8//! - [`midi`] - MIDI value-domain normalize / denormalize between
9//!   wire-native integers and `f32` ranges, plus the spec's MIDI 1.0
10//!   ↔ MIDI 2.0 bit-replication bridges.
11//! - [`shell_sidecar`] - sidecar-file path resolution shared by
12//!   `cargo-truce` (writes the sidecar at install-time) and the
13//!   `truce::plugin!` macro (reads it at runtime to locate the logic
14//!   dylib for hot-reload).
15//! - [`state`] - the canonical plugin-state wire format, shared by
16//!   the runtime (`truce-core` re-exports it) and `cargo-truce`'s
17//!   install-time preset emitters.
18//! - [`preset`] - the `.trucepreset` container (metadata + state
19//!   envelope), written at install time and read by format wrappers
20//!   during host preset scans.
21//! - [`presets`] - the preset *library*: scope roots, discovery
22//!   walk, and the `PresetStore` management API (re-exported as
23//!   `truce_core::presets`).
24//! - [`slugify`] - ASCII-safe filesystem / IRI slug used by the LV2
25//!   staging path and runtime bundle-name derivation.
26//! - [`safe_filename`] - case-preserving sanitizer for plugin
27//!   display names used as path components (`{name}.aaxplugin`,
28//!   `{name}.vst3`, etc.). Replaces filesystem-reserved characters
29//!   without lowercasing or collapsing words.
30//!
31//! `truce-core` re-exports the modules above so consumers that pull
32//! `truce-core` don't need a second dependency. Crates that want to
33//! avoid `truce-core`'s `truce-params` chain (notably `cargo-truce`)
34//! depend on `truce-utils` directly.
35
36pub mod cast;
37pub mod midi;
38pub mod preset;
39pub mod presets;
40pub mod shell_sidecar;
41pub mod state;
42
43/// Slug a plugin's display name into a lowercase, hyphenated,
44/// ASCII-safe identifier suitable for filesystem paths, LV2 bundle
45/// names, and IRI components.
46///
47/// Rules: ASCII alphanumerics pass through lowercased; every other
48/// character (including runs of them) collapses to a single `-`;
49/// leading and trailing dashes are trimmed.
50#[must_use]
51pub fn slugify(name: &str) -> String {
52    let mut out = String::with_capacity(name.len());
53    let mut prev_dash = false;
54    for c in name.chars() {
55        if c.is_ascii_alphanumeric() {
56            out.push(c.to_ascii_lowercase());
57            prev_dash = false;
58        } else if !prev_dash {
59            out.push('-');
60            prev_dash = true;
61        }
62    }
63    out.trim_matches('-').to_string()
64}
65
66/// Sanitize a plugin's display name into a filesystem-safe form,
67/// preserving case and spaces. Use this whenever the name is going
68/// to land in a path component (`{name}.aaxplugin`, `{name}.vst3`,
69/// the executable inside an AAX `Contents/MacOS/`, etc.). The
70/// in-Info.plist / in-host-browser display name should keep using
71/// the raw `name` so users still see "Truce Dry/Wet" in their DAW.
72///
73/// Replacements:
74/// - POSIX path separator `/`, Windows path separator `\`, NTFS /
75///   HFS path-reserved chars `:<>"|?*`, NUL and ASCII control chars
76///   → `-`.
77/// - Leading and trailing whitespace + ASCII dots stripped (Windows
78///   forbids trailing dots / spaces; trimming both keeps behaviour
79///   identical across platforms).
80/// - Runs of `-` collapsed to a single `-` so `Dry//Wet` doesn't
81///   produce `Dry--Wet`.
82#[must_use]
83pub fn safe_filename(name: &str) -> String {
84    let mut out = String::with_capacity(name.len());
85    let mut prev_dash = false;
86    for c in name.chars() {
87        let reserved = matches!(c, '/' | '\\' | ':' | '<' | '>' | '"' | '|' | '?' | '*')
88            || c == '\0'
89            || c.is_control();
90        if reserved {
91            if !prev_dash {
92                out.push('-');
93                prev_dash = true;
94            }
95        } else {
96            out.push(c);
97            prev_dash = false;
98        }
99    }
100    out.trim_matches(|c: char| c.is_whitespace() || c == '.' || c == '-')
101        .to_string()
102}
103
104#[cfg(test)]
105mod slugify_tests {
106    use super::slugify;
107
108    #[test]
109    fn slugify_basic() {
110        assert_eq!(slugify("My Plugin"), "my-plugin");
111        assert_eq!(slugify("Hello!! World"), "hello-world");
112        assert_eq!(slugify("--leading and trailing--"), "leading-and-trailing");
113        assert_eq!(slugify("ABC123"), "abc123");
114        assert_eq!(slugify(""), "");
115    }
116}
117
118#[cfg(test)]
119mod safe_filename_tests {
120    use super::safe_filename;
121
122    #[test]
123    fn replaces_path_separators() {
124        assert_eq!(safe_filename("Truce Dry/Wet"), "Truce Dry-Wet");
125        assert_eq!(safe_filename(r"Foo\Bar"), "Foo-Bar");
126    }
127
128    #[test]
129    fn replaces_windows_reserved() {
130        assert_eq!(safe_filename(r#"a:b<c>d"e|f?g*h"#), "a-b-c-d-e-f-g-h");
131    }
132
133    #[test]
134    fn collapses_runs_of_replacements() {
135        assert_eq!(safe_filename("Dry//Wet"), "Dry-Wet");
136        assert_eq!(safe_filename("A//B\\\\C"), "A-B-C");
137    }
138
139    #[test]
140    fn preserves_case_and_spaces() {
141        assert_eq!(safe_filename("Truce DryWet"), "Truce DryWet");
142        assert_eq!(safe_filename("ALL CAPS"), "ALL CAPS");
143    }
144
145    #[test]
146    fn trims_whitespace_and_dots() {
147        assert_eq!(safe_filename("  Foo  "), "Foo");
148        assert_eq!(safe_filename(".hidden."), "hidden");
149        assert_eq!(safe_filename(" . . trim . . "), "trim");
150    }
151
152    #[test]
153    fn empty_in_empty_out() {
154        assert_eq!(safe_filename(""), "");
155        assert_eq!(safe_filename("///"), "");
156    }
157}