rill-core 0.5.0-beta.1

Core foundation for the Rill ecosystem — traits, math, buffers, queues, time, macros
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
//! Parameter handling for audio nodes
//!
//! Defines the fundamental building blocks of the signal graph:
//! - `SignalNode`: Base trait for all nodes
//! - `Source`: Active generator (has no inputs)
//! - `Processor`: Passive processor (has inputs and outputs)
//! - `Sink`: Active consumer (has no outputs)

use super::error::{ParameterError, ParameterResult};
use std::collections::HashMap;
use std::fmt;
use std::str::FromStr;

// ============================================================================
// Parameter ID
// ============================================================================

/// Type-safe parameter identifier with validation
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ParameterId {
    name: String,
}

impl ParameterId {
    /// Maximum length of a parameter name
    pub const MAX_LEN: usize = 64;

    /// Create a new ParameterId with validation
    ///
    /// # Rules
    /// - Not empty
    /// - Max length MAX_LEN
    /// - Starts with a letter (a-z, A-Z)
    /// - Contains only letters, digits, and underscores
    pub fn new(name: impl Into<String>) -> ParameterResult<Self> {
        let name = name.into();

        if name.is_empty() {
            return Err(ParameterError::Empty);
        }

        if name.len() > Self::MAX_LEN {
            return Err(ParameterError::TooLong { max: Self::MAX_LEN });
        }

        let first = name.chars().next().unwrap();
        if !first.is_ascii_alphabetic() {
            return Err(ParameterError::MustStartWithLetter);
        }

        for c in name.chars() {
            if !c.is_ascii_alphanumeric() && c != '_' {
                return Err(ParameterError::InvalidCharacter(c));
            }
        }

        Ok(Self { name })
    }

    /// Get the string representation
    pub fn as_str(&self) -> &str {
        &self.name
    }

    /// Convert into a String
    pub fn into_string(self) -> String {
        self.name
    }
}

impl AsRef<str> for ParameterId {
    fn as_ref(&self) -> &str {
        &self.name
    }
}

impl fmt::Display for ParameterId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.name)
    }
}

impl FromStr for ParameterId {
    type Err = ParameterError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        ParameterId::new(s)
    }
}

// ============================================================================
// Parameter Type
// ============================================================================

/// Type of parameter value
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ParamType {
    /// Floating point value
    Float,

    /// Integer value
    Int,

    /// Boolean value
    Bool,

    /// String value
    String,

    /// Choice from a list of options
    Choice,
}

impl ParamType {
    /// Get the name of the parameter type
    pub fn name(&self) -> &'static str {
        match self {
            Self::Float => "float",
            Self::Int => "int",
            Self::Bool => "bool",
            Self::String => "string",
            Self::Choice => "choice",
        }
    }
}

impl fmt::Display for ParamType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.name())
    }
}

// ============================================================================
// Parameter Value
// ============================================================================

/// Parameter value (can be of different types)
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ParamValue {
    /// Floating point value
    Float(f32),

    /// Integer value
    Int(i32),

    /// Boolean value
    Bool(bool),

    /// String value
    String(String),

    /// Choice from a list of options
    Choice(String),
}

impl ParamValue {
    /// Get the type of this value
    pub fn param_type(&self) -> ParamType {
        match self {
            Self::Float(_) => ParamType::Float,
            Self::Int(_) => ParamType::Int,
            Self::Bool(_) => ParamType::Bool,
            Self::String(_) => ParamType::String,
            Self::Choice(_) => ParamType::Choice,
        }
    }

    /// Try to convert to f32
    pub fn as_f32(&self) -> Option<f32> {
        match self {
            Self::Float(f) => Some(*f),
            Self::Int(i) => Some(*i as f32),
            Self::Bool(b) => Some(if *b { 1.0 } else { 0.0 }),
            _ => None,
        }
    }

    /// Try to convert to i32
    pub fn as_i32(&self) -> Option<i32> {
        match self {
            Self::Float(f) => Some(*f as i32),
            Self::Int(i) => Some(*i),
            Self::Bool(b) => Some(if *b { 1 } else { 0 }),
            _ => None,
        }
    }

    /// Try to convert to bool
    pub fn as_bool(&self) -> Option<bool> {
        match self {
            Self::Bool(b) => Some(*b),
            Self::Float(f) => Some(*f > 0.5),
            Self::Int(i) => Some(*i > 0),
            _ => None,
        }
    }

    /// Return the string value if this is a `String` or `Choice` variant.
    pub fn as_str(&self) -> Option<&str> {
        match self {
            Self::String(s) | Self::Choice(s) => Some(s.as_str()),
            _ => None,
        }
    }
}

// ============================================================================
// Parameter Range
// ============================================================================

/// Range constraints for a parameter
#[derive(Debug, Clone, PartialEq)]
pub struct ParamRange {
    /// Minimum value (if applicable)
    pub min: Option<f32>,

    /// Maximum value (if applicable)
    pub max: Option<f32>,

    /// Step size (if applicable)
    pub step: Option<f32>,
}

impl ParamRange {
    /// Create a new empty range
    pub fn new() -> Self {
        Self {
            min: None,
            max: None,
            step: None,
        }
    }

    /// Set minimum value
    pub fn with_min(mut self, min: f32) -> Self {
        self.min = Some(min);
        self
    }

    /// Set maximum value
    pub fn with_max(mut self, max: f32) -> Self {
        self.max = Some(max);
        self
    }

    /// Set step size
    pub fn with_step(mut self, step: f32) -> Self {
        self.step = Some(step);
        self
    }

    /// Check if value is within range
    pub fn contains(&self, value: f32) -> bool {
        if let Some(min) = self.min {
            if value < min {
                return false;
            }
        }
        if let Some(max) = self.max {
            if value > max {
                return false;
            }
        }
        true
    }

