caw_core/
sig.rs

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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
use std::{cell::RefCell, fmt::Debug, iter, marker::PhantomData, rc::Rc};

use crate::arith::signed_to_01;

#[derive(Clone, Copy)]
pub struct SigCtx {
    pub sample_rate_hz: f32,
    pub batch_index: u64,
    pub num_samples: usize,
}

impl SigCtx {
    pub fn sample_period_s(&self) -> f32 {
        self.num_samples as f32 / self.sample_rate_hz
    }
}

pub trait Buf<T>
where
    T: Clone,
{
    fn iter(&self) -> impl Iterator<Item = T>;

    fn clone_to_vec(&self, out: &mut Vec<T>) {
        out.clear();
        for x in self.iter() {
            out.push(x.clone());
        }
    }
}

impl<T> Buf<T> for &Vec<T>
where
    T: Clone,
{
    fn iter(&self) -> impl Iterator<Item = T> {
        (self as &[T]).iter().cloned()
    }

    fn clone_to_vec(&self, out: &mut Vec<T>) {
        if let Some(first) = self.first() {
            out.resize_with(self.len(), || first.clone());
            out.clone_from_slice(self);
        } else {
            // self is empty
            out.clear();
        }
    }
}

pub struct ConstBuf<T> {
    pub value: T,
    pub count: usize,
}

impl<T> Buf<T> for ConstBuf<T>
where
    T: Clone,
{
    fn iter(&self) -> impl Iterator<Item = T> {
        iter::repeat_n(&self.value, self.count).cloned()
    }

    fn clone_to_vec(&self, out: &mut Vec<T>) {
        out.resize_with(self.count, || self.value.clone());
        out.fill(self.value.clone());
    }
}

/// Used to implement `map` methods (but not `map_mut`) by deferring the mapped function until the
/// iteration of the following operation, preventing the need to buffer the result of the map.
pub struct MapBuf<B, F, I, O>
where
    I: Clone,
    O: Clone,
    B: Buf<I>,
    F: Fn(I) -> O,
{
    buf: B,
    f: F,
    phantom: PhantomData<(I, O)>,
}

impl<B, F, I, O> MapBuf<B, F, I, O>
where
    I: Clone,
    O: Clone,
    B: Buf<I>,
    F: Fn(I) -> O,
{
    pub fn new(buf: B, f: F) -> Self {
        Self {
            buf,
            f,
            phantom: PhantomData,
        }
    }
}

impl<B, F, I, O> Buf<O> for MapBuf<B, F, I, O>
where
    I: Clone,
    O: Clone,
    B: Buf<I>,
    F: Fn(I) -> O,
{
    fn iter(&self) -> impl Iterator<Item = O> {
        self.buf.iter().map(&self.f)
    }
}

/// Used to implement arithmetic operations by deferring the computation until the iteration of the
/// following operation, preventing the need to buffer the result of the map.
pub struct MapBuf2<BL, BR, F, L, R, O>
where
    L: Clone,
    R: Clone,
    O: Clone,
    BL: Buf<L>,
    BR: Buf<R>,
    F: Fn(L, R) -> O,
{
    buf_left: BL,
    buf_right: BR,
    f: F,
    phantom: PhantomData<(L, R, O)>,
}

impl<BL, BR, F, L, R, O> MapBuf2<BL, BR, F, L, R, O>
where
    L: Clone,
    R: Clone,
    O: Clone,
    BL: Buf<L>,
    BR: Buf<R>,
    F: Fn(L, R) -> O,
{
    pub fn new(buf_left: BL, buf_right: BR, f: F) -> Self {
        Self {
            buf_left,
            buf_right,
            f,
            phantom: PhantomData,
        }
    }
}

impl<BL, BR, F, L, R, O> Buf<O> for MapBuf2<BL, BR, F, L, R, O>
where
    L: Clone,
    R: Clone,
    O: Clone,
    BL: Buf<L>,
    BR: Buf<R>,
    F: Fn(L, R) -> O,
{
    fn iter(&self) -> impl Iterator<Item = O> {
        self.buf_left
            .iter()
            .zip(self.buf_right.iter())
            .map(|(l, r)| (self.f)(l, r))
    }
}

/// Used to implement zip without the need for an explicit buffer for zipped values. The zipping
/// will take place in the iteration of the signal that consumes this buffer. Since zip operations
/// often follow map operations, and map operations use the `MapBuf` buffer type, sequences of zip
/// and map operations are fused without the need for intermediate buffers.
pub struct ZipBuf<BL, BR, L, R>
where
    L: Clone,
    R: Clone,
    BL: Buf<L>,
    BR: Buf<R>,
{
    buf_left: BL,
    buf_right: BR,
    phantom: PhantomData<(L, R)>,
}

