quantlib_rs 0.1.0

A ground-up, idiomatic Rust quantitative finance library inspired by QuantLib.
Documentation
//! Quote abstraction and generational identifiers.

use std::sync::atomic::{AtomicU64, Ordering};
use thiserror::Error;

/// Core errors for market storage and handles.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
pub enum CoreError {
    /// Attempted to access an invalid or deallocated handle.
    #[error("Invalid or stale handle (index: {index}, generation: {generation})")]
    StaleHandle {
        /// Index of handle
        index: u32,
        /// Generation of handle
        generation: u32,
    },
}

/// A generational identifier for quotes and market observables in an arena.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct QuoteId {
    /// Slot index in the arena
    pub index: u32,
    /// Generation counter to prevent ABA stale handle issues
    pub generation: u32,
}

/// Common trait for all market observables (e.g. spot price, FX rate, index level).
pub trait Quote: Send + Sync {
    /// Return the current numeric value of the quote.
    fn value(&self) -> f64;

    /// Return true if the quote currently holds a valid numeric value.
    fn is_valid(&self) -> bool;

    /// Return the monotonic revision counter of this quote.
    fn revision(&self) -> u64;
}

/// A simple in-memory quote holding a single floating point value and a monotonic revision stamp.
///
/// Thread-safe (`Send + Sync`) via atomic revision counter and internal mutability.
///
/// # Examples
/// ```
/// use quantlib_rs::core::quote::{Quote, SimpleQuote};
///
/// let quote = SimpleQuote::new(100.0);
/// assert_eq!(quote.value(), 100.0);
/// assert_eq!(quote.revision(), 0);
///
/// quote.set_value(102.5);
/// assert_eq!(quote.value(), 102.5);
/// assert_eq!(quote.revision(), 1);
/// ```
#[derive(Debug)]
pub struct SimpleQuote {
    value: std::sync::RwLock<f64>,
    revision: AtomicU64,
}

impl SimpleQuote {
    /// Create a new SimpleQuote with the given initial value.
    pub fn new(val: f64) -> Self {
        Self {
            value: std::sync::RwLock::new(val),
            revision: AtomicU64::new(0),
        }
    }

    /// Set a new value and advance the monotonic revision stamp.
    pub fn set_value(&self, new_val: f64) {
        let mut lock = self.value.write().expect("RwLock write lock");
        *lock = new_val;
        self.revision.fetch_add(1, Ordering::SeqCst);
    }
}

impl Quote for SimpleQuote {
    #[inline]
    fn value(&self) -> f64 {
        *self.value.read().expect("RwLock read lock")
    }

    #[inline]
    fn is_valid(&self) -> bool {
        let v = self.value();
        v.is_finite()
    }

    #[inline]
    fn revision(&self) -> u64 {
        self.revision.load(Ordering::SeqCst)
    }
}