tulip_rs 0.1.15

High-performance technical analysis library — 100+ indicators and 60+ candlestick patterns with SIMD acceleration
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
//! Fixed-size, stack-allocated ring buffer (no mirroring).
//!
//! A single `vals: [T; N]` array advanced by an `index` pointer, matching the
//! field names and semantics of the heap-based `Buffer<T>` / `RingBuffer` pair.
//!
//! Unlike [`FixedMirrorBuffer`](super::FixedMirrorBuffer), there is no always-ordered
//! `view` array.  `get_slice()` returns the raw underlying storage (unordered once
//! the buffer wraps); use `to_ordered_vec()` or `get_by_period()` when order matters.
//!
//! Use this type when you need a fixed-capacity ring with O(1) lookback but do
//! **not** need a contiguous ordered window on the hot path.

use crate::ring_buffer::buffer::{period_to_idx, BufferElement, SerdeElement};
use serde::{
    de::{self, MapAccess, Visitor},
    ser::SerializeStruct,
    Deserialize, Deserializer, Serialize, Serializer,
};
use std::{fmt, marker::PhantomData};

/// A fixed-capacity, stack-allocated ring buffer without a mirrored view.
///
/// Generic parameters:
/// * `T` — element type; must implement [`BufferElement`].
/// * `N` — compile-time capacity (number of slots).
///
/// # Layout (field names mirror heap-based `Buffer<T>`)
/// ```text
/// vals:  [T; N]   — ring storage; vals[index] is the next slot to write
/// index: usize    — next write position (advances mod N)
/// count: usize    — valid elements (0 <= count <= N)
/// ```
#[derive(Clone)]
pub struct FixedRingBuffer<T: BufferElement, const N: usize> {
    /// Ring storage — `vals[index]` is the next slot to be written.
    pub(crate) vals: [T; N],
    /// Next write position (advances mod `N`).  Mirrors `Buffer::index`.
    pub(crate) index: usize,
    /// Number of valid elements currently stored (`0 <= count <= N`).
    pub(crate) count: usize,
}

impl<T: BufferElement, const N: usize> FixedRingBuffer<T, N> {
    // ── Construction ──────────────────────────────────────────────────────────

    /// Create a new, empty buffer. All slots are initialised to `T::default()`.
    #[inline]
    pub fn new() -> Self {
        Self {
            vals: [T::default(); N],
            index: 0,
            count: 0,
        }
    }

    // ── Queries ───────────────────────────────────────────────────────────────

    /// `true` when the buffer holds exactly `N` elements.
    #[inline(always)]
    pub fn is_full(&self) -> bool {
        self.count == N
    }

    /// `true` when the buffer holds no elements.
    #[inline(always)]
    pub fn is_empty(&self) -> bool {
        self.count == 0
    }

    /// Number of valid elements currently stored (`0 <= len <= N`).
    #[inline(always)]
    pub fn len(&self) -> usize {
        self.count
    }

    /// The compile-time maximum capacity of this buffer (always `N`).
    #[inline(always)]
    pub const fn capacity(&self) -> usize {
        N
    }

    // ── Writes ────────────────────────────────────────────────────────────────

    /// Push a new element, evicting the oldest when full.
    #[inline(always)]
    pub fn push(&mut self, value: T) {
        self.vals[self.index] = value;
        self.index += 1;
        if self.index == N {
            self.index = 0;
        }
        if self.count < N {
            self.count += 1;
        }
    }

    /// Push and return the evicted element, if any.
    ///
    /// Returns `Some(evicted)` once the buffer is full, `None` while filling.
    #[inline(always)]
    pub fn push_with_info(&mut self, value: T) -> Option<T> {
        if self.count == N {
            Some(unsafe { self.push_with_info_unchecked(value) })
        } else {
            self.push(value);
            None
        }
    }

    /// Push without the fullness check.
    ///
    /// # Safety
    ///
    /// Caller must ensure `is_full() == true`.
    #[inline(always)]
    pub unsafe fn push_unchecked(&mut self, value: T) {
        *self.vals.get_unchecked_mut(self.index) = value;
        self.index += 1;
        if self.index == N {
            self.index = 0;
        }
    }

    /// Push and return the evicted element, without the fullness check.
    ///
    /// # Safety
    ///
    /// Same precondition as [`push_unchecked`](Self::push_unchecked).
    #[inline(always)]
    pub unsafe fn push_with_info_unchecked(&mut self, value: T) -> T {
        let evicted = *self.vals.get_unchecked(self.index);
        self.push_unchecked(value);
        evicted
    }

    // ── Reads ─────────────────────────────────────────────────────────────────