impl<BL, BR, L, R> ZipBuf<BL, BR, L, R>
where
    L: Clone,
    R: Clone,
    BL: Buf<L>,
    BR: Buf<R>,
{
    pub fn new(buf_left: BL, buf_right: BR) -> Self {
        Self {
            buf_left,
            buf_right,
            phantom: PhantomData,
        }
    }
}

impl<BL, BR, L, R> Buf<(L, R)> for ZipBuf<BL, BR, L, R>
where
    L: Clone,
    R: Clone,
    BL: Buf<L>,
    BR: Buf<R>,
{
    fn iter(&self) -> impl Iterator<Item = (L, R)> {
        self.buf_left.iter().zip(self.buf_right.iter())
    }
}

/// A signal with values produced for each audio sample. Values are produced in batches of a size
/// determined by the audio driver. This is suitable for audible audio signals or controls signals
/// that vary at the same rate as an audio signal (e.g. an envelope follower produced by analyzing
/// an audio signal). Low-frequency signals such as LFOs should still use this type, as their
/// value still changes smoothly at the audio sample rate despite the signal they represent
/// typically being below perceptible audio frequencies.
pub trait SigT {
    type Item: Clone;

    fn sample(&mut self, ctx: &SigCtx) -> impl Buf<Self::Item>;

    fn filter<F>(self, filter: F) -> Sig<F::Out<Self>>
    where
        F: Filter<ItemIn = Self::Item>,
        Self: Sized,
    {
        Sig(filter.into_sig(self))
    }
}

/// Similar to `SigT` but less flexible as it needs to populate a `Vec`. However this trait is
/// possible to be boxed allowing for type erasure.
pub trait SigSampleIntoBufT {
    type Item: Clone;

    fn sample_into_buf(&mut self, ctx: &SigCtx, buf: &mut Vec<Self::Item>);
}

impl SigT for f32 {
    type Item = f32;

    fn sample(&mut self, ctx: &SigCtx) -> impl Buf<Self::Item> {
        ConstBuf {
            value: *self,
            count: ctx.num_samples,
        }
    }
}

/// For gate and trigger signals
impl SigT for bool {
    type Item = bool;

    fn sample(&mut self, ctx: &SigCtx) -> impl Buf<Self::Item> {
        ConstBuf {
            value: *self,
            count: ctx.num_samples,
        }
    }
}

pub struct SigConst<T: Clone>(T);
impl<T: Clone> SigT for SigConst<T> {
    type Item = T;

    fn sample(&mut self, ctx: &SigCtx) -> impl Buf<Self::Item> {
        ConstBuf {
            value: self.0.clone(),
            count: ctx.num_samples,
        }
    }
}

/// Wrapper type for the `SigT` trait to simplify some trait implementations for signals. For
/// example this allows arithmetic traits like `std::ops::Add` to be implemented for signals.
#[derive(Clone)]
pub struct Sig<S>(pub S)
where
    S: SigT;

impl<S: SigT> SigT for Sig<S> {
    type Item = S::Item;

    fn sample(&mut self, ctx: &SigCtx) -> impl Buf<Self::Item> {
        self.0.sample(ctx)
    }
}

impl<S: SigT> SigSampleIntoBufT for Sig<S> {
    type Item = S::Item;

    fn sample_into_buf(&mut self, ctx: &SigCtx, buf: &mut Vec<Self::Item>) {
        let buf_internal = self.0.sample(ctx);
        buf_internal.clone_to_vec(buf);
    }
}

pub struct SigBoxed<T>(Box<dyn SigSampleIntoBufT<Item = T>>)
where
    T: Clone;

impl<T> SigSampleIntoBufT for SigBoxed<T>
where
    T: Clone,
{
    type Item = T;

    fn sample_into_buf(&mut self, ctx: &SigCtx, buf: &mut Vec<Self::Item>) {
        self.0.sample_into_buf(ctx, buf);
    }
}

