src/logger.rs

Fri, 06 Dec 2024 16:14:41 -0500

author
Tuomo Valkonen <tuomov@iki.fi>
date
Fri, 06 Dec 2024 16:14:41 -0500
branch
dev
changeset 55
7b2ee3e84c5f
parent 50
4bc24abe77c5
permissions
-rw-r--r--

Add "nightly" feature and provide alternative low-performance implementations of several things when not available.

/*!
Logging routines for intermediate computational results.
*/

use serde::Serialize;
use crate::tabledump::TableDump;

/// A log of items of type `T` along with log configuration.
/// The constructor takes no arguments;  create the log with `Log{T}()` for `T` your
/// data type, e.g., `Float64`.
#[derive(Debug, Clone)]
pub struct Logger<V> {
    data : Vec<V>,
}

impl<V> Logger<V> {
    /// Create new log
    pub fn new() -> Logger<V> {
        Logger{ data : Vec::new() }
    }

    /// Store the value `v` in the log.
    pub fn log(&mut self,  v : V) -> () {
        self.data.push(v);
    }

    /// Get the logged data as a [`Vec`] array.
    pub fn data(&self) -> &Vec<V> {
        &self.data
    }

    /// Map the log with `g`.
    pub fn map<W>(self, g : impl FnMut(V) -> W) -> Logger<W> {
        Logger { data : self.data.into_iter().map(g).collect() }
    }
}

impl<'a, V : Serialize + 'a> TableDump<'a> for Logger<V> {
    type Iter = std::slice::Iter<'a, V>;

    fn tabledump_entries(&'a self) -> Self::Iter {
        self.data.iter()
    }
}

mercurial