    /// Clamp value to range
    pub fn clamp(&self, value: f32) -> f32 {
        let mut value = value;
        if let Some(min) = self.min {
            value = value.max(min);
        }
        if let Some(max) = self.max {
            value = value.min(max);
        }
        value
    }
}

impl Default for ParamRange {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// Parameter Metadata
// ============================================================================

/// Metadata about a parameter
#[derive(Debug, Clone, PartialEq)]
pub struct ParamMetadata {
    /// Parameter name (must be a valid ParameterId)
    pub name: String,

    /// Human-readable description
    pub description: String,

    /// Parameter type
    pub typ: ParamType,

    /// Default value
    pub default: ParamValue,

    /// Value range (if applicable)
    pub range: ParamRange,

    /// Unit of measurement (e.g., "Hz", "dB", "ms")
    pub unit: Option<String>,

    /// Possible choices (for Choice parameters)
    pub choices: Option<Vec<(String, f32)>>,
}

impl ParamMetadata {
    /// Create new parameter metadata
    pub fn new(name: impl Into<String>, typ: ParamType, default: ParamValue) -> Self {
        Self {
            name: name.into(),
            description: String::new(),
            typ,
            default,
            range: ParamRange::default(),
            unit: None,
            choices: None,
        }
    }

    /// Set description
    pub fn with_description(mut self, description: impl Into<String>) -> Self {
        self.description = description.into();
        self
    }

    /// Set range
    pub fn with_range(mut self, min: f32, max: f32, step: f32) -> Self {
        self.range = ParamRange::new()
            .with_min(min)
            .with_max(max)
            .with_step(step);
        self
    }

    /// Set unit
    pub fn with_unit(mut self, unit: impl Into<String>) -> Self {
        self.unit = Some(unit.into());
        self
    }

    /// Set choices
    pub fn with_choices(mut self, choices: Vec<(String, f32)>) -> Self {
        self.choices = Some(choices);
        self
    }
}

// ============================================================================
// NodeParams — bag of parameters for factory-based node construction
// ============================================================================

/// A flexible set of parameters passed to a node constructor.
///
/// Uses `HashMap<String, ParamValue>` so any node type can extract
/// whatever named parameters it supports. This is intentionally
/// open-ended — no fixed schema, no required fields.
///
/// See `NodeConstructor` (in `rill-graph`) for how builder uses this.
#[derive(Debug, Clone, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct NodeParams {
    /// Sample rate the node will be initialized with.
    pub sample_rate: f32,

    /// Arbitrary named parameters.
    pub parameters: HashMap<String, ParamValue>,
}

impl NodeParams {
    /// Create params with a given sample rate.
    pub fn new(sample_rate: f32) -> Self {
        Self {
            sample_rate,
            parameters: HashMap::new(),
        }
    }

    /// Builder-style: insert a parameter and return self.
    pub fn with(mut self, key: impl Into<String>, value: ParamValue) -> Self {
        self.parameters.insert(key.into(), value);
        self
    }

    /// Get a parameter by name.
    pub fn get(&self, key: &str) -> Option<&ParamValue> {
        self.parameters.get(key)
    }

    /// Insert or overwrite a parameter.
    pub fn insert(&mut self, key: impl Into<String>, value: ParamValue) -> Option<ParamValue> {
        self.parameters.insert(key.into(), value)
    }

    /// Remove a parameter, returning its value if present.
    pub fn remove(&mut self, key: &str) -> Option<ParamValue> {
        self.parameters.remove(key)
    }

    /// Check whether a parameter exists.
    pub fn contains(&self, key: &str) -> bool {
        self.parameters.contains_key(key)
    }

    /// Number of stored parameters.
    pub fn len(&self) -> usize {
        self.parameters.len()
    }

    /// True when no parameters have been stored.
    pub fn is_empty(&self) -> bool {
        self.parameters.is_empty()
    }

    /// Get a float parameter by name, falling back to `default`.
    pub fn get_f32(&self, key: &str, default: f32) -> f32 {
        self.parameters
            .get(key)
            .and_then(|v| v.as_f32())
            .unwrap_or(default)
    }

    /// Get an integer parameter by name.
    pub fn get_i32(&self, key: &str, default: i32) -> i32 {
        self.parameters
            .get(key)
            .and_then(|v| v.as_i32())
            .unwrap_or(default)
    }

    /// Get a bool parameter by name.
    pub fn get_bool(&self, key: &str, default: bool) -> bool {
        self.parameters
            .get(key)
            .and_then(|v| v.as_bool())
            .unwrap_or(default)
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parameter_id_valid() {
        assert!(ParameterId::new("gain").is_ok());
        assert!(ParameterId::new("cutoff_freq").is_ok());
        assert!(ParameterId::new("delay_time_2").is_ok());
    }

    #[test]
    fn test_parameter_id_invalid() {
        assert!(ParameterId::new("").is_err());
        assert!(ParameterId::new("1gain").is_err());
        assert!(ParameterId::new("_gain").is_err());

        let long_name = "a".repeat(ParameterId::MAX_LEN + 1);
        assert!(ParameterId::new(long_name).is_err());
    }

    #[test]
    fn test_param_value_conversion() {
        let f = ParamValue::Float(42.0);
        assert_eq!(f.as_f32(), Some(42.0));
        assert_eq!(f.as_i32(), Some(42));
        assert_eq!(f.as_bool(), Some(true));

        let i = ParamValue::Int(0);
        assert_eq!(i.as_f32(), Some(0.0));
        assert_eq!(i.as_i32(), Some(0));
        assert_eq!(i.as_bool(), Some(false));
    }
}