impl<S> Sig<S>
where
    S: SigT<Item: Clone>,
{
    pub fn map_mut<T, F>(self, f: F) -> Sig<MapMut<S, T, F>>
    where
        T: Clone,
        F: FnMut(S::Item) -> T,
    {
        Sig(MapMut {
            sig: self.0,
            f,
            buf: Vec::new(),
        })
    }

    pub fn map_mut_ctx<T, F>(self, f: F) -> Sig<MapMutCtx<S, T, F>>
    where
        T: Clone,
        F: FnMut(S::Item, &SigCtx) -> T,
    {
        Sig(MapMutCtx {
            sig: self.0,
            f,
            buf: Vec::new(),
        })
    }

    pub fn map<T, F>(self, f: F) -> Sig<Map<S, T, F>>
    where
        T: Clone,
        F: Fn(S::Item) -> T,
    {
        Sig(Map { sig: self.0, f })
    }

    pub fn map_ctx<T, F>(self, f: F) -> Sig<MapCtx<S, T, F>>
    where
        T: Clone,
        F: Fn(S::Item, &SigCtx) -> T,
    {
        Sig(MapCtx { sig: self.0, f })
    }

    pub fn zip<O>(self, other: O) -> Sig<Zip<S, O>>
    where
        O: SigT,
    {
        Sig(Zip {
            a: self.0,
            b: other,
        })
    }

    pub fn shared(self) -> Sig<SigShared<S>> {
        sig_shared(self.0)
    }

    pub fn debug<F: FnMut(&S::Item)>(
        self,
        mut f: F,
    ) -> Sig<impl SigT<Item = S::Item>> {
        self.map_mut(move |x| {
            f(&x);
            x
        })
    }
}

impl<S> Sig<S>
where
    S: SigT + 'static,
{
    pub fn boxed(self) -> SigBoxed<S::Item> {
        SigBoxed(Box::new(self))
    }
}

impl<S> Sig<S>
where
    S: SigT<Item: Debug>,
{
    pub fn debug_print(self) -> Sig<impl SigT<Item = S::Item>> {
        self.debug(|x| println!("{:?}", x))
    }
}

impl<S> Sig<S>
where
    S: SigT<Item = f32>,
{
    /// clamp `x` between +/- `max_unsigned`
    pub fn clamp_symetric<C>(
        self,
        max_unsigned: C,
    ) -> Sig<impl SigT<Item = f32>>
    where
        C: SigT<Item = f32>,
    {
        self.zip(max_unsigned).map(|(s, max_unsigned)| {
            crate::arith::clamp_symetric(s, max_unsigned)
        })
    }

    /// The function f(x) =
    ///   k > 0  => exp(k * (x - a)) - b
    ///   k == 0 => x
    ///   k < 0  => -(ln(x + b) / k) + a
    /// ...where a and b are chosen so that f(0) = 0 and f(1) = 1.
    /// The k parameter controls how sharp the curve is.
    /// The functions when k != 0 are inverses of each other and zip approach linearity as k
    /// approaches 0.
    pub fn exp_01<K>(self, k: K) -> Sig<impl SigT<Item = f32>>
    where
        K: SigT<Item = f32>,
    {
        self.zip(k).map(|(x, k)| crate::arith::exp_01(x, k))
    }

    pub fn inv_01(self) -> Sig<impl SigT<Item = f32>> {
        1.0 - self
    }

    pub fn signed_to_01(self) -> Sig<SignedTo01<S>> {
        Sig(SignedTo01(self.0))
    }

    pub fn abs(self) -> Sig<SigAbs<S>> {
        Sig(SigAbs(self.0))
    }
}

pub struct GateToTrigRisingEdge<S>
where
    S: SigT<Item = bool>,
{
    sig: S,
    prev: bool,
    buf: Vec<bool>,
}

impl<S> SigT for GateToTrigRisingEdge<S>
where
    S: SigT<Item = bool>,
{
    type Item = bool;

    fn sample(&mut self, ctx: &SigCtx) -> impl Buf<Self::Item> {
        self.buf.resize(ctx.num_samples, false);
        for (out, sample) in
            self.buf.iter_mut().zip(self.sig.sample(ctx).iter())
        {
            *out = sample && !self.prev;
            self.prev = sample;
        }
        &self.buf
    }
}

impl<S> Sig<S>
where
    S: SigT<Item = bool>,
{
    pub fn gate_to_trig_rising_edge(self) -> Sig<GateToTrigRisingEdge<S>> {
        Sig(GateToTrigRisingEdge {
            sig: self.0,
            prev: false,
            buf: Vec::new(),
        })
    }

    pub fn trig_to_gate<P>(self, period_s: P) -> Sig<impl SigT<Item = bool>>
    where
        P: SigT<Item = f32>,
    {
        let mut remaining_s = 0.0;
        self.zip(period_s).map_mut_ctx(move |(x, period_s), ctx| {
            if x {
                remaining_s = period_s;
            }
            remaining_s -= 1.0 / ctx.sample_rate_hz;
            remaining_s > 0.0
        })
    }
}

