serial_int 0.2.1

Safe, easy-to-use auto-increment integers
Documentation
use crate::Serial;

use std::{
    fmt,
    fmt::{Display, Formatter},
};

/// A utility for generating instances of a given [Serial] type.
///
/// See the [crate] documentation for more information.
#[derive(Clone, Debug)]
pub struct SerialGenerator<T: Serial = u32> {
    value: T,
}

impl<T: Serial> SerialGenerator<T> {
    /// Create a new generator.
    pub fn new() -> Self {
        Self::default()
    }

    /// Create a new generator with the given value.
    ///
    /// [Serial::START] is always considered the first value. If this method is
    /// used with a greater value, [SerialGenerator::previous] may give an
    /// unexpected answer because the "previous" value is calculated, not
    /// recorded.
    pub fn with_init_value(value: T) -> Self {
        SerialGenerator { value }
    }

    /// Generate a new instance of the generator's [Serial] type.
    ///
    /// Relies on [Serial::next_increment].
    pub fn generate(&mut self) -> T {
        let current = self.value.clone();
        let next = current.next_increment();
        self.value = next;

        current
    }

    /// Return the previously generated value.
    ///
    /// This method will return None if the current value is [Serial::START].
    ///
    /// The return value is calculated, not recorded. If the highest possible
    /// value has been reached, this method will continue to return one less
    /// than that value. To check that unique values can still be generated, use
    /// [SerialGenerator::remaining_increments].
    ///
    /// Relies on [Serial::prev_increment].
    pub fn previous(&self) -> Option<T> {
        if self.value == T::START {
            None
        } else {
            Some(self.value.prev_increment())
        }
    }

    /// Return the number of unique values that can still be generated by this
    /// generator.
    ///
    /// Relies on [Serial::remaining_increments].
    pub fn remaining_increments(&self) -> T {
        self.value.remaining_increments()
    }

    /// Return a boolean representing whether unique values can still be
    /// generated.
    ///
    /// Relies on [Serial::remaining_increments].
    pub fn has_remaining_increments(&self) -> bool {
        self.value.is_max_value()
    }
}

impl<T: Serial> Default for SerialGenerator<T> {
    fn default() -> Self {
        SerialGenerator { value: T::START }
    }
}

impl<T: fmt::Debug + Display + Serial> Display for SerialGenerator<T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{:?}", self)
    }
}

impl<T: Serial> Iterator for SerialGenerator<T> {
    type Item = T;

    fn next(&mut self) -> Option<Self::Item> {
        let next_value = self.generate();

        Some(next_value)
    }
}