    /// Raw underlying storage slice.
    ///
    /// Elements are in ring order — **not** guaranteed to be oldest-first once the
    /// buffer has wrapped.  For an ordered snapshot use [`to_ordered_vec`](Self::to_ordered_vec).
    /// While still filling (`count < N`) the slice `vals[..count]` is in insertion order.
    #[inline(always)]
    pub fn get_slice(&self) -> &[T] {
        if self.count < N {
            &self.vals[..self.count]
        } else {
            &self.vals
        }
    }

    /// Newest element, or `None` if empty.
    #[inline(always)]
    pub fn back(&self) -> Option<T> {
        if self.count == 0 {
            return None;
        }
        // The slot written most recently is one behind index (mod N).
        let prev = (self.index + N - 1) % N;
        Some(unsafe { *self.vals.get_unchecked(prev) })
    }

    /// Oldest element, or `None` if empty.
    #[inline(always)]
    pub fn front(&self) -> Option<T> {
        if self.count == 0 {
            return None;
        }
        // When full, index points at the oldest slot (about to be overwritten).
        // When still filling, slot 0 is the oldest.
        let oldest = if self.count == N { self.index } else { 0 };
        Some(unsafe { *self.vals.get_unchecked(oldest) })
    }

    /// O(1) lookback.
    ///
    /// `period = 0` → most recently pushed element.
    /// `period = N - 1` → oldest stored element (when full).
    #[inline(always)]
    pub fn get_by_period(&self, period: usize) -> T {
        let idx = period_to_idx(self.index, N, period);
        unsafe { *self.vals.get_unchecked(idx) }
    }

    /// Allocate an ordered `Vec<T>` with elements from oldest to newest.
    pub fn to_ordered_vec(&self) -> Vec<T> {
        if self.count == 0 {
            return Vec::new();
        }
        if self.count < N {
            return self.vals[..self.count].to_vec();
        }
        // Full: oldest is at `index`, wraps around.
        let mut out = Vec::with_capacity(N);
        out.extend_from_slice(&self.vals[self.index..]);
        if self.index > 0 {
            out.extend_from_slice(&self.vals[..self.index]);
        }
        out
    }

    /// Allocate an ordered `Vec<T>` of the newest `period` elements (oldest-first).
    pub fn to_ordered_by_period(&self, period: usize) -> Vec<T> {
        if self.count == 0 || period == 0 {
            return Vec::new();
        }
        let take = period.min(self.count);
        // bars_ago = take-1 is the oldest of the window, bars_ago = 0 is the newest.
        (0..take)
            .map(|i| self.get_by_period(take - 1 - i))
            .collect()
    }

    /// Convert a raw `vals`-slice index (from an ordered snapshot) into a "bars ago" distance.
    ///
    /// `window_index = count - 1` → `0` (newest).
    /// `window_index = 0` → `count - 1` (oldest).
    #[inline(always)]
    pub fn window_index_to_bars_ago(&self, window_index: usize) -> usize {
        self.count - 1 - window_index
    }
}

impl<T: BufferElement, const N: usize> Default for FixedRingBuffer<T, N> {
    fn default() -> Self {
        Self::new()
    }
}

// ── Iterator ──────────────────────────────────────────────────────────────────

/// Iterator produced by `(&FixedRingBuffer).into_iter()`.
///
/// Yields elements from **newest to oldest** (`buf[0]` first).
pub struct FixedRingIter<'a, T: BufferElement, const N: usize> {
    buffer: &'a FixedRingBuffer<T, N>,
    /// Current position expressed as bars-ago (0 = newest).
    pos: usize,
}

impl<'a, T: BufferElement, const N: usize> Iterator for FixedRingIter<'a, T, N> {
    type Item = T;

    #[inline]
    fn next(&mut self) -> Option<T> {
        if self.pos >= self.buffer.count {
            return None;
        }
        let val = self.buffer.get_by_period(self.pos);
        self.pos += 1;
        Some(val)
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.buffer.count.saturating_sub(self.pos);
        (remaining, Some(remaining))
    }
}

impl<'a, T: BufferElement, const N: usize> ExactSizeIterator for FixedRingIter<'a, T, N> {}

impl<'a, T: BufferElement, const N: usize> IntoIterator for &'a FixedRingBuffer<T, N> {
    type Item = T;
    type IntoIter = FixedRingIter<'a, T, N>;

    /// Iterate from newest to oldest (`buf[0]` first).
    #[inline]
    fn into_iter(self) -> FixedRingIter<'a, T, N> {
        FixedRingIter {
            buffer: self,
            pos: 0,
        }
    }
}