pub struct MapMut<S, T, F>
where
    S: SigT,
    F: FnMut(S::Item) -> T,
{
    sig: S,
    f: F,
    buf: Vec<T>,
}

impl<S, T, F> SigT for MapMut<S, T, F>
where
    T: Clone,
    S: SigT,
    F: FnMut(S::Item) -> T,
{
    type Item = T;

    fn sample(&mut self, ctx: &SigCtx) -> impl Buf<Self::Item> {
        let buf = self.sig.sample(ctx);
        self.buf.clear();
        self.buf.extend(buf.iter().map(&mut self.f));
        &self.buf
    }
}

pub struct MapMutCtx<S, T, F>
where
    S: SigT,
    F: FnMut(S::Item, &SigCtx) -> T,
{
    sig: S,
    f: F,
    buf: Vec<T>,
}

impl<S, T, F> SigT for MapMutCtx<S, T, F>
where
    T: Clone,
    S: SigT,
    F: FnMut(S::Item, &SigCtx) -> T,
{
    type Item = T;

    fn sample(&mut self, ctx: &SigCtx) -> impl Buf<Self::Item> {
        let buf = self.sig.sample(ctx);
        self.buf.clear();
        self.buf.extend(buf.iter().map(|x| (self.f)(x, ctx)));
        &self.buf
    }
}

pub struct Map<S, T, F>
where
    S: SigT,
    F: Fn(S::Item) -> T,
{
    sig: S,
    f: F,
}

impl<S, T, F> SigT for Map<S, T, F>
where
    T: Clone,
    S: SigT,
    F: Fn(S::Item) -> T,
{
    type Item = T;

    fn sample(&mut self, ctx: &SigCtx) -> impl Buf<Self::Item> {
        MapBuf::new(self.sig.sample(ctx), &self.f)
    }
}

pub struct MapCtx<S, T, F>
where
    S: SigT,
    F: Fn(S::Item, &SigCtx) -> T,
{
    sig: S,
    f: F,
}

impl<S, T, F> SigT for MapCtx<S, T, F>
where
    T: Clone,
    S: SigT,
    F: Fn(S::Item, &SigCtx) -> T,
{
    type Item = T;

    fn sample(&mut self, ctx: &SigCtx) -> impl Buf<Self::Item> {
        MapBuf::new(self.sig.sample(ctx), |x| (self.f)(x, ctx))
    }
}

pub struct Zip<A, B>
where
    A: SigT,
    B: SigT,
{
    a: A,
    b: B,
}

impl<A, B> SigT for Zip<A, B>
where
    A: SigT,
    B: SigT,
{
    type Item = (A::Item, B::Item);

    fn sample(&mut self, ctx: &SigCtx) -> impl Buf<Self::Item> {
        ZipBuf::new(self.a.sample(ctx), self.b.sample(ctx))
    }
}

pub struct SigAbs<S>(S)
where
    S: SigT<Item = f32>;

impl<S> SigT for SigAbs<S>
where
    S: SigT<Item = f32>,
{
    type Item = f32;

    fn sample(&mut self, ctx: &SigCtx) -> impl Buf<Self::Item> {
        MapBuf::new(self.0.sample(ctx), |x| x.abs())
    }
}

pub struct SignedTo01<S>(S)
where
    S: SigT<Item = f32>;

impl<S> SigT for SignedTo01<S>
where
    S: SigT<Item = f32>,
{
    type Item = f32;

    fn sample(&mut self, ctx: &SigCtx) -> impl Buf<Self::Item> {
        MapBuf::new(self.0.sample(ctx), signed_to_01)
    }
}

/// For signals yielding `f32`, this trait provides a general way of defining filters.
pub trait Filter {
    /// The type of the item of the input signal to this filter.
    type ItemIn;

    /// The type of the signal produced by this filter. Filters take an input signal (`S`) and wrap
    /// them it a new signal whose type is this associated type. The output type will usually be
    /// generic with a type parameter for the input signal, so this associated type must also have
    /// that type parameter.
    type Out<S>: SigT
    where
        S: SigT<Item = Self::ItemIn>;

    /// Create a new signal from an existing signal, consuming self in the process.
    fn into_sig<S>(self, sig: S) -> Self::Out<S>
    where
        S: SigT<Item = Self::ItemIn>;
}

/// Wrapper for a `Sig` that prevents recomputation of its value
/// for a particular point in time.
struct SigCached<S>
where
    S: SigT,
{
    sig: S,
    cache: Vec<S::Item>,
    next_batch_index: u64,
}

impl<S> SigCached<S>
where
    S: SigT,
{
    fn new(sig: S) -> Self {
        Self {
            sig,
            cache: Vec::new(),
            next_batch_index: 0,
        }
    }
}

/// A wrapper of a signal that can be shallow-cloned. It doesn't implement `SigT` that would be
/// less performant than iterating the underlying signal with a callback.
impl<S> SigT for SigCached<S>
where
    S: SigT,
{
    type Item = S::Item;

    fn sample(&mut self, ctx: &SigCtx) -> impl Buf<Self::Item> {
        if ctx.batch_index >= self.next_batch_index {
            self.next_batch_index = ctx.batch_index + 1;
            let buf = self.sig.sample(ctx);
            buf.clone_to_vec(&mut self.cache);
        }
        &self.cache
    }
}

/// A wrapper of a signal which can be shallow-cloned. Use this to split a signal into two copies
/// of itself without duplicating all the computations that produced the signal. Incurs a small
/// performance penalty as buffered values must be copied from the underlying signal into each
/// instance of the shared signal.
pub struct SigShared<S>
where
    S: SigT,
{
    shared_cached_sig: Rc<RefCell<SigCached<S>>>,
    buf: Vec<S::Item>,
}

impl<S> Clone for SigShared<S>
where
    S: SigT,
{
    fn clone(&self) -> Self {
        SigShared {
            shared_cached_sig: Rc::clone(&self.shared_cached_sig),
            buf: self.buf.clone(),
        }
    }
}

impl<S> SigT for SigShared<S>
where
    S: SigT,
{
    type Item = S::Item;

    fn sample(&mut self, ctx: &SigCtx) -> impl Buf<Self::Item> {
        let mut shared_cached_sig = self.shared_cached_sig.borrow_mut();
        // This will only actually run the underlying signal if it hasn't been computed yet this
        // frame. If it has already been computed this frame then the already-populated buffer will
        // be returned. We still need to copy the buffer to the buffer inside `self` so that the
        // buffer returned by _this_ function has the appropriate lifetime.
        let buf = shared_cached_sig.sample(ctx);
        buf.clone_to_vec(&mut self.buf);
        &self.buf
    }
}

pub fn sig_shared<S>(sig: S) -> Sig<SigShared<S>>
where
    S: SigT,
{
    Sig(SigShared {
        shared_cached_sig: Rc::new(RefCell::new(SigCached::new(sig))),
        buf: Vec::new(),
    })
}

pub struct SigFn<F, T>
where
    F: FnMut(&SigCtx) -> T,
    T: Clone + Default,
{
    f: F,
    buf: Vec<T>,
}

impl<F, T> SigT for SigFn<F, T>
where
    F: FnMut(&SigCtx) -> T,
    T: Clone + Default,
{
    type Item = T;

    fn sample(&mut self, ctx: &SigCtx) -> impl Buf<Self::Item> {
        self.buf.resize_with(ctx.num_samples, Default::default);
        for out in self.buf.iter_mut() {
            *out = (self.f)(ctx);
        }
        &self.buf
    }
}

impl<F, T> Sig<SigFn<F, T>>
where
    F: FnMut(&SigCtx) -> T,
    T: Clone + Default,
{
    pub fn from_fn(f: F) -> Self {
        Self(SigFn { f, buf: Vec::new() })
    }
}

pub struct SigBufFn<F, T>
where
    F: FnMut(&SigCtx, &mut Vec<T>),
    T: Clone + Default,
{
    f: F,
    buf: Vec<T>,
}

impl<F, T> SigT for SigBufFn<F, T>
where
    F: FnMut(&SigCtx, &mut Vec<T>),
    T: Clone + Default,
{
    type Item = T;

    fn sample(&mut self, ctx: &SigCtx) -> impl Buf<Self::Item> {
        self.buf.resize_with(ctx.num_samples, Default::default);
        (self.f)(ctx, &mut self.buf);
        &self.buf
    }
}

impl<F, T> Sig<SigBufFn<F, T>>
where
    F: FnMut(&SigCtx, &mut Vec<T>),
    T: Clone + Default,
{
    pub fn from_buf_fn(f: F) -> Self {
        Self(SigBufFn { f, buf: Vec::new() })
    }
}