impl<T: BufferElement, const N: usize> std::ops::Index<usize> for FixedRingBuffer<T, N> {
    type Output = T;

    /// Index by bars-ago: `buf[0]` is the newest element, `buf[count-1]` is the oldest.
    #[inline]
    fn index(&self, bars_ago: usize) -> &T {
        debug_assert!(
            bars_ago < self.count,
            "index out of bounds: bars_ago {bars_ago} >= count {}",
            self.count
        );
        let idx = period_to_idx(self.index, N, bars_ago);
        &self.vals[idx]
    }
}

// ── Serde ─────────────────────────────────────────────────────────────────────
//
// Hand-rolled to avoid the `where [T; N]: Serialize` bound serde's derive
// generates for generic N, and to go through T::Repr so that non-serde types
// like Simd<f64, N> are supported.
//
// Serialize  — map each element through T::to_repr, emit as a Vec<T::Repr>.
// Deserialize — read Vec<T::Repr>, map through T::from_repr, convert to [T; N].

impl<T: BufferElement + SerdeElement, const N: usize> Serialize for FixedRingBuffer<T, N> {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let mut state = serializer.serialize_struct("FixedRingBuffer", 3)?;
        let repr: Vec<T::Repr> = self.vals.iter().map(|v| T::to_repr(*v)).collect();
        state.serialize_field("vals", &repr)?;
        state.serialize_field("index", &self.index)?;
        state.serialize_field("count", &self.count)?;
        state.end()
    }
}

impl<'de, T: BufferElement + SerdeElement, const N: usize> Deserialize<'de>
    for FixedRingBuffer<T, N>
where
    T::Repr: Deserialize<'de>,
{
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        const FIELDS: &[&str] = &["vals", "index", "count"];

        enum Field {
            Vals,
            Index,
            Count,
        }

        impl<'de> Deserialize<'de> for Field {
            fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
                struct FieldVisitor;
                impl<'de> Visitor<'de> for FieldVisitor {
                    type Value = Field;
                    fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
                        f.write_str("`vals`, `index`, or `count`")
                    }
                    fn visit_str<E: de::Error>(self, v: &str) -> Result<Field, E> {
                        match v {
                            "vals" => Ok(Field::Vals),
                            "index" => Ok(Field::Index),
                            "count" => Ok(Field::Count),
                            _ => Err(de::Error::unknown_field(v, FIELDS)),
                        }
                    }
                }
                deserializer.deserialize_identifier(FieldVisitor)
            }
        }

        struct FRBVisitor<T, const N: usize>(PhantomData<fn() -> T>);

        impl<'de, T: BufferElement + SerdeElement, const N: usize> Visitor<'de> for FRBVisitor<T, N>
        where
            T::Repr: Deserialize<'de>,
        {
            type Value = FixedRingBuffer<T, N>;

            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
                f.write_str("struct FixedRingBuffer")
            }

            fn visit_map<V: MapAccess<'de>>(
                self,
                mut map: V,
            ) -> Result<FixedRingBuffer<T, N>, V::Error> {
                let mut vals: Option<Vec<T::Repr>> = None;
                let mut index: Option<usize> = None;
                let mut count: Option<usize> = None;

                while let Some(key) = map.next_key::<Field>()? {
                    match key {
                        Field::Vals => {
                            if vals.is_some() {
                                return Err(de::Error::duplicate_field("vals"));
                            }
                            vals = Some(map.next_value()?);
                        }
                        Field::Index => {
                            if index.is_some() {
                                return Err(de::Error::duplicate_field("index"));
                            }
                            index = Some(map.next_value()?);
                        }
                        Field::Count => {
                            if count.is_some() {
                                return Err(de::Error::duplicate_field("count"));
                            }
                            count = Some(map.next_value()?);
                        }
                    }
                }

                let vals_repr: Vec<T::Repr> =
                    vals.ok_or_else(|| de::Error::missing_field("vals"))?;
                let index = index.ok_or_else(|| de::Error::missing_field("index"))?;
                let count = count.ok_or_else(|| de::Error::missing_field("count"))?;

                let vals_vec: Vec<T> = vals_repr.into_iter().map(T::from_repr).collect();
                let vals_arr: [T; N] = vals_vec.try_into().map_err(|v: Vec<T>| {
                    de::Error::invalid_length(v.len(), &"vals array of length N")
                })?;

                Ok(FixedRingBuffer {
                    vals: vals_arr,
                    index,
                    count,
                })
            }
        }

        deserializer.deserialize_struct("FixedRingBuffer", FIELDS, FRBVisitor::<T, N>(PhantomData))
    }
}